Webpack React Babel build it without modernizr - reactjs

👋 hi devs!
I build a ReactJs project with classic ecosystem Webpack and babel.
I need to optimize and control the build resources loaded inside my budles.
Currently I reading included modernizr into a part of bundle under "#license React of react-dom.production.min.js"... who included it? how can I exlude it from my builds?
Can someone understand how can i have more control on sub elements of build? thank you.
dependencies:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.0",
"css-loader": "^6.7.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"http-server": "^14.1.1",
"style-loader": "^3.3.1",
"webpack": "^5.75.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1"
}
and webpack.config...
const HtmlPack = require('html-webpack-plugin')
const HtmlList = [
"index",
"test/secondpage"
]
module.exports = {
//https://stackoverflow.com/questions/70916332/webpack-bundle-files-for-multiple-pages
// entry: { main: [ "./src/index.js", ], test: [ "./src/test/secondpage.js", ], },
entry: HtmlList.reduce( (config, page) => {
config[page] = `./src/${page}.js`;
return config;
},{}),
output: {
path: __dirname+'/public/reactor',
filename: '[name].bundle.js',
clean: true
},
devServer: {
static: __dirname+'/src',
port: 8080,
open: true,
hot: true
},
optimization: {
minimize: false,
// minimizer: [new TerserPlugin({
// extractComments: false,
// })],
removeAvailableModules: true, // detect and remove modules already included
sideEffects: true, // detect and not load the sub libs of module (https://github.com/webpack/webpack/blob/main/examples/side-effects/README.md)
runtimeChunk: 'single', // true = automatic nesting chunks progess, 'multiple', 'single' = one file for all chuncks
removeEmptyChunks: true, // clean & optimize file size
splitChunks: {
chunks: "all"
},
},
module: {
rules: [ {
test: /\.js$/i,
exclude: /node_modules/,
use: [ 'babel-loader' ]
}, {
test: /\.css$/i,
exclude: /node_modules/,
use: [ 'style-loader', 'css-loader' ]
}
, {
test: /\.(jpe?g|png|gif|webp|svg|ico|zip|json)$/i,
exclude: /node_modules/,
loader: 'file-loader',
options: {
name: '[path][name].[ext]'
}
}
]
},
plugins : [].concat(
// https://dev.to/marcinwosinek/tutorial-for-building-multipage-website-with-webpack-4gdk
// https://github.com/jantimon/html-webpack-plugin
HtmlList.map( page => new HtmlPack({
filename: `${page}.html`,
})),
)
}
UPDATE NOTE 01:
FAKE POSITIVE - sorry
After different test i see this: "runtimeChunk" generete a strange no requested inclusion of modernizr and other codes... I don't know why
UPDATE NOTE 02:
It seems that it's included directly via react-dom
/**
* #license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
Modernizr 3.0.0pre (Custom Build) | MIT
*/
var aa=__webpack_require__(294),ca=__webpack_require__(840);function p(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length..... etc
Modernizr 3.0.0pre (Custom Build) | MIT <= wtf???

Related

Unable to start my react application and getting error in webpack server

I don't know where am going wrong
Am not sharing all package.json but whatever required am sharing.
here is my package.json
"scripts": {
"develop": "webpack serve --hot --port 8080 --disable-host-check --config webpack.develop.js",
},
"engines": {
"node": ">=10"
},
"devDependencies": {
"react-hot-loader": "^4.12.20",
"react-test-renderer": "^17.0.1",
"typescript": "4.1.2",
"webpack": "^5.70.0",
"webpack-bundle-analyzer": "^4.2.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
}
web.develop.js
const commonConfig = require('./webpack.config')
module.exports = {
...commonConfig,
output: {
...commonConfig.output,
publicPath: 'http://localhost:8080/',
},
mode: 'development',
module: {
rules: [
...commonConfig.module.rules,
{
test: /\.(js|jsx|ts|tsx)?$/,
use: 'react-hot-loader/webpack',
include: /node_modules/,
},
],
},
devServer: {
index: 'index.html',
hot: "only", // hot:true
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
},
plugins: [...commonConfig.plugins],
}
error:
[webpack-cli] Error: Unknown option '--disable-host-check'
[webpack-cli] Run 'webpack --help' to see available commands and options
if i use this command
"develop": "webpack serve --hot --port 8080 --allowed-hosts all --config webpack.develop.js"
am getting below error
[webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema.
- options has an unknown property 'index'. These properties are valid:
object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?,
onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? }
i removed index and localhost up and running but build.js is not created in dist folder.
webpack.config.js
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')
const dotenv = require('dotenv')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer')
.BundleAnalyzerPlugin
// Create .env file if it does not exist
if (!fs.existsSync('.env')) {
fs.copyFileSync('.env_example', '.env')
}
dotenv.config()
if (!process.env.POSTS_SERVER_URL) {
// webpack 5 is stricter about environment variables. The POSTS_SERVER_URL
// environment variable was not mentioned in the README so default it for
// those developers who may have created a .env file without the variable.
process.env.POSTS_SERVER_URL = 'http://127.0.0.1:3000'
}
const PATHS = {
app: path.join(__dirname, 'src/index.tsx'),
}
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
module: {
rules: [{
test: /\.(js|jsx|ts|tsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/,
sideEffects: false,
},
{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'file-loader'},
{
test: /\.(scss|css)$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: {
localIdentName: "[hash:base64]",
auto: true
},
sourceMap: true
}
},
{
loader: 'sass-loader'
}
]
}
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.css'],
modules: [__dirname,
'node_modules'
],
fallback: { buffer: false },
},
devtool: 'source-map'
}
Can anyone suggest me where is my configuration is going wrong

