Hi I am student developer. I facing an error like this
ERROR in ./src/index.js 5:16 Module parse failed: Unexpected token
(5: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 | import App from
'../src/components/App' |
ReactDOM.render(,document.getElementById("app")); i 「wdm」: Failed to compile.
I am starting to learn webpack what it is but I do not have enough information about solving this. Could you help me at this issue to solve ?
package.json Dev Part :
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.42.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.10.3"
}
My webconfig :
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.export = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
use : {
loader : 'babel-loader'
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
index.js
import React from 'react';
import ReactDOM from 'react-dom'
import App from '../src/components/App'
// Error is he
ReactDOM.render(<App />,document.getElementById("app"));
App.js:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
export default App;
There are two mistakes in your webpack configuration, which is causing this issue.
There is a typo error. Change module.export to module.exports (This one drive me crazy man :P)
As #Muhammad mentioned, you need to mention webpack to compile the react. So, I have added '#babel/react' as presets for the babel-loader.
Below is the webpack that is working for me:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test : /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [
'#babel/react',
]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
Hope it helps :)
You need to tell webpack that you are compiling react. You need to update your rule as:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry : './src/index.js',
output : {
path:path.join(__dirname,'/dist') ,
filename:'index_bundle.js'
},
module:{
rules : [{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ["react"]
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template:'./src/index.html'
})
]
}
Related
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'm writing a React component library which I want to use in other projects without much overhead ( bit, create-react-library, generact, etc. ) and without publishing. I want to use npm install ../shared_lib to add it to my project as a symlink in /node_modules. This command adds the symlink to project node_modules. In my shared_lib I just have a test to export default a <div></div>:
import React from 'react';
const TryTest = function() {
return (
<div>
TryTest
</div>
)
}
export default TryTest;
The problem I'm facing is the following error when I import the component into my working project:
import TryTest from 'shared_lib';
Error:
ERROR in ../shared_lib/src/index.js 6:4
Module parse failed: Unexpected token (6:4)
You may need an appropriate loader to handle this file type.
| const TryTest = function() {
| return (
> <div>
| TryTest
| </div>
# ./src/App.js 27:0-33 28:12-19
# ./src/index.js
# multi babel-polyfill ./src/index.js
If I import anything from shared_lib other than a file with jsx - for example, a string or a function, etc. - it works fine.
EDIT: the application webpack has resolve object's symlinks prop set to false:
resolve: {
symlinks: false
},
EDIT: After applying the solution in the answer below (https://stackoverflow.com/a/60980492/3006493), I later changed symlinks prop back to true. I didn't need to set it to false for the solution to work and render shared_lib components.
My app's loader:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ 'babel-loader' ]
}
EDIT: When I applied the solution in the answer below, the loader now looks like this:
{
test: /\.jsx?$/,
include: [
path.join( __dirname, 'src'), // app/src
fs.realpathSync(__dirname + '/node_modules/shared_lib'), // app/node_modules/shared_lib/dist/shared_lib.js
],
exclude: /node_modules/,
use: [ {
loader: 'babel-loader',
options: require("./package.json").babel
}
]
}
App's current .babelrc settings (I also tried removing .babelrc and including the presets in package.json with same result):
{
"presets": [ "#babel/preset-react", "#babel/preset-env"]
}
**EDIT: After applying the solution in the answer below, I ended up putting babel presets back into package.json.
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
},
I researched for a while to find a solution to this and apparently webpack has issues bundling symlinked react components? I am not using create-react-app.
So, I tried to bundle the shared_lib before importing it into the project, just to see what would happen. Here's the final webpack config (I tried other configurations as well):
const pkg = require('./package.json');
const path = require('path');
const buildPath = path.join( __dirname, 'dist' );
const clientPath = path.join( __dirname, 'src');
const depsPath = path.join( __dirname, 'node_modules');
const libraryName = pkg.name;
module.exports = [
'cheap-module-source-map'
].map( devtool => ({
bail: true,
mode: 'development',
entry: {
lib : [ 'babel-polyfill', path.join( clientPath, 'index.js' ) ]
},
output: {
path: buildPath,
filename: 'shared_lib.js',
libraryTarget: 'umd',
publicPath: '/dist/',
library: libraryName,
umdNamedDefine: true
},
// to avoid bundling react
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
}
},
module: {
rules: [
{
test: /\.jsx?$/,
include: [
clientPath
],
exclude: /node_modules/,
use: [ 'babel-loader' ],
},
]
},
devtool,
optimization: {
splitChunks: {
chunks: 'all',
},
}
}));
And the package.json for the shared_lib
{
"name": "shared_lib",
"version": "1.0.0",
"description": "",
"main": "dist/shared_lib.js",
"scripts": {
"clean": "rm -rf dist/",
"build": "$(npm bin)/webpack --config ./webpack.config.js",
"prepublish": "npm run clean && npm run build"
},
"author": "",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.6"
},
"devDependencies": {
"react": "^16.8.6",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"webpack": "^4.42.1",
"webpack-cli": "^3.3.11"
},
"babel": {
"presets": [
"#babel/preset-react",
"#babel/preset-env"
]
}
}
The package is bundled without errors:
When I try to import the component in the same way:
import TryTest from 'shared_lib';
The console.log returns undefined.
The path to the library file in my app is fine, because if I erase everything in shared_lib/dist/shared_lib.js and just write export default 1 the console.log(TryTest) in my App.js will return 1.
I tried changing libraryTarget property in shared_lib/webpack.config to libraryTarget: 'commonjs'. The result of console.log(TryTest) becomes {shared_lib: undefined}.
Has anyone ever run into this?
I found what finally worked for me and rendered the symlinked shared_lib to the app.
This answer: https://github.com/webpack/webpack/issues/1643#issuecomment-552767686
Worked well rendering symlinked shared_lib components. I haven't discovered any drawbacks from using this solution, but it's the only one that worked so far.
I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,
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.
Getting the following exception when starting the npm.
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.module has an unknown property 'loaders'. These properties are valid:
object { exprContextCritical?, exprContextRecursive?, exprContextRegExp?, exprContextRequest?, noParse?, rules?, defaultRules?, unknownContextCritical?, unknownContextRecursive?, unknownContextRegExp?, unknownContextRequest?, unsafeCache?, wrappedContextCritical?, wrappedContextRecursive?, wrappedContextRegExp?, strictExportPresence?, strictThisContextOnImports? }
-> Options affecting the normal modules (NormalModuleFactory).
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
loaders: [
{
test:/\.jsx?$/,
loaders:'babel-loader',
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
After the updations the code is running but react components are not getting rendered on the screen.
//Update
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test title</title>
</head>
<body>
<div id ="content">
<h1>This is the demo of your web page</h1>
</div>
<script src ="transpiled.js"></script>
</body>
</html>
//webpack config
var path= require('path');
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,'react/index.html'),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test: /\.jsx?$/,
loaders: 'babel-loader',
//use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
//script.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class MyComponent extends React.Component {
render() {
return (
<h2>Hello World !!!</h2>
);
}
}
ReactDom.render(
<MyComponent/>,document.getElementById('content')
);
//package.json
{
"name": "reactjs",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"it": "webpack-dev-server --hot"
},
"author": "chetan",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-middleware": "^3.1.2",
"webpack-dev-server": "^3.1.3",
"webpack-hot-middleware": "^2.21.2"
},
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"webpack-sources": "^1.1.0"
}
}
You need to replace keyword loaders to keyword rules. And in each rules object replace loaders to keyword use.
module.exports = {
entry : './script.jsx',
output : {
path : path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module : {
rules: [ // rules rules
{
test:/\.jsx?$/,
use:'babel-loader', // use here
exclude : /node_modules/,
query : {
presets : ['es2015','react']
}
}
]
}
}
Edit
Now your component not rendered on the screen because output.path in webpack config incorrect. It should be like this:
output : {
path : path.resolve(__dirname),
filename: 'transpiled.js'
}
Because script tag in your html reference in root of the project:
<script src="transpiled.js"></script>
Your webpack.config file is in the wrong format
var path = require('path');
module.exports = {
entry: './script.jsx',
output: {
path: path.resolve(__dirname, ''),
filename: 'transpiled.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: 'babel-loader',
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
// your preset
]
}
}
]
}
]
}
}
See more here