React with NPM cannot be used on the client because "development" is undefined. The package was created from Webpack
I am creating a React Node.js application and I am trying to create a Webpack package containing the React source code downloaded from NPM.
However, it looks like NPM's React code cannot be used directly in the client. This error throws an error:
Uncaught ReferenceError: development is not defined
The code that triggers the exception is in the React code:
Is there anything I can do to make this work?
EDIT
This is mine webpack.config.js
:
import _ from 'lodash';
import webpack from 'webpack';
import yargs from 'yargs';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
export default {
entry: {
bundle: './src/client.js'
},
output: {
filename: '[name].js',
path: './dist/assets',
publicPath: '/assets/'
},
externals: undefined,
resolve: {
extensions: ['', '.js', '.json']
},
module: {
loaders: [
{test: /\.js/, loader: 'babel?optional=es7.objectRestSpread!client', exclude: /node_modules/ },
{test: /\.css/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
{test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")},
{test: /\.json$/, loader: 'json'},
{test: /\.jpe?g$|\.gif$|\.png$/, loader: 'file?name=[name].[ext]'},
{test: /\.eot$|\.ttf$|\.svg$|\.woff2?$/, loader: 'file?name=[name].[ext]'}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': 'development'
},
'development': true
}),
new ExtractTextPlugin('[name].css')
]
};
My file client.js
only contains this line (for debugging this issue):
import React from 'react';
source to share
Any values passed to webpack.DefinePlugin
as strings are treated as code snippets, i.e. using
new webpack.DefinePlugin({
ENV: "development"
});
with code
console.log(ENV);
leads to
console.log(development);
You want instead
new webpack.DefinePlugin({
ENV: "\"development\""
});
which will lead to
console.log("development");
To fix the problem, change your plugins to
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': "'development'"
}
}),
new ExtractTextPlugin('[name].css')
]
I usually allow webpack to read from process.env.NODE_ENV
, so that React correctly extinguishes when running webpack with NODE_ENV=production
:
new webpack.DefinePlugin({
"process.env": { NODE_ENV: JSON.stringify(process.env.NODE_ENV || "development") }
})
source to share