How to set environment variables on React with custom webpack - reactjs

My React app isn't run by create-react-app, but a custom Webpack config.
I"ve installed dotenv / dotenv-expand / and also dotenv-webpack.
I have .env / .env.development files with API_URL variable in it.
On my url file,
const { API_URL } = process.env
and use this API_URL to fetch data.
But on this file, when I console.log(process.env), it is empty.
I also have tried to update webpack.config.js file with
const Dotenv = require('dotenv-webpack');
and
new Dotenv()
in plugins array.
But still doesn't work.
I also tried having variable name REACT_APP_API_URL but was same result.
Could anyone help me to set the env vars?
Thank you.
webpack.config.js
const webpack = require('webpack')
const Dotenv = require('dotenv-webpack');
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpackMerge = require('webpack-merge')
const modeConfig = env => require(`./build-utils/webpack.${env}`)(env)
const presetConfig = require('./build-utils/loadPresets')
module.exports = ({ mode, presets } = { mode: 'production', presets: [] }) => {
console.log('mode', mode, 'presets', presets)
return webpackMerge(
{
mode,
module: {
rules: [
{
test: /\.(png|jpe?g|svg)$/,
use: {
loader: 'file-loader',
options: {
name: 'assets/[name].[ext]',
}
},
},
],
},
node: {
fs: 'empty'
},
resolve: {
extensions: ['.js', '.json'],
},
output: {
filename: 'bundle.js',
chunkFilename: '[name].lazy-chunk.js',
path: path.resolve(__dirname, 'build'),
publicPath: mode === 'development' ? '/' : './'
},
devServer: {
historyApiFallback: true
},
plugins: [
new HtmlWebpackPlugin({
template: './build-utils/template.html'
}),
new webpack.ProgressPlugin(),
new Dotenv()
]
},
modeConfig(mode),
presetConfig({ mode, presets })
)
}

If you're trying to access the env values in your JS files, you typically need to have the dotenv plugin.
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpackMerge = require('webpack-merge')
require('dotenv').config() // may need to set path to your .env file if it isn't at the root at the project
const modeConfig = env => require(`./build-utils/webpack.${env}`)(env)
const presetConfig = require('./build-utils/loadPresets')
module.exports = ({ mode, presets } = { mode: 'production', presets: [] }) => {
return webpackMerge(
...
plugins: [
new HtmlWebpackPlugin({
template: './build-utils/template.html'
}),
new webpack.ProgressPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
SOME_VALUE: JSON.stringify(process.env.SOME_VALUE),
...
}
})
]
},
...
)
}
NOTE: With this implementation you won't be able to do
const { API_URL } = process.env because DefinePlugin does a search and replace of the JavaScript where it will look up any references to process.env.API_URL and replace it with whatever that value is. Therefore API_URL won't exist on porcess.env, so to use it just do process.env.API_URL
You could also use dotenv-webpack, I think you were close to getting it to work.
const webpack = require('webpack')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpackMerge = require('webpack-merge')
const Dotenv = require('dotenv-webpack');
const modeConfig = env => require(`./build-utils/webpack.${env}`)(env)
const presetConfig = require('./build-utils/loadPresets')
module.exports = ({ mode, presets } = { mode: 'production', presets: [] }) => {
return webpackMerge(
...
plugins: [
new HtmlWebpackPlugin({
template: './build-utils/template.html'
}),
new webpack.ProgressPlugin(),
new Dotenv({
path: envPath
})
]
},
...
)
}
If you need more help please share more details in by creating a Minimal, Reproducible Example.

Related

Reactjs - Can xterm.js have problem with webpack configuration?

