Webpack stopped transpiling React - reactjs

I've been using WebPack v2.6.1 to transpile and bundle my react jsx code. I did not change anything. All of a sudden, WebPack stopped transpiling and bundling my React code for production.
Below is a part of the error messages I'm getting:
When I use webpack dev server, everything works perfectly fine. This is happening when I try to go to production. WebPack seems to be producing the bundled output files but when I try to pull up the page, they don't come up. I'm issuing the same webpack --env.process command I've always used. In the browser, this is the error I'm getting which is preventing my React component from displaying.
My webpack.config.js file is below. Any idea what's happening here?
var IS_DEV = false; // change to false if building production files
var webpack = require('webpack');
var path = require("path");
// Define plugins needed for production and dev cases
var _pluginsDev = [
new webpack.ProvidePlugin({
'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch',
moment: 'moment',
ps: 'perfect-scrollbar'
}),
];
var _pluginsProd = [
new webpack.ProvidePlugin({
'fetch': 'imports-loader?this=>global!exports-loader?global.fetch!whatwg-fetch',
moment: 'moment',
ps: 'perfect-scrollbar'
}),
new webpack.DefinePlugin({ // Minimizer, removing multiple occurances of imports et.c
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: true,
output: { comments: false }
})
];
var _devtool = IS_DEV ? 'eval' : 'cheap-module-source-map';
var _plugins = IS_DEV ? _pluginsDev : _pluginsProd;
var _fileName = IS_DEV ? "./build/[name]-bundle.js" : "./dist/[name]-bundle.js";
var _bundles = {
home: './UI/components/home/home.jsx',
accounts: './UI/components/accounts/accounts.jsx',
contacts: './UI/components/contacts/contacts.jsx',
projectsList: './UI/components/projects/projects_list/projectsList.jsx'
};
module.exports = {
entry: _bundles,
output: {
path: path.resolve(__dirname, "wwwroot"),
publicPath: "/",
filename: _fileName
},
devtool: _devtool,
plugins: _plugins,
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader",
options: {
presets: ['es2015', 'stage-2', 'stage-0', 'react']
}
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
}

Related

How do you configure Webpack to clear the React Warning for production minification?

