Search code examples
webpackwebpack-2

Wepback - Include a script tag if environment is set to production


My issue is this

https://github.com/petehunt/webpack-howto/issues/46

or - how do I get webpack to include a script tag into the HTML based off of my environment? I only want a certain script tag to be included if I'm running in production.

Here is what my current webpack file looks like (I'm using webpack 2).

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'react', 'react-dom', 'react-router', 'react-apollo', 'prop-types'
];

module.exports = {
  entry: {
    bundle: './client/src/index.js',
    vendor: VENDOR_LIBS
  },
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].[chunkhash].js'
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader"
            }]
      },
      {
        test: /\.(jpe?g|png|gif|svg|)$/,
        use: [
          {
            loader: 'url-loader',
            options: {limit: 40000}
          },
          'image-webpack-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new HtmlWebpackPlugin({
      template: './client/src/index.html'
    })
  ]
};

Solution

  • Webpack always looks for a webpack.config.js file so you must do the following configurations to make it dynamic:

    package.json

    "dev": "webpack-dev-server --env=dev",
    "prod": webpack -p --env=prod
    

    webpack.config.js

    module.exports = function(env) {
      return require(`./webpack.${env}.js`)
    }
    

    Setting the --env=[env] flag is key.

    I then had two different webpack files. One called wepback.dev.js and one called webpack.prod.js. Based on the package.json command it would run which ever. Then I had created two different index.html files - index.prod.html and index.dev.html. Inside of those I included any scripts I needed for each environment.

    I'm using webpack 2. In each of the files my plugins area looks as so:

    webpack.dev.js

    plugins: [
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest']
      }),
      new HtmlWebpackPlugin({
        template: './client/src/index.dev.html'
      })
    ]
    

    As you can see in this example, my webpack.dev.js will output everything into my index.dev.html file. The prod version will mirror the same except using prod. To see the full webpack file look at the original post.