Error when I tried to upgrade from webpack3 to webpack4 - reactjs

I'm getting this below error when I upgraded my project from webpack 3.x to webpack 4.0.0
ERROR in multi script-loader!jquery/dist/jquery.min.js script-loader!foundation-sites/dist/js/foundation.min.js eventsource-polyfill webpack-hot-middleware/client?reload=true ./src/index.jsx
Module not found: Error: Can't resolve 'babel-loader' in 'C:\projects\rebasing\uisrc'
# multi script-loader!jquery/dist/jquery.min.js script-loader!foundation-sites/dist/js/foundation.min.js eventsource-polyfill webpack-hot-middleware/client?reload=true ./src/index.jsx
The rules configurations is as shown below in config file
rules: [
{
test: /\.(jsx?)$/,
use: 'babel-loader',
exclude: /node_modules/,
},
]
Package.json have following libraries
"devDependencies": {
"babel-cli": "6.26.0",
"babel-core": "6.8.0",
"babel-eslint": "7.0.0",
"babel-loader": "7.1.5",
"babel-preset-es2015": "6.6.0",
"babel-preset-react": "6.5.0",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-0": "6.5.0",
"babel-preset-stage-2": "6.17.0",
"babel-register": "6.26.0",
}
Any help would be appreciated.

In webpack4 the configuration should be loader: "babel-loader" but not use: "babel-loader"
rules: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.(jsx?)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
]
Here is my working demo of webpack4
Versions I am using
"webpack": "^4.15.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server":"^3.1.4",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-polyfill": "^6.26.0", "babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");
const webpack = require('webpack');
module.exports = {
target: "web",
entry: [
"whatwg-fetch",
'webpack-dev-server/client?http://localhost:8090',
'webpack/hot/only-dev-server',
'babel-polyfill',
"./src/index.js"
],
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js",
publicPath: "/"
//make sure port 8090 is used when launching webpack-dev-server
},
plugins: [new HtmlWebpackPlugin({
template: "index.html"
}),
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.jsx$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
}),
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.NoEmitOnErrorsPlugin(),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
})
],
module: {
rules: [
{
//tell webpack to use jsx-loader for all *.jsx files
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|jpg|jpeg|gif|woff|woff2|svg)$/,
loader: 'url-loader?limit=100000'
},
{
test: /\.(eot|ttf)$/,
loader: "file-loader"
},
{
test: /\.html$/,
exclude: /node_modules/,
loader: 'html-loader'
},
{
test: /\.scss$/,
loaders: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
},
devServer: {
watchOptions: {
// Needed for Windows Subsystem for Linux dev environment:
poll: true
},
contentBase: "/build"
},
devtool: "cheap-module-eval-source-map",
node: {
child_process : "empty",
fs: "empty"
}
};

Try clearing your node_modules cache and re-installing if you haven't yet:
rm -rf node_modules/
rm -rf ~/.npm
npm cache verify
npm install

Related

Webpack not recognizing npm module that starts with '#'

I am trying to move from a CRA app to using webpack, but having trouble with the loaders.
I have npm modules that start with '#', including but not limited to #material-ui/core/styles.
Removal of this '#' is not an option, I need to figure out how to get around this error.
The error I am seeing it this:
ERROR in ./node_modules/#connect/nav/lib/Canvas/index.js 116:17
Module parse failed: Unexpected character '#' (116:17)
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
|
| "use strict";
> module.exports = #material-ui/core/styles;
My webpack.config.js is
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js',
publicPath: '/'
},
resolve: {
modules: [path.join(__dirname, 'src'), 'node_modules'],
alias: {
react: path.join(__dirname, 'node_modules', 'react'),
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
{
test: /\.svg$/,
use: {
loader: 'svg-url-loader',
options: {
encoding: 'base64'
}
}
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loader: 'file-loader',
options: {
name: '/public/assets/[name].[ext]'
}
}
],
},
plugins: [
new HtmlWebPackPlugin({
template: './public/index.html',
}),
],
devServer: {
historyApiFallback: true,
}
};
Using the following packages:
"#babel/core": "^7.19.1",
"#babel/preset-env": "^7.19.1",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^8.2.5",
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"

ReferenceError: [BABEL] Unknown option: base.__esModule