I am sure everyone has seen this error but here it is again:
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://facebook.github.io/react/docs/optimizing-performance.html#use-the-production-build for more details.
So of course I followed the instructions in the link provided, yet though I have made all the necessary updates to my code, I am still getting this error.
According to some other answers I have seen on StackOverflow and Github, the process.env.NODE_ENV being set to production through the Webpack plugin DefinePlugin tells React to build using the minified version. So I logged process.env.NODE_ENV in my main application component and it is in fact being set to production by the plugin and still I am getting the warning.
So even though the environment variable is being set to production, I am getting the warning and my React Dev Tools says:
This page is using the development build of React. 🚧
Note that the development build is not suitable for production.
Make sure to use the production build before deployment.
I cannot seem to isolate where the problem might be here since I have done all the necessary changes to get the production build to work.
Here is my webpack.config.js file:
const webpack = require('webpack');
const resolve = require('path').resolve;
const SRC_BASE = resolve(__dirname, 'src');
const merge = require('webpack-merge');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const argv = require('yargs').argv;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const definePlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')),
__PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false')),
__PRODUCTION__: JSON.stringify(JSON.parse(process.env.NODE_ENV === 'production' || 'false')),
'process.env': {
NODE_ENV: process.env.NODE_ENV === 'production' ? // set NODE_ENV to production or development
JSON.stringify('production') : JSON.stringify('development'),
},
});
const loaderOptionsPlugin = new webpack.LoaderOptionsPlugin({ options: { context: __dirname } });
const commonsPlugin = new webpack.optimize.CommonsChunkPlugin('common.js');
const cssOutput = new ExtractTextPlugin({ filename: 'style.css', allChunks: true });
const sourceMapPlugin = new webpack.SourceMapDevToolPlugin({ filename: '[name].map' });
const htmlPlugin = new HtmlWebpackPlugin({
template: `${SRC_BASE}/index.template.ejs`,
filename: '../index.html', // relative to public/build/ so this is public/index.html
inject: true,
hash: true,
});
let config = {
cache: true,
entry: {
main: ['babel-polyfill', resolve(SRC_BASE, 'index')],
},
output: {
path: resolve(__dirname, 'public/build'),
filename: '[name].bundle.js',
publicPath: '/build/',
sourceMapFilename: '[name].map',
},
resolve: {
modules: [
SRC_BASE,
'node_modules',
],
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: [/\.jsx$/, /\.js$/],
loader: 'babel-loader',
exclude: /(local_modules|node_modules|bower_components)/,
query: {
presets: [
'react',
'es2015',
'stage-1',
],
},
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
loader: 'file-loader',
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!sass-loader',
}),
},
],
},
node: {
fs: 'empty',
},
plugins: [
definePlugin,
commonsPlugin,
cssOutput,
htmlPlugin,
loaderOptionsPlugin,
sourceMapPlugin,
],
};
// Only load dashboard if we're watching the code
if (argv.watch) {
const DashboardPlugin = require('webpack-dashboard/plugin');
config = merge(config, { plugins: [new DashboardPlugin()] });
}
if (process.env.NODE_ENV === 'production') {
console.log('******* I AM MERGING PRODUCTION CONFIGS ******');
console.log(`process.env.NODE_ENV = ${process.env.NODE_ENV}`);
config = merge(config, {
devtool: 'cheap-module-source-map',
plugins: [
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
}),
new webpack.optimize.UglifyJsPlugin(),
],
module: {
rules: [
{ test: /redux-logger/, loader: 'null-loader' },
],
},
});
}
module.exports = config;
And here is my gulpfile.js tasks that runs gulp build --production:
/* Production Builds use this task */
gulp.task('webpack', (done) => {
if (argv.production) {
process.env.BUILD_DEV = false;
process.env.NODE_ENV = 'production';
}
const buildConfig = require('./webpack.config');
const compiler = webpack(buildConfig);
const tag = '[webpack]';
const info = gutil.colors.green;
const error = gutil.colors.red;
const warning = gutil.colors.yellow;
const filterStackTraces = err =>
err.toString().split(/[\r\n]+/).filter(line => ! line.match(/^\s+at Parser/)).join(EOL);
if (argv.watch) {
compiler.watch({}, (err, stats) => {
const statDetails = stats.toJson();
if (err) {
gutil.log(error(tag), err.toString({ colors: true }));
}
else if (stats.hasErrors()) {
statDetails.errors.forEach(ex => gutil.log(error(tag), filterStackTraces(ex)));
}
else if (stats.hasWarnings()) {
statDetails.warnings.forEach(wx => gutil.log(warning(tag), filterStackTraces(wx)));
}
else {
statDetails.chunks.forEach(chunk => {
if (chunk.entry) gutil.log(info(tag), `Built ${chunk.files[0]} (${chunk.size} bytes)`);
});
gutil.log(info(tag), 'Build complete');
}
});
}
else {
compiler.run((err, stats) => {
if (err) {
return done(new gutil.PluginError('webpack', err));
}
if (stats.hasErrors()) {
const statDetails = stats.toJson();
statDetails.errors.forEach(ex => gutil.log(error(tag), filterStackTraces(ex)));
return done(new gutil.PluginError('webpack', 'Parse/ build error(s)'));
}
gutil.log(gutil.colors.green(tag), stats.toString({ colors: true }));
done();
});
}
});
gulp.task('build', ['webpack']);
After stumbling around the interweb for some different ways to configure webpack to overcome this problem I found a configuration option in the UglifyJsPlugin that cleared the error.
plugins: [
new webpack.optimize.UglifyJsPlugin({
include: /\.min\.js$/, <------This option fixed it
})
]
All though this cleared the warning in the console, I am still seeing my React Dev Tools saying that it is not using the production version.
I've had the same problem, but it doesn't seem to be a problem with webpack- it's likely something to do with Gulp. Have you tried running webpack with the config directly from the command line (i.e. webpack --config webpack-build.config.js or whatever) ? That produced a build without the warning quite happily. Here's my webpack config, cobbled together from various sources:
const path = require('path')
const webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-source-map',
entry: './src/scripts/app',
output: {
path: path.join(__dirname, 'dist/scripts'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['env', 'react']
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new webpack.optimize.UglifyJsPlugin({
beautify: false,
mangle: {
screw_ie8: true,
keep_fnames: true
},
compress: {
screw_ie8: true
},
comments: false
})
]
}
If I track down what's going on with gulp + webpack I'll write an update.

