Configure webpack production build - reactjs

I need to use production build with Webpack. If I visit my site now in production icon is having red background which means it's not using production
When I do npm run build, it says npm ERR! missing script: build
How can I adjust webpack so I can make a production build and make my app faster?
Here is my webpack config:
const webpack = require('webpack');
const config = {
entry: ['babel-polyfill', './src/index.js'],
output: {
filename: 'bundle.js',
},
devServer: {
inline: true,
port: 8080,
historyApiFallback: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
API_KEY: 'API_KEY',
GOOGLE_MAPS_KEY: 'GOOGLE_MAPS_KEY',
GOOGLE_GEOLOCATION_KEY: 'GOOGLE_GEOLOCATION_KEY',
},
}),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react'],
},
},
{
test: /\.css$/,
loader: 'style!css',
},
],
},
};
module.exports = config;

plugins: [
new webpack.DefinePlugin({
'process.env': {
API_KEY: 'API_KEY',
GOOGLE_MAPS_KEY: 'GOOGLE_MAPS_KEY',
GOOGLE_GEOLOCATION_KEY: 'GOOGLE_GEOLOCATION_KEY',
NODE_ENV: JSON.stringify('production') // <--- this set everything to use production.
},
}),
],

Related

Build bundle.js in create-react-app application

Made a project. Now we need to collect everything in one bundle.js, and not in the way create-react-app does.
Executed the eject command, configs appeared. But how do i get bundle.js?
It is important that everything that is in the project (styles, pictures, etc.) be gathered into one file.
## My Solution
webpack.config.js:
const path = require("path");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
context: __dirname,
entry: "./src/index.js",
output: {
path: path.join(__dirname, "/dist"),
publicPath: '',
filename: "widget.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ["babel-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(gif|png|jpe?g|svg|woff(2)?|ttf|eot)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: 'img',
outputPath: 'img',
name: '[name].[ext]',
},
},
],
}
]
},
optimization: {
minimizer: [new UglifyJsPlugin({
uglifyOptions: {
warnings: false,
parse: {},
compress: {},
mangle: true,
output: {
comments: false,
},
toplevel: false,
nameCache: null,
ie8: true,
keep_fnames: false,
},
})],
},
plugins: [
new HtmlWebpackPlugin({
template: "./public/index.html"
})
]
};
Ejecting is a real bad solution, instead use rewire npm install react-app-rewired and add a customized build script.
please checkout my answer here
How to build a production version of React without minification?

dev-server taking lot time to rebuild project in webpack 4

i developed react app,before that i built same app on webpack v3 now i upgrade to v4.on v3 dev-server it worked fine but on v4 it is taking lot of time to build and every time its building whole project again(may be that's why)
my webpack.dev.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.s?css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize:false,
importLoaders: 1,
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},{
test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: "file-loader",
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true,
host:'0.0.0.0',
disableHostCheck: true,
}
};
and my scripts in package.json
"scripts": {
"start": "node server/server.js",
"build": "webpack --mode production --config=webpack.prod.js",
"dev": "webpack --mode development --config=webpack.dev.js",
"dev-server": "webpack-dev-server --config=webpack.dev.js"
}
it showing me error
ou are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) to ensure you have the correct code for your production build.
but if console my process.env.NODE_ENV varialbe it showing me developement
i have two problems with dev-server on development mode
1) how can i reduce time of rebuilding on dev-server
2)on development mode also why it showing me production error.
Your development server is being run in production mode because you haven't set the --mode development argument in your dev-server NPM script. It seems like it isn't required since webpack-dev-server is, after all, a development server, but the argument is still necessary.
"dev-server": "webpack-dev-server --mode development --config webpack.dev.js"
To speed up the build in development, inject all CSS into the HTML with style-loader instead of extracting the CSS to a separate file. See the following code where I removed mini-css-extract-plugin and its loader.
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.s?css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
sourceMap: true,
minimize:false,
importLoaders: 1,
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(gif|svg|jpg|png|ttf|eot|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
],
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true,
host:'0.0.0.0',
disableHostCheck: true,
}
};
Building source maps will slow the build down as well, so consider if you truly need them.
The answer is: you are using the inline-source-map devtool which causes the build & rebuild process super slow.
According to the Official Webpack Document, they said:
Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically.
For more information, you could read it here: https://webpack.js.org/configuration/devtool/#devtool
Hopefully, that helps!
Adding caching to babel-loader can shave off some time:
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
cacheDirectory: true,
cacheCompression: false
}
}
]
}
https://github.com/babel/babel-loader#options
I have had the same issue and i completely remove source map for development and now is super-fast.My webpack.common.js file looks like this
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
filename: '[name].[hash].js',
path: path.resolve('./dist')
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
},
{
loader: 'eslint-loader'
}]
}, {
test: /\.s?css$/,
use: [
{
loader: 'css-loader',
options: {
sourceMap: false
}
},
{
loader: 'sass-loader',
options: {
sourceMap: false
}
}
]
}]
},
optimization: {
minimize: true
},
plugins: [
new HtmlWebPackPlugin({
template: 'index.html'
}),
new CleanWebpackPlugin()
]
};
and my webpack.dev.js looks like this one
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'development',
devServer: {
host: 'localhost',
disableHostCheck: true,
port: 3000,
open: true,
historyApiFallback: true
}
});
With this aproach we losing source-map in development and get fast at speed,if you really need source-mapping in dev-mode choose some light-weight source-map like cheap-eval-source-map and change it when you go in production build to inline-source-map because inline-source-map decreases dramatically size of main.js || bundle.js file.

