How can I replace files at compile time using webpack?

5tarter picture 5tarter · Jul 14, 2018 · Viewed 9.5k times · Source

I have a project with miltiple configuration. The first config is config.dev.js file that contains some development configiration. I using it in development mode. The second config is config.js file. I using it in production mode.

In the code I using imports:

import * as config from './config.js';

I want to use the first config file in development and the second to production whithout rewriting all of the imports. How can I replace this config depending on the build mode?

Answer

Jacques ジャック picture Jacques ジャック · Mar 14, 2019

I realize this is an old post, but this is one of the first results on Google, so I thought a better answer would be good.

Webpack has a built in "Normal Module Replacement Plugin".

plugins: [
  new webpack.NormalModuleReplacementPlugin(
    /some\/path\/config\.development\.js/,
    './config.production.js'
  )
]

For my use, I put the env file in a variable Here is an example:

let envFilePath = './environment.dev.js';
if (env === 'production') {
  envFilePath = './environment.prod.js';
} else if (env === 'staging') {
  envFilePath = './environment.stg.js';
}

module.exports = {
    // other webpack stuff
    ....
    plugins:[ 
        new webpack.NormalModuleReplacementPlugin(
            /src\/environment\/environment\.js/,
            envFilePath
        ),
        ...
    ]
}