webpack 2 cannot omit '-loader' error

I've been using webpack 1.x successfully on my React project up to this point. I'm now trying to migrate to webpack 2 and running into this problem:
In my actions.js files, I import JavaScript functions from other files -- see below:
When I run webpack, I get the following error. Looks like webpack is confusing my import statements with importing loaders -- see below:
Here's the webpack.config.js file that I've just converted to webpack 2 format:
var IS_DEV = false;
var webpack = require('webpack');
var path = require("path");
var _pluginsDev = [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
moment: 'moment',
ps: 'perfect-scrollbar'
}),
];
var _pluginsProd = [
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch',
moment: 'moment',
ps: 'perfect-scrollbar'
}),
new webpack.DefinePlugin({ // Minimizer, removing multiple occurances of imports et.c
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: true,
output: { comments: false }
})
];
var _devtool = IS_DEV ? 'eval' : 'cheap-module-source-map';
var _plugins = IS_DEV ? _pluginsDev : _pluginsProd;
var _fileName = IS_DEV ? "./build/[name]-bundle.js" : "./dist/[name]-bundle.js";
var _bundles = {
accounts: './UI/components/accounts/accounts.jsx'
};
module.exports = {
entry: _bundles,
output: {
path: path.resolve(__dirname, "wwwroot"),
publicPath: "/",
filename: _fileName
},
devtool: _devtool,
plugins: _plugins,
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: {
presets: ['es2015', 'stage-0', 'stage-2', 'react']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx']
}
}
Any idea what's causing this and how to fix it?
In new webpack versions, you can not omit loader prefix.
new webpack.ProvidePlugin({
'fetch': 'imports-loader?this=>global!exports?global.fetch!whatwg-fetch',
moment: 'moment',
ps: 'perfect-scrollbar'
})

webpack dev server with razor templating engine (angular2 - netcore)

I have a aspnet core + angular2 + webpack project. I´m having trouble to get working the livereload part of webpack-dev-server. I think the problem may come because the use of razor templating. Dev server expects a plain index.html that never exists.
var webpack = require('webpack');
const path = require('path');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
polyfills: './wwwroot/polyfills.ts',
vendor: './wwwroot/vendor.ts',
app: "./wwwroot/main.ts"
},
output: {
publicPath : '/lib/webpack',
path:'wwwroot/lib/webpack',
filename: '[name].[hash].build.js'
},
resolve: {
extensions: ['.ts', '.js']
},
devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, '/wwwroot/'),
proxy: {
'*': 'http://localhost:5000'
},
watchOptions: {
aggregateTimeout: 300,
poll: 1000
}
},
module: {
rules: [
{
test: /\.ts$/,
loaders: ['ts-loader?ConfigFileName=./wwwroot/tsconfig.json', 'angular2-template-loader']
},
{
test: /\.css$/,
loaders: 'style-loader!css-loader'
},
{
test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
loader: 'url-loader'
},
{
test: /\.(html)$/,
loader: 'raw-loader'
}
]
},
plugins: [
new CleanWebpackPlugin(
[
'./wwwroot/lib/webpack'
]
),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery'
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
inject: false,
template: 'Views/Shared/_layoutTemplate.cshtml',
filename: '../../../Views/Shared/_layout.cshtml'
}),
]
}
The dev server runs and then I run the dotnet project. The result is that I can render the page because of the proxy. But the dev server does not inject it´s livereload code in that rendered view. So when I do changes i have to reload manually.
How can I tell dev server to use that .cshtml file? or how can I achieve it?
Thank you.

React error even after using DefinePlugin