ERROR in ./node_modules/leaflet/dist/leaflet.css 3:0 > You may need an appropriate loader to handle this file type

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,
},
},
],
},

Webpack 4, babel 7, react, typescript: Unexpected token, expected ","

Error:
ERROR in ./src/client/index.tsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: ***\src\client\index.tsx: Unexpected token, expected "," (5:16)
3 |
4 | const a = {title: 'te'}
> 5 | const x = <span {...a}/>
| ^
6 | console.log(`>>>`, a)
webpack config:
import * as Webpack from 'webpack';
import {Compiler} from 'webpack';
import * as WebpackDevServer from 'webpack-dev-server';
import {paths} from './paths';
import {alias} from './alias';
const domain = ''
const createWebpackConfig = (): Webpack.Configuration => {
const config: Webpack.Configuration = {
mode: 'development',
devtool: 'cheap-module-source-map',
entry: [
'react-hot-loader/patch',
paths.appEntryFile,
],
output: {
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
// This does not produce a real file. It's just the virtual path that is
// served by WebpackDevServer in development. This is the JS bundle
// containing code from all our entry points, and the Webpack runtime.
filename: 'static/js/[name].bundle.js',
// There are also additional JS chunk files if you use code splitting.
chunkFilename: 'static/js/[name].chunk.js',
// This is the URL that app is served from. We use "/" in development.
publicPath: '/',
},
resolve: {
alias,
extensions: ['.tsx', '.ts', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(j|t)sx?$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
babelrc: false,
presets: [
['#babel/preset-env', {
targets: '> 0.25%, not dead',
// Only add polyfills our code might need
useBuiltIns: 'usage',
debug: true,
// Looks like by default bable uses core-js 2 which breaks
corejs: 3,
modules: 'commonjs'
}],
'#babel/preset-react'
],
plugins: [
// To have `private` on class properties. `loose:true` to don't add bloat to the code.
['#babel/plugin-proposal-class-properties', {loose: true}],
// Ability to do: `const enum`
'babel-plugin-const-enum',
// Ability to use typescript, has to be after 'babel-plugin-const-enum' otherwise will complain
['#babel/plugin-transform-typescript', {allowNamespaces: true}],
'react-hot-loader/babel',
],
},
},
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader',
},
],
},
]
},
plugins: [
],
node: {
fs: 'empty',
net: 'empty',
// Because of promise-request
tls: 'empty'
}
}
return config
}
const compiler = Webpack(createWebpackConfig());
const host = '127.0.0.1';
const devServerOptions: WebpackDevServer.Configuration = {
open: false,
host,
hot: true,
stats: {
colors: true,
},
}
const server = new WebpackDevServer(compiler, devServerOptions);
server.listen(3000, host, () => {
console.log('Starting server on http://localhost:3000');
});
index.tsx:
import * as React from 'react';
const a = {title: 'te'}
const x = <span {...a}/>
console.log(`>>>`, a)
partial package.json (plus more crap):
"#babel/core": "^7.8.4",
"#babel/plugin-proposal-class-properties": "^7.8.3",
"#babel/plugin-transform-typescript": "^7.8.3",
"#babel/polyfill": "^7.8.3",
"#babel/preset-env": "^7.8.4",
"#babel/preset-react": "^7.8.3",
"babel-cli": "^6.26.0",
"babel-jest": "^25.1.0",
"babel-loader": "^8.0.6",
"babel-plugin-const-enum": "^0.0.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react-app": "^9.1.1",
I can't figure out why it doesn't work. I have react plugin so it should understand react, "babel-loader": "^8.0.6",
Fixed by adding a babel preset: ['#babel/preset-typescript', {allowNamespaces: true}],
I have no clue why react breaks...
I faced the same issue. To fix this issue I have
to install #babel/preset-typescript by running
yarn add #babel/preset-typescript
to add
['#babel/preset-typescript', {allowNamespaces: true}]
in webpack.config.js like this
rules: [
{
test: /\.[tj]sx?$/,
include: /(src)/,
use: [{
loader: 'babel-loader',
options: {
presets: [
[
'#babel/preset-env',
{
"useBuiltIns": "usage",
"corejs": 3
}
],
['#babel/preset-typescript', { allowNamespaces: true }]
],
plugins: [
'#babel/plugin-syntax-dynamic-import'
]
}
}]
},
{
test: /\.tsx?$/,
include: path.resolve(__dirname, "src"),
use: [{
loader: 'ts-loader',
options: {
transpileOnly: true
}
}]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: [{
loader: 'url-loader',
options: {
limit: 10000,
}
}]
}
]

