Passing command line arguments to webpack.config.js

前端 未结 4 753
甜味超标
甜味超标 2021-01-03 17:44

I have a simple webpack.config.js

module.exports = {
  entry: \"./app.js\",
  output: {
    filename: \"bundle.js\"
  },
}

And I want to p

相关标签:
4条回答
  • 2021-01-03 18:10

    webpack.config.js can also exports a function of env which can return a conf object. You can therefore have a webpack config like:

    module.exports = env => {
        return {
            entry: env === "production" ? "./app.js": "app-dev.js",
            output: {
              filename: "bundle.js"
            },
        }
    };
    

    and then call webpack from command-line (or package.json) like this:

    webpack --env=production
    
    0 讨论(0)
  • 2021-01-03 18:12

    You may use argv package and set the variables. You must do it before module.export.

    0 讨论(0)
  • 2021-01-03 18:13

    The easiest way, in my opinion, to pass arguments is to use Node. Webpack being the one receiving the arguments, you can save your command line arguments in a dedicated environment variable (which exists only within the session):

    // webpack.config.js 
    process.env.MY_APPLICATION_NAME_ARGS = JSON.stringify(process.argv)
    
    export default {
    ...
    

    Then in your main.js (anywhere where you want to parse them), you retrieve your command line arguments from your dedicated environment variable.

    // main.js
    const myArgs = JSON.parse(env.MY_APPLICATION_NAME_ARGS )
    

    As you'll be retrieving all of the arguments you passed to Webpack, using this, you'll be able to use any node modules (like yargs for instance) painlessly to parse them (or do it manually of course).

    So you'll be able to do things like these without any issues:

    webpack ... --opt1 the_value --custom1 something
    
    yarn run dev --opt1 the_value --custom1 something
    

    etc.

    0 讨论(0)
  • 2021-01-03 18:17

    You can provide custom parameters on the env variable from the command line, so for this example you could call:

    webpack --env.entry='./app.js' --env.output='bundle.js'

    and use them in your webpack by doing

    module.exports = env => ({
      entry: env.entry,
      output: {
        filename: env.output
      },
    });
    
    0 讨论(0)
提交回复
热议问题