react and webpack bundle not being loaded

I'm trying to understand the innings and outings of webpack and it's quirks.
So i've set up a project working with webpack 1(i know it's outdated, but for now it will work for my needs), that coupled with react and redux.
While developing and testing locally it works like a charm all is good. when i try to set it to production it all goes A-wire. when i try to access the app i get a famous
Uncaught SyntaxError: Unexpected token <
While inspecting the firefox dev console and chrome dev console i see that on the sources the the html file is there, but the bundle is not.
The bundle is generated on the corresponding folder, either while in development mode, or in production mode.
I've tried the adding adding a dot for relative path, removing the dot on the relative path, moving the location of the js bundle file around, setting it to async and still no solution.
Bellow are the webpack config for development and production.
Development webpack file structure
const webpack = require('webpack');
const path = require('path');
//const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: ['whatwg-fetch','./src/index.js'],
module: {
devtool: 'source-map',
loaders: [
{
test: /\.js?$/,
loader: 'babel',
exclude: /node_modules/
},
{
test:/\.jsx$/,
loader: 'babel',
exclude: /node_modules/,
},
{
test: /\.scss$/,
loader: 'style!css!sass'
},{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
},
resolve: {
extensions: ['', '.js','.jsx']
},
output: {
path: path.join(__dirname, '/dist'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist',
hot: true
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
/* new CleanWebpackPlugin(['dist'], {
verbose: true,
dry: false,
exclude: ['index.html','server.bundle.js','dbFactory.js','httpService.js']
}) */
]
};
Webpack production file structure
const config = require('./webpack.config.js');
const webpack = require('webpack');
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
comments:false,
minimize:true,
mangle:true,
compress: {
warnings: false,
sequences: true,
dead_code: true,
conditionals: true,
booleans: true,
unused: true,
if_return: true,
join_vars: true,
drop_console: true,
screw_ie8: true,
}
})
);
config.plugins.push(
new webpack.optimize.DedupePlugin()
);
/*
config.plugins.push(
new webpack.optimize.CommonsChunkPlugin({
name:'vendor',
entries:['history',
'react',
'react-dom',
'react-router',
'react-redux',
'redux'],
chunks:['vendor'],
minChunks:Infinity
})
);*/
module.exports = config;
The package.json command to generate the bundle is the following one
"postinstall": "webpack -p --config webpack.prod.config.js --progress --colors"
now with some more time to spare and some console.log abuse it looks like that the actual bundle was being created on the correct folder but it was not being obtained correctly by express.
One lesson learned is that always check your paths!

Configure react webpack for deploy

