user9105849
user9105849

Reputation:

How to put React in production mode?

I tried using the solution from here but the icon is still read indicating dev mode.

Here is my current file with updates from the answer below:

const path = require('path');
const SRC_DIR = path.join(__dirname, '/client-react/src');
const DIST_DIR = path.join(__dirname, '/client-react/dist');
const webpack = require('webpack')

module.exports = {
  entry: `${SRC_DIR}/index.jsx`,
  output: {
    filename: 'bundle.js',
    path: DIST_DIR
  },
  plugins: [
    new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production')} })
  ],
  module: {
      loaders: [
      {
        test: /\.jsx?/,
        include: SRC_DIR,
        loader: 'babel-loader',
        query: {
          plugins: ["transform-object-rest-spread", "transform-class-properties"],
          presets: ['react', 'es2015']
       }
      }
    ]
  }
};

Upvotes: 12

Views: 41301

Answers (5)

Rm4n
Rm4n

Reputation: 858

This worked for me: run npm run build followed by npm install -g serve and serve -s build

Upvotes: 4

Arsen K.
Arsen K.

Reputation: 5660

If you use Webpack 4, you don't need to change webpack.config.js. It remains the same in both development and production modes.

The only thing needed is in your package.json:

"scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
}

Having this, to create a development bundle:

npm run dev

Production bundle:

npm run build

Upvotes: 5

Arnold Gandarillas
Arnold Gandarillas

Reputation: 4322

Had the same error so to fix it I did this:

package.json

"scripts": {
  "build": "NODE_ENV=production webpack --progress --colors",
  "start": "NODE_ENV=development webpack-dev-server --progress --colors"
}

webpack.config.js

const env = process.env.NODE_ENV

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(env)
    })
  ]
}

It should work for sure.

Here I have some configuration that you can try to optimize your build.

Upvotes: 0

margaretkru
margaretkru

Reputation: 2781

When you want to build your app in production mode, you should use webpack production shortcut. Like this:

webpack -p

This will enable webpack optimize options to minify your JS. See more detailed explanation of webpack flags on this SO answer.

Upvotes: 2

Chris
Chris

Reputation: 298

Webpack plugins need to be put under the plugins key in module.exports.

https://webpack.github.io/docs/using-plugins.html#built-in-plugins

Try this:

module.exports = {
    plugins: [
        new webpack.DefinePlugin({
          'process.env': { NODE_ENV: JSON.stringify('production') }
      }),
   ]
}

Upvotes: 1

Related Questions