Passing command line arguments to webpack.config.js

前端 未结 4 752
甜味超标
甜味超标 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: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.

提交回复
热议问题