need a little help.
We had tried to deploy a react project, but we are unable to configure it.
We use: es6, webpack, redux, react, babel.
this is webpack base:
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
export default {
entry: './app/app.js',
output: {
path: './app/App/dist',
filename: '/bundle.js',
},
module: {
loaders: [
{
test: /\.json$/,
loader: 'json',
},
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract('css!sass'),
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css!sass'),
},
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
{
test: /\.svg$/,
loader: 'babel?presets[]=es2015,presets[]=react!svg-react',
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './app/App/index.html',
}),
new ExtractTextPlugin('/app/App/css/default.css', {
allChunks: true,
}),
],
};
webpack dev:
import webpack from 'webpack';
import baseConfig from './webpack.config.base';
const config = {
...baseConfig,
debug: true,
devtool: 'cheap-module-eval-source-map',
plugins: [
...baseConfig.plugins,
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
colors: true,
historyApiFallback: true,
inline: true,
hot: true,
},
};
export default config;
webpack prod:
import webpack from 'webpack';
import baseConfig from './webpack.config.base';
const config = {
...baseConfig,
plugins: [
...baseConfig.plugins,
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: {
screw_ie8: true,
warnings: false,
},
}),
],
};
export default config;
This is our actual webpack, we are trying to deploy the project with it, but does not work.
Does anyone have an idea how to configure it?
So, it's a server problem probably. You need a HTTP server in order to server the static files (your app basically). I recommend the Ngxin, very easy to configure and use.
After install nginx, delete the /etc/nginx/sites-enable/default file and create a new one (you can use whatever name you want here). Here's the config I use:
server {
listen 80;
listen [::]:80;
server_name example.com;
location / {
root /var/html/myProject/;
try_files $uri /index.html;
}
}
after that, restart nginx and should be ready to go.
for webpack, I have a simpler config that works well:
const path = require("path");
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProd = process.env.NODE_ENV && process.env.NODE_ENV.toLowerCase() == 'production';
const plugins = [
new ExtractTextPlugin(isProd ? 'bundle.[hash].css' : 'bundle.css', { allChunks: true }),
new HtmlWebpackPlugin({
template: 'index.html',
inject: 'body',
filename: 'index.html'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
})
];
const prodPlugins = [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
];
module.exports = {
devtool: isProd ? 'cheap-module-source-map' : 'eval',
entry: [
'./src/index.jsx'
],
output: {
path: isProd ? path.join(__dirname, 'dist') : __dirname,
publicPath: '/',
filename: isProd ? 'bundle.[hash].js' : 'bundle.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
},
{
test: /\.(scss|css|sass)$/,
loader: ExtractTextPlugin.extract('css!sass')
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: 'url'
},
{
test: /\.html$/,
loader: 'html'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
},
plugins: isProd ? prodPlugins.concat(plugins) : plugins
};
A few points:
I'm using SASS
Check the path's before run anything
To compile for production, just run NODE_ENV=production webpack -p
I'm using a few plugins for Uglify JS and compress files.
I think that's it! Cheers!
sure I think the fastest way to solve your problem is to click on this link:
React starter kit
and select any starters that matches your technologies!
I think you are looking for this one : react-boilerplate

How to webpack React.js using uglify version

I would like to webpack my React.js app using uglify version
webpack.config.js
module.exports = {
entry: './_react/index',
output: {
path: './dist/public/app',
filename: 'bundle.min.js'
},
devtool: 'source-map',
devServer: {
contentBase: __dirname
},
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: ['babel-loader'],
query: {
presets: ['es2015', 'react']
}
}]
}
}
Terminal
webpack -p
After previewing on the web browser, I got this error
Please guide, thanks
As jmargolisvt said, you need to set the NODE_ENV.
Try updating your webpack.config.js with the following:
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
Or in your current config as:
module.exports = {
entry: './_react/index',
output: {
path: './dist/public/app',
filename: 'bundle.min.js'
},
devtool: 'source-map',
devServer: {
contentBase: __dirname
},
module: {
loaders: [{
test: /\.js?$/,
exclude: /(node_modules|bower_components)/,
loader: ['babel-loader'],
query: {
presets: ['es2015', 'react']
}
}]
}
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
})
],
}
Make sure to use JSON.stringify to insert a string and not the variable production
You need to set the NODE_ENV to production. From the React site:
Note: by default, React will be in development mode. To use React in production mode, set the environment variable NODE_ENV to production (using envify or webpack's DefinePlugin).

Resources