webpack react development mode

I am not able to configure Webpack with react in development mode.
Here is my package JSON :
...
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"gulp": "^4.0.0",
"gulp-sass": "^4.0.1",
"webpack": "^4.12.2",
"webpack-stream": "^4.0.3"
}
...
I am getting this error in the browser :
Uncaught Error: Minified React error #37; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=37 for the full message or use the non-minified dev environment
When I set web pack to mode development :
const DIR_PAGES = path.join(__dirname, 'pages');
const DIR_TARGET = path.join(__dirname, '..', 'assets');
const DIR_TARGET_PAGES = path.join(__dirname, '..', 'assets', 'pages');
module.exports = {
mode: "development",
/**
* DEFINE PAGES JS HERE
*/
entry: {
'test' : path.join(DIR_PAGES, 'test', 'test.js'),
},
resolve: {
extensions: ['.js', '.jsx']
},
/**
* HOW TO TRANSCODE JAVASCRIPT
*/
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
}
]
},
/**
* OUTPUT LOCATION
*/
output: {
path: DIR_TARGET_PAGES,
filename: '[name]/[name].js'
},
};
I am building using webpack-stream. here is my build task :
const webpack_stream = require('webpack-stream');
const webpack_config = require('./webpack.config.js');
gulp.task('webpack', function() {
return webpack_stream(webpack_config)
.pipe(gulp.dest(DIR_TARGET_JS));
});
I am getting this error while building web pack using gulp :
[13:57:12] 'webpack' errored after 161 ms
[13:57:12] WebpackOptionsValidationError: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration has an unknown property 'mode'. These properties are valid:
object { amd?, bail?, cache?, context?, dependencies?, devServer?, devtool?, entry, externals?, loader?, module?, name?, node?, output?, parallelism?, performance?, plugins?, profile?, recordsInputPath?, recordsOutputPath?, recordsPath?, resolve?, resolveLoader?, stats?, target?, watch?, watchOptions? }
For typos: please correct them.
For loader options: webpack 2 no longer allows custom properties in configuration.
Loaders should be updated to allow passing options via loader options in module.rules.
Until loaders are updated one can use the LoaderOptionsPlugin to pass these options to the loader:
plugins: [
new webpack.LoaderOptionsPlugin({
// test: /\.xxx$/, // may apply this only for some modules
options: {
mode: ...
}
})
]
...
I don't know what to do can you help me please
Thank you

Webpack production build: Unexpected token

