I am trying to use async and await in my react application.
onSubmit = async (model) => {
await this.setState({ data: model });
}
After adding the above code i get an error in my browser console.
ReferenceError: regeneratorRuntime is not defined
.babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties"
],
"sourceMaps": "inline"
}
webpack.config.js
const path = require("path");
const WebpackShellPlugin = require("webpack-shell-plugin");
const nodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = [
{
Server config removed
},
{
entry: {
app1: './src/public/app1/index.js',
app2: './src/public/app2/index.js',
app3: './src/public/app3/index.js',
},
devtool: "source-map",
output: {
path: __dirname + '/dist/public/',
publicPath: '/',
filename: '[name]/bundle.js',
devtoolLineToLine: true,
sourceMapFilename: "[name]/bundle.js.map",
},
module: {
rules: [
{
test: /(\.css|.scss)$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
},
{
test: /\.(jsx|js)?$/,
use: [{
loader: "babel-loader",
// options: {
// cacheDirectory: true,
// presets: ['react', 'es2015'] // Transpiles JSX and ES6
// }
}]
}
],
},
"plugins": [
new CopyWebpackPlugin([
{
from: 'src/public/app1/index.html',
to: 'app1'
},
{
from: 'src/public/app2/index.html',
to: 'app2'
},
{
from: 'src/public/app3/index.html',
to: 'app3'
},
]),
]
}
];
I have added my babelrc and webpack config. Please let me know if i am missing something that would cause this error to appear in my browser console.
Import regeneratorRuntime in the component using async/await:
import regeneratorRuntime from "regenerator-runtime";
*** UPDATED ANSWER *** (probably don't use above)
Import babel and #babel/plugin-transform-runtime plugin:
package.json
"devDependencies": {
"#babel/core": "^7.8.7",
"#babel/plugin-transform-runtime": "^7.8.3",
},
.babelrc
{
"plugins": ["#babel/plugin-transform-runtime"]
}
You did not include your package.json file, so it is a bit unclear what you are missing.
Assuming you have #babel/polyfill as a dependency in your package.json file, is it possible that you are not specifying:
import '#babel/polyfill'
in your React file (such as index.js)?
Adding polyfills from create-react-app worked for me.
yarn add --dev react-app-polyfill
Then add the following lines to webpack.config.js
entry: {
app: [
'react-app-polyfill/ie9', // Only if you want to support IE 9
'react-app-polyfill/stable',
'./src/index.jsx',
],
},
See more examples on the react-app-polyfill GitHub page.
Related
If you install the official npm package, it works.
But according to the official documentation and simply including import { Viewer } from "forge-dataviz-iot-react-components" (like in this example) in a empty new react project (using npx create-react-app) you will get this error:
./node_modules/forge-dataviz-iot-react-components/client/components/BasicTree.jsx 107:16
Module parse failed: Unexpected token (107:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| if (node.children.length > 0) {
| return (
> <TreeItem
| id={`tree-node-${node.id}`}
| key={node.id}
Which loader do I need to add on webpack to avoid this error?
it is not possible to include the package https://www.npmjs.com/package/forge-dataviz-iot-react-components inside a react project made with npx create-react-app (hoping Autodesk is going to fix this problem soon).
You need to edit /node_modules/react-scripts/config/webpack.config.js in 2 parts:
one line about PIXI
...
alias: {
'PIXI': "pixi.js/",
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
...
and another part about /forge-dataviz-iot-react-component
...
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
{
test: /forge-dataviz-iot-react-component.*.jsx?$/,
use: [
{
loader: require.resolve('babel-loader'),
options: {
presets: ["#babel/react", ["#babel/env", { "targets": "defaults" }]],
plugins: ["#babel/plugin-transform-spread"]
}
},
],
exclude: path.resolve(__dirname, "node_modules", "forge-dataviz-iot-react-components", "node_modules"),
},
// TODO: Merge this config once `image/avif` is in the mime-db
// https://github.com/jshttp/mime-db
{
test: [/\.avif$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
mimetype: 'image/avif',
name: 'static/media/[name].[hash:8].[ext]',
},
},
...
after that on /node_modules/forge-dataviz-iot-react-components/client/components/Viewer.jsx you will get errors about undefined Autodesk variable easily fixable changing Autodesk with window.Autodesk.
Although you will not see any other errors, the package will not work.
I recently tried this package and I got the same problem.
So I created a React project from scratch without CRA and followed the webpack.config.js of this repo : Forge Dataviz IOT Reference App
Here's my webpack.config.js file :
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
PIXI: path.resolve(__dirname, "node_modules/pixi.js/"),
},
},
devServer: {
port: process.env.PORT || 3000
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{ loader: "babel-loader" }
]
},
{
test: /forge-dataviz-iot-react-component.*.jsx?$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/react", ["#babel/env", { "targets": "defaults" }]],
plugins: ["#babel/plugin-transform-spread"]
}
},
],
exclude: path.resolve(__dirname, "node_modules", "forge-dataviz-iot-react-components", "node_modules"),
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.svg$/i,
use: {
loader: "svg-url-loader",
options: {
// make loader to behave like url-loader, for all svg files
encoding: "base64",
},
},
},
],
},
plugins: [
new HtmlWebPackPlugin({
template: './src/index.html',
}),
],
};
Update :
If you want to use CRA, you can customise your webpack config using Customize-CRA and create a config-overrides.js like this :
/* config-overrides.js */
const path = require("path");
const {
override,
addExternalBabelPlugins,
babelInclude,
babelExclude,
addWebpackAlias
} = require("customize-cra");
module.exports = override(
babelInclude([
path.resolve("src"), // make sure you link your own source
path.resolve("node_modules")
]),
babelExclude([path.resolve("node_modules/forge-dataviz-iot-react-components/node_modules")]),
addWebpackAlias({
['PIXI']: path.resolve(__dirname, 'node_modules/pixi.js/')
})
);
I managed to make this work on a fresh CreateReactApp project, so you should be able to make it working on your project.
Trying to setup a react-app with all latest versions.
Github Repo Link
Trying to run storybook with sass file imported will result in below error. Trying to run without importing the styles, storybook works.
The same code works correctly when its run as npm start run with no warnings and errors.
I have configured css modules using #dr.pogodin/babel-plugin-react-css-modules with sass, webpack 5, react 17 and with latest packages.
ERROR in ./src/assets/stylesheets/app.scss 1:0
Module parse failed: Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> #import "./base.scss";
| #import "./generics/font.scss";
| #import "./generics/spacing.scss";
# ./stories/index.js 5:0-44 8:2-10:4 8:58-10:3 9:4-49
# ./src/components/atoms/button/stories.js
babel.config.js
module.exports = {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: [
[
"#dr.pogodin/babel-plugin-react-css-modules",
{
webpackHotModuleReloading: true,
autoResolveMultipleImports: true,
filetypes: {
".scss": {
syntax: "postcss-scss",
},
},
generateScopedName: "[name]__[local]___[hash:base64:5]",
},
],
],
};
webpack.config.js for css (partial code inlcuded)
{
test: /\.(css|sass|scss)$/,
exclude: /node_modules/,
use: [
isDev ? "style-loader" : MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: {
auto: (resourcePath) =>
resourcePath.indexOf("assets/stylesheets") === -1,
localIdentName:"[name]__[local]___[hash:base64:5]",
},
sourceMap: true,
},
},
"sass-loader",
],
}
storybook/webpack.config.js file
const custom = require('../webpack.config.js');
module.exports = {
// stories: ['../src/components/**/*.stories.js'],
webpackFinal: (config) => {
return {
...config,
module: {
rules: custom.module.rules,
},
resolve: {
...config.resolve,
...custom.resolve,
}
};
},
};
I don't know what you have done with your configuration but you would define the config things inside .storybook/main.js. And for global style css is supposed to be included in preview.js file.
In short, you have to do the few things:
Remove your .storybook/config.js and add .storybook/main.js with following content:
const custom = require('../webpack.config.js');
module.exports = {
stories: [
'../src/**/stories.js', // The name should have a prefix for component name like `button.stories.js` instead of `stories.js` like you've done. As you renamed, you can remove this pattern
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
webpackFinal: (config) => {
return {
...config,
module: {
rules: custom.module.rules,
},
resolve: {
...config.resolve,
...custom.resolve,
}
};
},
};
Create the .storybook/preview.js to import your global style:
import "../src/assets/stylesheets/app.scss";
Some people have been running into problems a some scss preset when using Storybook 6.2.0 with Webpack 5. Instead of using a preset, I recommend configuring the Webpack config in main.js as mentioned above. Here's the relevant portion of a working Storybook Webpack config for Sass:
module: {
...config.module,
rules: [
...config.module.rules,
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: function () {
return [require('precss'), require('autoprefixer')];
},
},
},
},
{
loader: require.resolve('sass-loader'),
options: {
implementation: require('sass'),
},
},
],
},
],
},
I've written more about getting Storybook off the ground with Webpack 5 (and modifying the Storybook Webpack config) over here.
Another reason this might happen: if you are adding new components to your app and the path defined for your sass-loader does not match anymore.
E.g. if you have this in your .storybook/main.js:
webpackFinal: async config => {
// Add SASS support
// https://storybook.js.org/docs/configurations/custom-webpack-config/#examples
config.module.rules.push({
test: /\.scss$/,
use: [
"style-loader",
{
loader: "css-loader",
options: {
modules: {
compileType: "icss",
},
},
},
"sass-loader",
],
include: path.resolve(__dirname, "../"),
})
Update or completely remove the include path.
I am working on a project with react-leaflet and run into the problem where while building I get this error:
ERROR in ./node_modules/leaflet/dist/leaflet.css 3:0
Module parse failed: Unexpected token (3:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| /* required styles */
|
> .leaflet-pane,
| .leaflet-tile,
| .leaflet-marker-icon,
ℹ 「wdm」: Failed to compile.
As this error started after importing the leaflet.css into my project like this:
import 'leaflet/dist/leaflet.css';
All my imports in this file are:
import React, { PureComponent } from 'react';
import { LatLngExpression } from "leaflet";
import { Map, TileLayer, Marker, Popup, ZoomControl, ScaleControl, Viewport } from 'react-leaflet';
import { Classes } from "jss";
import 'leaflet/dist/leaflet.css';
To solve this I added css-loader, file-loader and style-loader to my project (using yarn).
After that I changed my webpack config to this:
module: {
rules: [{
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
}, {
test: /\.css$/i,
use: [{
loader: 'style-loader'
},{
loader: 'css-loader',
options: {
url: false,
modules: false
}
}]
}]
}
However I still get the same error while building.
I tried several solutions, trying to add url-loader for instance.
Somehow it does not make any difference, I keep getting the same error.
Here is my complete Webpack config. Please understand I am using EJS and node here as well.
import * as path from 'path';
import * as HtmlWebpackPlugin from 'html-webpack-plugin';
import * as ForkTsCheckerWebpackPlugin from 'fork-ts-checker-webpack-plugin';
import { Mode } from './enum/Mode';
import { Languages } from './enum/Languages';
// only when condition is met
const when = (condition:any, returnValue:any) => (condition ? returnValue : undefined);
// remove empty values from object
const removeEmpty = (obj) => {
return Object.keys(obj).reduce((newObj, key) => {
if (obj[key] !== undefined && obj[key] !== null) {
newObj[key] = obj[key];
}
return newObj;
}, {});
};
module.exports = async (env, argv) => {
// get arguments
const { mode = Mode.PRODUCTION } = argv;
// array holding the webpack configs
const webpackConfigs = [];
// get languages from cli arguments
const languages = argv.languages
? argv.languages.split(',')
: 'NL';
// build config for every target in every language
languages.forEach((language) => {
// build the actual config
webpackConfigs.push({
mode,
devtool: 'inline-source-map', // Needed for chrome dev tools
entry: {
app: [
'console-polyfill',
path.resolve(process.cwd(), 'src/index.tsx')
]
},
output: removeEmpty({
publicPath: '/',
path: path.resolve(process.cwd(), `build/${Languages[language]}/`),
filename: mode === Mode.DEVELOPMENT ? '[name].js' : '[name]-[contenthash].min.js'
}),
resolve: {
extensions: [
'.js',
'.jsx',
'.ts',
'.tsx'
],
moduleExtensions: []
},
plugins: [
new HtmlWebpackPlugin({
mobile: true,
inject: false,
title: mode === Mode.PRODUCTION ? 'production' : 'Development',
template: path.resolve(process.cwd(), 'webpack/index.ejs'),
templateOptions: {
language: Languages[language]
}
}),
when(mode === Mode.DEVELOPMENT, // DEVELOPMENT only
new ForkTsCheckerWebpackPlugin()
)
],
devServer: removeEmpty({
disableHostCheck: true, // Security issue
hot: true,
hotOnly: false,
compress: true,
watchContentBase: true,
host: 'localhost',
contentBase: path.resolve(process.cwd(), 'webpack/public'),
port: 8080,
stats: 'minimal',
watchOptions: {
ignored: /node_modules/
}
}),
module: {
exprContextCritical: false,
rules: [
{ // babel javascript/typescript (no type checking), also see ./babel.config.js
test: /\.(js|jsx|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
['#babel/preset-env', {
targets: {
browsers: [
'firefox >= 40',
'chrome >= 49',
'edge >= 12',
'opera >= 47',
'safari >= 9',
'android >= 5',
'ios >= 10'
]
}
}]
]
}
}
},
{ // images
test: /\.(png|svg|jpg|gif)$/,
use: [{
loader: 'file-loader'
}]
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: [{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
url: false, // leaflet uses relative paths
modules: false
}
}],
},
{ // sourcemaps
loader: 'source-map-loader',
exclude: /node_modules/
},
{ // html template
test: /\.ejs$/u,
loader: 'ejs-loader'
}
]
}
});
});
return webpackConfigs;
};
To be complete I am using:
"react": "16.13.1",
"react-dom": "16.13.1",
"react-leaflet": "2.7.0",
"leaflet": "1.6.0",
"#babel/core": "7.9.6",
"babel-loader": "8.1.0",
"css-loader": "3.5.3",
"file-loader": "6.0.0",
"style-loader": "1.2.1",
"webpack": "4.43.0",
"webpack-cli": "3.3.11",
"webpack-dev-server": "3.10.3"
Thanks in advance for the help.
You try to load CSS file as a JS module.
This line is the problem: import 'leaflet/dist/leaflet.css';
Try this instead: import leaflet from 'leaflet'
I had something similar and guessed at the solution. I guess the location it cares about for leaflet is node_modules but I am new at this and can't tell you more than that, only that adding what appears to be a reference to the directory in the webpack.config.js solved the problem. My error message did not include the exact directory with the problem so thank you for this question
In my case the solution looked like this. I added something to the end of the include line to the css rule in the module section of the webpack file. The include line is what you may be needing. Specifically the correct location to the the node_module which is what I added to the end of the include line
{
test: /\.css$/,
include: [APP_DIR, /superset-ui.+\/src/,/superset-ui.+\/node_modules/],
use: [
isDevMode ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: isDevMode,
},
},
],
},
I am able to transpile scss file to css file but the only importing is not working during the build. since *.js its importing a .scss file. I tried replacing .scss with .css during the build.
js still has references to scss files which do not exist in the dist folder as all scss there is distributes as normal css
error :
ERROR in ./src/Checkbox/Checkbox.js
Module not found: Error: Can't resolve './Checkbox.css' in '/src/Checkbox'
# ./src/Checkbox/Checkbox.js 36:0-22
# ./src/index.js**
src/checkbox.js
'use strict';
import {Checkbox} from 'semantic-ui-react';
import * as React from 'react';
import PropTypes from 'prop-types';
// Style
import './Checkbox.scss';
react code...
dist/checkbox.js transpiled JS file (looks like )
var _propTypes2 = _interopRequireDefault(_propTypes);
require('./Checkbox.scss');
**I am expecting require('./Checkbox.css');**
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
and so on ...
*.js its importing a .scss file. I tried replacing .scss with .css during the build
my webpack.config.js
const webpack = require('webpack')
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractLESS_checkbox = new ExtractTextPlugin({
filename: 'component/Checkbox.css',
allChunks: true
});
const config = {
entry : {
index:'./src/index.js'
},
output : {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
pathinfo: true
},
devtool: 'source-map',
module: {
rules: [{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
//enforce: 'pre',
exclude: /node_modules/,
}, {
test: /\.scss$/,
enforce: 'pre',
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
['css-loader', 'resolve-url-loader', 'sass-loader']})
]
},
plugins: [
extractLESS_checkbox
],
externals: {
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
};
module.exports = config;
my package.json
"name": "name",
"version": "0.1",
"description": "Elements",
"author": "dg",
"license": "ISC",
"jsnext:main": "dist/es/index.js",
"main": "dist/commonjs/index.js",
"module": "dist/es/index.js",
"scripts": {
"build": "npm run build:commonjs && npm run build:es",
so on ....
}
"dependencies" : { ...}
"devDependencies" : {... }
Am I doing something wrong, Please suggest me
Use Extract text plugin
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
sourceMap: true,
},
}, {
loader: 'sass-loader',
options: {
sourceMap: true
},
}, {
loader: 'import-glob-loader',
},
]
})
Should look something like this
I have a small app running through webpack dev server (on dev environment).
The hot module replacement is running well, I can see my changes on the fly while I edit my js files.
But as soon as I add the es2015 preset in babel loader config, it stops working !
webpack.config.js :
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
process.env.BABEL_ENV = 'development';
module.exports = {
entry: {
app: ['react-hot-loader/patch', path.join(__dirname, 'src')]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
include: path.join(__dirname, 'src'),
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: ['react'],
},
},
}
]
},
devServer: {
historyApiFallback: true,
quiet: true,
hotOnly: true,
contentBase: './build',
host: 'my-host.local',
port: 8091,
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
},
},
plugins: [
new HtmlWebpackPlugin({
title: 'Webpack demo',
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new FriendlyErrorsWebpackPlugin(),
new webpack.WatchIgnorePlugin([
path.join(__dirname, 'node_modules')
]),
],
};
src/index.js file :
import React from 'react';
import ReactDOM from 'react-dom';
import Component from './Component';
import { AppContainer } from 'react-hot-loader';
const app = document.createElement('div');
document.body.appendChild(app);
const render = App => {
ReactDOM.render(
<AppContainer><App /></AppContainer>,
app
);
};
render(Component);
if (module.hot) {
module.hot.accept('./Component', () => render(Component));
}
Component.js
import React from 'react';
export default class Title extends React.Component {
render() {
return (
<div>Ass</div>
);
}
}
.babelrc
{
"presets": [
[
"react",
"es2015",
{
"modules": false
}
]
],
"env": {
"development": {
"plugins": [
"react-hot-loader/babel"
]
}
}
}
And soon as I replace
presets: ['react'],
by
presets: ['es2015', 'react'],
The Hot Module Replacement feature stops working.. Does anyone has a clue here ?
(also don't hesitate to point at bad practices or avoidable complications in my code)
You need the following .babelrc (I don't know why).
.babelrc
{
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
],
}
Where stage-2 is the npm package babel-preset-stage-2.