So far I am not able to properly integrate xterm.js with reactjs due to which my code breaks in production but works while development.
HELP !!!
import React, {useEffect} from 'react';
import {Terminal} from 'xterm';
import {FitAddon} from 'xterm-addon-fit';
const UITerminal = () => {
const term = new Terminal();
const fitAddon = new FitAddon();
term.loadAddon(fitAddon);
useEffect(() => {
let termDocument = document.getElementById('terminal')
if (termDocument) {
term.open(termDocument)
fitaddon.fit();
}
window.addEventListener('resize', () => {
fitaddon.fit();
})
}, [])
return (<div id="terminal"></div>)
}
Below is the error response from production code. clearly it fails to import xterm
react_devtools_backend.js:4012 ReferenceError: Cannot access 'r' before initialization
at new m (96209.72626fc1cc862aea477a.bundle.js:1:165467)
at new b (96209.72626fc1cc862aea477a.bundle.js:1:159758)
at new M (96209.72626fc1cc862aea477a.bundle.js:1:57572)
at new r.exports.i.Terminal (96209.72626fc1cc862aea477a.bundle.js:1:294972)
at w (96209.72626fc1cc862aea477a.bundle.js:1:15994)
at zo (main.71e827eabc798023c129.bundle.js:1:1260000)
at Ws (main.71e827eabc798023c129.bundle.js:1:1333492)
at Wi (main.71e827eabc798023c129.bundle.js:1:1294411)
at Ui (main.71e827eabc798023c129.bundle.js:1:1294336)
at Pi (main.71e827eabc798023c129.bundle.js:1:1291367)
UPDATE
I have found out that it is happening because of my production webpack configuration but still the root cause is unidentified. please help in soughting this out. I am adding my development and production webpack config here.
Please note that the dev webpack config absolutely works fine if build with it and serve.
webpack.dev.js
const fqdn = "some.fqdn.com"
const path = require("path");
const webpack = require("webpack")
const common = require("./webpack.common");
const { merge } = require("webpack-merge");
const fs = require('fs');
const jsonFormat = require('json-format');
var HtmlWebpackPlugin = require("html-webpack-plugin");
const jsonFromatConfig = {
type: 'space',
size: 4
}
module.exports = merge(common, {
mode: "development",
devtool: "source-map",
output: {
filename: "bundle.js",
publicPath: '/',
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html"
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
target: "web",
devServer: {
open: true,
static: {
directory: path.join(__dirname, '../public'),
},
historyApiFallback: true,
},
});
webpack.prod.js
const path = require("path");
const common = require("./webpack.common");
const { merge } = require("webpack-merge");
var MinifyPlugin = require('babel-minify-webpack-plugin')
var CompressionPlugin = require('compression-webpack-plugin');
const CleanWebpackPlugin = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
var HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = merge(common, {
mode: "production",
output: {
filename: "naming.[name].contenthash.[contenthash].bundle.js",
path: path.resolve(__dirname, "../build")
},
optimization: {
minimizer: [
new TerserPlugin(),
new HtmlWebpackPlugin( {
template: "./public/index.html",
minify: {
removeAttributeQuotes: true,
collapseWhitespace: true,
removeComments: true
}
} ),
new MinifyPlugin({}, {
comments: false
})
],
splitChunks: {
chunks: 'all',
minChunks: 3
}
},
plugins: [
new CompressionPlugin({
test: /\.js$|\.css$|\.html$/
}),
new MiniCssExtractPlugin({ filename: "naming.[name].contenthash.[contenthash].css" }),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /\.css/i,
use: [
MiniCssExtractPlugin.loader,
"css-loader"
]
},
]
}
});
The error shows that you might use Xterm before its initialization,
You might find it useful to use react-aptor or the idea behind it to connect pure js packages like Xterm.js into react world.
import useAptor from 'react-aptor';
const initializer = (node, params) => {
// user params for further configuration
const terminal = new Terminal();
term.open(node);
return terminal;
}
const getAPI = (terminal, params) => {
return () => ({ terminal })
}
const ReactXterm = (props, ref) => {
const aptorRef = useAptor(ref, {
getAPI,
instantiate,
/* params: anything */
});
return <div ref={aptorRef} />;
};
function App() {
const ref = useRef();
const writeToTerminal = () => {
ref.current.terminal?.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
};
return (
<div>
<ReactXterm ref={ref} />
<button onClick={writeToTerminal}>write to terminal</button>
</div>
);
}
Disclosure: I am the maintainer of react-aptor