I am using React 15.4.2 and Redux 3.6.0 with Webpack and this is my webpack.config.js file contents: (some of the code is omitted for brevity)
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const FaviconsWebpackPlugin = require('favicons-webpack-plugin');
const pkg = require('./package.json');
const TARGET = process.env.npm_lifecycle_event;
const PATHS = {
src: path.join(__dirname, 'src/js'),
dist: path.join(__dirname, 'dist')
};
process.env.BABEL_ENV = TARGET;
const common = {
resolve: {
extensions: ['', '.js', '.jsx']
},
entry: {
app: PATHS.src
},
output: {
path: PATHS.dist,
publicPath: '/',
filename: '[name].[hash].js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loaders: ['babel?cacheDirectory'], include: PATHS.src },
{ test: /\.scss$/, exclude: /node_modules/, loaders: ['style', 'css', 'sass'] },
{ test: /(\.ttf|\.woff2?|\.eot|\.svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, exclude: /node_modules/, loader: 'url' },
{ test: /\.(jpe?g|png|gif|svg)$/i, exclude: /node_modules/, loader: 'url?limit=10000!img?progressive=true' },
{ test: /\.json/, loaders: ['json']}
]
},
plugins: [
new HTMLWebpackPlugin({
template: 'src/index.html',
inject: 'body'
})
]
};
if (TARGET === 'build') {
module.exports = merge(common, {
entry: {
vendor: Object.keys(pkg.dependencies)
},
output: {
path: PATHS.dist,
filename: '[name].[chunkhash].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: ExtractTextWebpackPlugin.extract('style', 'css'), include: PATHS.src }
]
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new CleanWebpackPlugin([PATHS.dist]),
new ExtractTextWebpackPlugin('[name].[chunkhash].css'),
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest']
})
]
});
}
Running npm run build gives the minified code. But it still gives the error
Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See https://facebook.github.io/react/docs/optimizing-performance.html#use-the-production-build for more details.
I have also tried reordering the plugins in build TARGET, but its giving the same error.
What am I missing here?
P.S. Redux gives the same minification error too.
EDIT
This is my package.json build script:
"scripts": {
...
"build": "NODE_ENV=production webpack --progress"
...
}
EDIT #2
This is the output to a console.log statement from within the application.
You could use this syntax for the DefinePlugin.
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production')
}
}),
I enabled source maps to see that its a package I have been using that was minified using non-standard ways. So, setting NODE_ENV to 'production' had no effect on the said package. Nevertheless, my Webpack config and my build scripts have been working perfectly fine. Thank you for your help guys!

Webpack Dev Server with React Hot Loader

I have a webpack configuration that works perfect in itself. I'm trying to install React Hot Loader together with HMR as suggested, which require webpack-dev-server. Here I cannot get it to work. I can not find where my bundle is located. I want it to be just at localhost:3000.
My webpack.config.js:
var webpack = require('webpack');
var path = require('path');
module.exports = {
watch: true,
devtool: 'eval',
// entry: './src/main.js', This runs just for webpack bundling
entry:[
'webpack-dev-server/client?http:localhost:9000', // WebpackDevServer host and port
'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
'./src/main.js' // Your appʼs entry point
],
output: {
path: path.resolve(__dirname, 'public', 'dist'),
filename: 'main.js'/*,
publicPath: '/dist/'*/
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel-loader?cacheDirectory=true,presets[]=react,presets[]=es2015'],
exclude: function(path) {
var isModule = path.indexOf('node_modules') > -1;
var isJsaudio = path.indexOf('jsaudio') > -1;
if (isModule && !isJsaudio) {
return true;
}
}
}, {
test: /\.json$/,
loader: "json-loader"
}]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['', '.js', '.json', 'index.js'],
root: [
path.resolve(__dirname, 'src'),
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'node_modules', 'jsaudio', 'src')
]
},
target: 'web',
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
}
};
And the webpack-server.js:
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: '/dist/',
hot: true,
historyApiFallback: true
}).listen(9000, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:9000/');
});
Update: The linked question does not help, especially since it does not even have a confirmed answer.
I would suggest trying out react-hot-loader v3 as the updates to get hot-reloading working have been simplified (in my opinion!).
in webpack then try point now only needs:
entry: {
app: [
'react-hot-loader/patch',
'webpack-hot-middleware/client',
`${SRC}/client-entry.js`
]
}
here is a link to an example app, react-lego that i've created to help people add react-hot-loader v3 to their apps. hope it helps

Resources