I have been trying to deploy my production build with webpack but I can't get it done. I almost read and tried everything and can't make it work.
This is the last error that I have:
My webpack configuration looks like this:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname, 'src');
const buildPath = path.join(__dirname, 'dist');
module.exports = {
devtool: 'cheap-module-source-map',
entry: {
// base: path.resolve(staticSourcePath, 'src/sass/base.scss'),
app: path.resolve(sourcePath, 'index.prod.jsx')
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
sourcePath,
path.resolve(__dirname, 'node_modules')
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[chunkhash].js',
minChunks(module) {
return module.context && module.context.indexOf('node_modules') >= 0;
}
}),
new UglifyJsPlugin({
sourceMap: true,
uglifyOptions: {
ecma: 8,
compress: {
warnings: false
}
}
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({
browsers: [
'last 3 version',
'ie >= 10'
]
})
],
context: staticSourcePath
}
}),
new webpack.HashedModuleIdsPlugin(),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src', 'index.html'),
path: buildPath,
excludeChunks: ['base'],
// filename: 'index.html',
minify: {
collapseWhitespace: true,
collapseInlineTagWhitespace: true,
removeComments: true,
removeRedundantAttributes: true
}
}),
new PreloadWebpackPlugin({
rel: 'preload',
as: 'script',
include: 'all',
fileBlacklist: [/\.(css|map)$/, /base?.+/]
}),
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
new ExtractTextPlugin({
filename: '[name].[contenthash].css',
allChunks: true
}),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.jsx$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
],
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: /node_modules/,
query: {
presets: ["es2015", "react", "env"],
plugins: [
"transform-object-rest-spread",
"transform-class-properties"
]
}
},
{
test: /\.(eot?.+|svg?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
use: 'file-loader?name=assets/[name]-[hash].[ext]'
},
{
test: /\.(png|gif|jpg|svg)$/,
use: [
'url-loader?limit=20480&name=assets/[name]-[hash].[ext]'
],
include: staticSourcePath
}
]
}
};
I tried changing the presets of babel. I don't know if it could be a problem with the library query-string but even when I don't use it the error persists.
I also tried almost all configurations from https://github.com/webpack-contrib/uglifyjs-webpack-plugin/issues/104 and can't make it work :C....
I hope someone can help me I have been fighting with this error since weekend and im near to kill myself T_T
Already tried babel-polyfill and dont work :(
Just updated to webpack 4 and solved my problem. To many people have this kind of error with webpack < 4.
I will leave my webpack 4 configuration here for those who had suffered like me
webpack.config.js
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
resolve: {
extensions: ['.js', '.jsx']
},
output: {
publicPath: '/'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
// host: '0.0.0.0', /******* Para ver en lan*/
// disableHostCheck: true,/****** Para ver en lan */
historyApiFallback: true,
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.js$|\.css$|\.html$|\.eot?.+$|\.ttf?.+$|\.woff?.+$|\.svg?.+$/,
threshold: 10240,
minRatio: 0.8
})
]
};
package.json
"scripts": {
"start": "webpack-dev-server --mode development --open",
"build": "webpack --mode production"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-regenerator": "^6.26.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"compression-webpack-plugin": "^1.1.11",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.0.7",
"mini-css-extract-plugin": "^0.2.0",
"react": "^16.3.0",
"react-dom": "^16.3.0",
"url-loader": "^1.0.1",
"webpack": "^4.2.0",
"webpack-cli": "^2.0.12",
"webpack-dev-server": "^3.1.1"
},
.babelrc
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"transform-regenerator"
]
}
In my experience, it's usually Uglify being too aggressive.
I noticed that in your answer, you've swapped out Uglify for compression-webpack-plugin. That's probably what made the bug go away.
In your original package.json, I'd change the Uglify config to
new UglifyJsPlugin({
sourceMap:true,
cache: true,
parallel: true,
uglifyOptions:{
ecma:8
}
}),
First, you want to see Uglify's warnings. It'll tell you if there's code that's likely to get clobbered by the minification / obfuscation algorithm. If there are, you may have to play with the compress, mangle, toplevel or keep_fnames options depending on how your code is structured. https://github.com/mishoo/UglifyJS2#minify-options
I understand that this might show a lot of warnings from 3rd party libraries. There's a couple things you can do:
Find alternative libs that minify correctly (they'll probably be higher quality anyways).
Import the already minified versions of the lib from /dist instead of from /src and then exclude the lib from the Uglify plugin
The settings for cache and parallel just make the minification run a bit faster.
Sometimes such a problem may be a result of the non-transpiled packages (excluded from transpiling).
To solve this you should include these packages to transpiled code:
rules: [
...
test: /\.jsx?$/,
exclude(resource) {
return (
/node_modules/.test(resource)
&& !/node_modules\/(query-string|strict-uri-encode|split-on-first)/.test(resource)
);
},
...
]

Resources