Updating nextjs from 8 to 9.3.3 broke styling

I just updated nextjs from 8 to 9.3.3, and some of my styling broke.
Previously I was importing .scss files and they were locally scoped to their respective components.
After updating to 9.3.3, it seems that components with classNames that are named the same are now sharing styles, so that leads me to believe that something with the sass-loader or css-loader in next.config.js seems off.
this is my next.config.js
const path = require('path');
const dotenv = require('dotenv');
const withSass = require('#zeit/next-sass');
const webpack = require('webpack');
const envConfig = dotenv.config();
const config = withSass({
cssModules : true,
cssLoaderOptions : {
modules : true,
sourceMap : true,
importLoaders : 1,
},
sassLoaderOptions: {
includePaths: [path.resolve(__dirname, './')], //eslint-disable-line
},
useFileSystemPublicRoutes: false,
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { // eslint-disable-line
const ENV = {};
for (let entry in envConfig.parsed) {
ENV[`process.env.${entry}`] = JSON.stringify(envConfig.parsed[entry]);
}
config.plugins.push(new webpack.DefinePlugin(ENV));
return config;
},
});
module.exports = config;
What I've tried
I've changing my config around like this:
const config = withSass({
cssModules : true,
cssLoaderOptions : {
modules : {
mode: 'local',
exportGlobals: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
context: path.resolve(__dirname, 'src'), //eslint-disable-line
hashPrefix: 'my-custom-hash',
},
sourceMap : true,
importLoaders : 1,
},
sassLoaderOptions: {
includePaths: [path.resolve(__dirname, './')], //eslint-disable-line
},
useFileSystemPublicRoutes: false,
webpack: (config, { buildId, dev, isServer, defaultLoaders }) => { // eslint-disable-line
const ENV = {};
for (let entry in envConfig.parsed) {
ENV[`process.env.${entry}`] = JSON.stringify(envConfig.parsed[entry]);
}
config.plugins.push(new webpack.DefinePlugin(ENV));
return config;
},
});
module.exports = config;
which didn't work.
My last resort which does work is manually going into each .scss file and changing them to x.module.scss, which would take a lot of time going into each file. Is there something wrong with my config?

deploying officejs fabric react word add in

