MaxWidth
MaxWidth

Reputation: 518

Detect inside webpack file which package.json script command was run

In webpack.config.js file, I need the publicPath to be http://localhost:3000 when I use it in development (npm run dev) and for production (npm run build) I need it to be /dist.

Currently, when I want production build I always manually change the publicPath from http://localhost:3000 to /dist. Is there a way that I can do that automatically based on the npm script command being run? it shall automatically use http://localhost:3000 when npm run dev and /dist when npm run build.

package.json-file:

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

webpack-file:

output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    // publicPath: 'http://localhost:3000'
    publicPath: '/dist'
},

Upvotes: 2

Views: 450

Answers (1)

masa
masa

Reputation: 2820

Turn your webpack.config.js module exports into a function and access mode via argv:

module.exports = (env, argv) => {
    return {
        ...
        output: {
            path: path.join(__dirname, 'dist'),
            filename: 'bundle.js',
            publicPath: argv.mode === 'production' ? 'dist' : 'http://localhost:3000'
        }
    }
};

Upvotes: 2

Related Questions