i am trying react lazy component loading ,that will load component separately and then I got
unexpected token import
i changed my babel file and now error is
ReferenceError: [BABEL] E:\projectSir\latestProject1\tools\startMsg.js: Unknown option: base.__esModule. Check out http://babeljs.io/docs/usage/options/ for more info
at Logger.error (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\logger.js:43:11)
at OptionManager.mergeOptions (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\options\option-manager.js:307:20)
at OptionManager.init (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\options\option-manager.js:506:10)
at File.initOptions (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\index.js:243:89)
at new File (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\file\index.js:159:72)
at Pipeline.transform (E:\projectSir\latestProject1\node_modules\babel-core\lib\transformation\pipeline.js:49:16)
at Object.transformFileSync (E:\projectSir\latestProject1\node_modules\babel-core\lib\api\node.js:152:10)
at compile (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:129:20)
at loader (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:158:14)
at Object.require.extensions.(anonymous function) [as .js] (E:\projectSir\latestProject1\node_modules\babel-register\lib\node.js:168:7)
my babel file is
{
"plugins": ["syntax-dynamic-import"],
"presets": ["env","react","es2015"],
"env": {
"development": {
"presets": [
"react-hmre"
]
}
}
}
my react code for this is
async loadLazyComponent () {
if(this.state.animation == null){
try{
const LazyComponent = await import('./animation.js')
this.setState({animation:React.createElement(LazyComponent.default)})
}catch(e){
this.setState({animation:<div>`failed ${e}`</div>})
}
}
}
and package.json file is
"babel-polyfill": "6.8.0",
"babel-preset-env": "^1.6.1",
and devDependencies are
"babel-cli": "^6.8.0",
"babel-core": "6.8.0",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-preset-es2015": "6.6.0",
"babel-preset-es2016": "^6.24.1",
"babel-preset-react": "6.5.0",
"babel-preset-react-hmre": "1.1.1",
"babel-register": "6.8.0",
and webpack.confg.dev.js file is
import webpack from 'webpack';
import path from 'path';
export default {
debug: true,
devtool: 'inline-source-map',
noInfo: false,
entry: [
'eventsource-polyfill', // necessary for hot reloading with IE
'webpack-hot-middleware/client?reload=true', //note that it reloads the page if hot module reloading fails.
path.resolve(__dirname, 'src/index')
],
target: 'web',
output: {
path: __dirname + '/dist', // Note: Physical files are only output by the production build task `npm run build`.
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: path.resolve(__dirname, 'src')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), exclude: /node_modules/, loaders: ['babel','babel-loader']},
{test: /(\.css)$/, loaders: ['style', 'css']},
{test: /\.(jpe?g|gif|svg)$/i, loader: "file-loader?name=/public/icons/[name].[ext]"},
{test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'url?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'}
]
},
node: {
fs: 'empty',
child_process:'empty'
}
};
i am in just learning phase so any help will be appreciated.
**
the error was that i am using older version of webpack, upgrading it
solved my issue.
**
i think code splitting was not allowed or syntax
import('./someModule.js')
is not allowed in webpack 1.X version
now i have webpack 3.X and error is resolved

webpack bundle file is not being generated with no errors

I am new to react, trying to learn webpack configuration. I am using webpack4 for my project, however, after setting up webpack, the bundle files are not generated, neither the js file nor the html file and there is no error.
The output on the console says "compiled successfully". How do i fix this. I have been struggling for about a week and no online resource seems to give me what i want.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;
const paths = {
DIST: path.resolve(__dirname, 'dist'),
SRC: path.resolve(__dirname, 'src'),
JS: path.resolve(__dirname, 'src/js')
}
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "./index.html"
});
module.exports = {
mode: 'development',
entry: path.join(paths.JS, 'index.js'),
output: {
path: paths.DIST,
filename: 'app.bundle.js'
},
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options:{
modules: true,
importLoaders: 1,
localIndentName: "[name]_[local]_[hash:base64]",
sourceMap: true,
minimize: true,
camelCase:true
}
}
]
}
]
},
plugins: [htmlPlugin],
devServer: {
publicPath: paths.DIST,
host: 'localhost',
port: port,
historyApiFallback: true,
open:true,
hot: true
}
};
Make sure all path correctly, not have missing file.
src/js/index.js
src/index.html
make sure run webpack correctly to show log like:
package.json
"scripts": {
"start": "webpack --config webpack.config.js --bail --progress --profile"
},
and run by npm start, then will show the log.
if you want, you can use new babel version. change your bable with this:
"dependencies": {
"#babel/core": "^7.0.0-beta.42",
"#babel/preset-env": "^7.0.0-beta.42",
"babel-eslint": "^8.0.3",
"babel-loader": "^8.0.0-beta.0",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^3.1.0",
...
"style-loader": "^0.20.3",
"webpack": "^4.4.1",
"webpack-cli": "^2.0.13"
},
.babelrc
{
"presets": ["#babel/preset-env"],
"plugins": ["#babel/plugin-proposal-object-rest-spread"]
}
then update your webpack rule:
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-proposal-object-rest-spread')]
}
},
exclude: /node_modules/
},