I have a word add in written in typescript using Officejs and office-ui-fabric-react. Everything works fine with the server running locally. I'd like to deploy into AWS S3 with Cloudfront. I'm building with npm run build, and npm run deploy (using deploy command "aws --profile profile-name s3 sync dist/ s3://bucketname". Static web site hosting is enabled in the S3 bucket. All files from the dist directory are seen in the bucket. After inserting the add in into Word with a manifest.xml file that points to the cloudfront endpoint I'm getting the error "Uncaught ReferenceError: React is not defined". The same error occurs when I point directly to the S3 static web endpoint. To see if I've missed anything I deployed a generic create-react-app using the steps above and it runs fine. I'm assuming that the problem lies with my webpack config so I've included that here (common, and prod). I'd be happy to include anything else that's needed. I'm also open to other deployment options if using AWS is causing the problem.
webpack.common.js:
const webpack = require('webpack');
const path = require('path');
const package = require('../package.json');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const build = (() => {
const timestamp = new Date().getTime();
return {
name: package.name,
version: package.version,
timestamp: timestamp,
author: package.author
};
})();
const entry = {
vendor: [
'react',
'react-dom',
'core-js',
'office-ui-fabric-react'
],
app: [
'react-hot-loader/patch',
'./index.tsx',
],
'function-file': '../function-file/function-file.ts'
};
const rules = [
{
test: /\.tsx?$/,
use: [
'react-hot-loader/webpack',
'ts-loader'
],
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
use: {
loader: 'file-loader',
query: {
name: 'assets/[name].[ext]'
}
}
}
];
const output = {
path: path.resolve('dist'),
publicPath: '/',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js'
};
const WEBPACK_PLUGINS = [
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.BannerPlugin({ banner: `${build.name} v.${build.version} (${build.timestamp}) © ${build.author}` }),
new webpack.DefinePlugin({
ENVIRONMENT: JSON.stringify({
build: build
})
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({ browsers: ['Safari >= 8', 'last 2 versions'] }),
],
htmlLoader: {
minimize: true
}
}
})
];
module.exports = {
context: path.resolve('./src'),
entry,
output,
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.scss', '.css', '.html']
},
module: {
rules,
},
optimization: {
splitChunks: {
chunks: 'async',
minChunks: Infinity,
name: 'vendor'
}
},
plugins: [
...WEBPACK_PLUGINS,
new ExtractTextPlugin('[name].[hash].css'),
new HtmlWebpackPlugin({
title: 'letterConfig',
filename: 'index.html',
template: './index.html',
chunks: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
title: 'letterConfig',
filename: 'function-file/function-file.html',
template: '../function-file/function-file.html',
chunks: ['function-file']
}),
new CopyWebpackPlugin([
{
from: '../assets',
ignore: ['*.scss'],
to: 'assets',
}
])
]
};
webpack.prod.js:
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const ENV = process.env.NODE_ENV = process.env.ENV = 'development';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
performance: {
hints: "warning"
},
optimization: {
minimize: true
}
});
index.tsx:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
import App from './components/App';
import './styles.less';
import 'office-ui-fabric-react/dist/css/fabric.min.css';
initializeIcons();
let isOfficeInitialized = false;
const title = 'letterConfig';
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Component title={title} isOfficeInitialized={isOfficeInitialized} />
</AppContainer>,
document.getElementById('container')
);
};
/* Render application after Office initializes */
Office.initialize = () => {
console.log('init');
isOfficeInitialized = true;
render(App);
};
/* Initial render showing a progress bar */
render(App);
if ((module as any).hot) {
(module as any).hot.accept('./components/App', () => {
const NextApp = require('./components/App').default;
render(NextApp);
});
}
It turned out that it was looking for a globally defined "React", and so not resolving via an npm module. In the webpack.prod.js file removing the following solved the problem:
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},

React production shows blank page

i have a problem with a webpack build, the command i run is
cross-env NODE_ENV=production webpack --config webpack.prod.js
and the file webpack prod is:
var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var path = require('path');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: path.join(process.cwd(), '/public'),
publicPath: '/',
filename: '[name].[hash].js'
},
plugins: [
//new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: {
keep_fnames: true,
except: ['$super']
}
}),
new ExtractTextPlugin('[name].[hash].css'),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
]
});
webpack.common.js is
var webpack = require('webpack');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var path = require('path');
var pkgBower = require('./package.json');
module.exports = {
entry: {
'app': './main.js'
},
resolve: {
root: path.join(__dirname, ''),
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [...]
},
devServer: {
outputPath: path.join(__dirname, 'public')
},
plugins: [
new HtmlWebpackPlugin({
template: process.env.NODE_ENV == 'development' ? 'index.html' : 'index.prod.html',
baseUrl: process.env.NODE_ENV == 'development' ? '/' : '/'
})
]
};
i can run the build but unfortunatelly when i open index.html it shows a blank page to me, i want to include this SPA in a spring boot project but I do not know how ;)
Thanks!
Solved! was a problem of "browserHistory"
If you use the "browserHistory" as history manager your webpack needs a node.js server to run, using a "hashHistory" you can use it as a normal web page!
See
Why is React Webpack production build showing Blank page?
First things first, which version of webpack are you using Lorenzo? Probably due to syntax, it's 1.X.
First, check in your package.json file which version is. Then, if it's really 1.x you can build in debug mode.
export default {
entry: [
'./src/Client.js'
],
debug: true
}
Inside your webpack.common.js
Check the error, paste here.
I hope it helps, welcome to StackOverflow, here are a few notes that can improve our community =)
Try to put "main":"index.js" in package.json file
That solved my problem.
"main": "index.js",
"scripts": {
...
},
Happy to help.

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.

Resources