Webpack3 unable to parse JSX files

I have the following configuration for a react based application that is failing JSX parsing during webpack build:
ERROR in ./src/App.jsx
Module parse failed: /Users/sangupta/git/plx/ui2/src/App.jsx Unexpected token (9:15)
You may need an appropriate loader to handle this file type.
|
| render() {
| return <div class='hello'>Hello World</div>;
| }
|
# multi (webpack)-dev-server/client?http://localhost:9000 webpack/hot/dev-server src/App.jsx
Any suggestions on what might be wrong?
The following is the package.json file:
{
"name": "Test-Project",
"version": "0.1.0",
"private": true,
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"css-loader": "0.28.4",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.30.1",
"less": "2.7.1",
"less-loader": "2.2.3",
"postcss-loader": "2.0.5",
"style-loader": "0.13.2",
"webpack": "3.4.1",
"webpack-dev-server": "2.6.1"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
},
"scripts": {
"build": "webpack",
"build-production": "NODE_ENV=production npm run build",
"watch": "webpack-dev-server --hot --progress"
}
}
The following is webpack.config.json file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
context: __dirname,
entry: {
app: 'src/App.jsx',
vendor: [ "react", "react-dom" ]
},
devServer: {
contentBase: path.join(__dirname, 'assets'),
compress: true,
port: 9000,
hot: true,
https: false,
noInfo: false,
historyApiFallback: true
},
resolve: {
extensions: [ '.js', '.jsx' ],
alias: {
src: './src'
},
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
module: {
rules: []
},
// Tell webpack to use html plugin
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
new webpack.ProvidePlugin({
'React': 'react',
}),
new UglifyJsPlugin({ sourceMap: !isProduction }),
new HtmlWebpackPlugin({ title: 'MultiPLX', template: 'src/index.ejs', inject : 'body' })
]
};
You should be using the react babel preset:
npm install --save-dev babel-preset-react
webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "src")
],
exclude: /node_modules/,
loader: [
'babel-loader',
],
options: {
presets: [ "react", "es2015" ]
}
},
{
test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3|css)$/,
use: [
"file-loader"
]
}
]
},

Having an issue when configuring HotModuleReplacement in webpack 2

I'm trying to integrate HotModuleReplacement and following this boilerplate, but is not working with my webpack configuration.
The "issue" I am having is in the output.publicPath entry. Following the example I mentioned, that line is "necessary for HMR to know where to load the hot update chunks", but when I include it in my webpack config it gives me this error GET http://localhost:3000/ 404 (Not Found). If I don't include it, webpack compiles everything successfully, but HMR does not work even though when I look at the console I get this
[WDS] App hot update...
dev-server.js:45 [HMR] Checking for updates on the server...
log-apply-result.js:20 [HMR] Updated modules:
log-apply-result.js:22 [HMR] - ./src/components/App.js
dev-server.js:27 [HMR] App is up to date.
Below is webpack.config.js file.
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static/'
},
devtool: 'inline-source-map',
module: {
rules: [
{ test: /\.(js)$/, exclude: /node_modules/, use: ['react-hot-loader/webpack', 'babel-loader'] },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(png|jpg)$/, loader: 'file-loader?name=images/[name].[hash].[ext]' },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/font-woff'},
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]&mimetype=application/octet-stream'},
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[hash].[ext]'},
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=images/[name].[hash].[ext]&mimetype=image/svg+xml' }
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({ template: 'public/index.html', favicon: 'public/favicon.ico' })
],
devServer: {
host: 'localhost',
port: 3000,
historyApiFallback: true,
hot: true
}
}
What am I missing?
These are my project dependencies just in case
"dependencies": {
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-prop-types": "^0.4.0",
"semantic-ui-css": "^2.2.10",
"semantic-ui-react": "^0.68.3"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"css-loader": "^0.28.1",
"file-loader": "^0.11.1",
"html-webpack-plugin": "^2.28.0",
"react-hot-loader": "next",
"style-loader": "^0.17.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
}
EDIT
I got it working. I changed publicPath to publicPath: '/' and added {"modules": false} to my .babelrc file
Below is my .babelrc file
{
"presets": [["env",{"modules": false}], "react", "stage-1"]
}
I guess I have a new question, what does {"modules": false} mean? what it is used for?
.babelrc is the configuration for the babel transpiler.
"Setting this to false will not transform modules.".
source: https://babeljs.io/docs/plugins/preset-es2015/#options

Resources