Webpack dev server custom parameters from command line

流过昼夜 提交于 2020-08-22 08:31:56

问题


I want to pass custom parameters from command line. Something like this:

webpack-dev-server --inline --hot --customparam1=value

Exactly what I am trying to achieve is that I am working on a vue-loader application. The application has certain services that fetch data.

I have another application that acts as the api server. We need the application to run in 2 ways (because all members of our team don't have access to the api server)

So that service has 2 ways to get data:

1) If api server is running(for dev team), use http calls to get the data from localhost

2) If api server is not running(for design team), simply use static data already there in services:

var someData;
if (customparam1 === "withApi"){
   someData=getData("http://localhost:8081/apiendpoint");
} else {
   someData=[
       {a:b},
       {c:d},
       // more custom array of static data
       .....
   ]
}

So this customparam1 is supposed to be passed from webpack-dev-server command line and as per this documentation, no such way exists that I could find(did I miss something?)

How do I do it?

PS: I am on webpack 1.12.1


回答1:


Update: 2020 / 2 / 16

1. webpack^4

If you are using webpack4 or the latest one, using the environment variables is very handy!

The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js. For example, --env.production or --env.NODE_ENV=local (NODE_ENV is conventionally used to define the environment type, see here.)

For example, the command is like:

env.NODE_ENV=development webpack-dev-server

Inside the webpack.config.js, we can define the env variable inside new webpack.DefinePlugin() to make it available in the app.

webpack.config.js:(plugin)

// pass the env and return the webpack setting
module.exports = env => {  
  console.log(env);

  return {
    ....
    plugins: [
      new HtmlWebpackPlugin({
        template: "./public/index.pug",
        inject: false
      }),
      new webpack.DefinePlugin({ customparam1: JSON.stringify(env.customparam1) })
    ],

        }
      ]
     ....
    }
  };
};


2. create-react-app

Check react-create-app doc, the variable will start with REACT_APP_

command: REACT_APP_CUSTOM_VARIABLE=234 npm run dev

app:

console.log(process.env.REACT_APP_CUSTOM_VARIABLE) // 234

3. old answer

command:

webpack-dev-server  --customparam1=value

webpack.config.js:

var path = require("path");
var webpack = require("webpack");

function findPara(param){
    let result = '';
    process.argv.forEach((argv)=>{
        if(argv.indexOf('--' + param) === -1) return;
        result = argv.split('=')[1];
    });
    return  result;
}

const customparam1 = findPara('customparam1');

module.exports = {
   ...
    plugins: [
        new webpack.DefinePlugin({ 
            customparam1:JSON.stringify(customparam1) 
        })
    ]
};

main js file:

if(customparam1 === xxx){ ... }



回答2:


You can use the --define option, which takes var=value as argument. Webpack will simply replace all the occurrences with the value. For example with the following code:

if (ENABLE_API) {
  // Use api
} else {
  // Use static data
}

When you run:

webpack-dev-server --inline --hot --define ENABLE_API

it will result in:

if (true) {
  // Use api
} else {
  // Use static data
}

You would also need to run it with --define ENABLE_API=false, otherwise it will throw an error that ENABLE_API is not defined. As it's a simple text replacement, the value you pass will be inserted as is, so if you want a string you'd have to use '"value"' (note quotes inside quotes) otherwise it is interpreted as regular JavaScript, but I couldn't get a string to work from the command line.

You can achieve the exact same by using webpack.DefinePlugin (I linked the webpack 2 docs, but it works the same in webpack 1). With that you can have more complex replacements and are also able to use utilities like JSON.stringify to create a string version. For instance to overcome the problem with passing a string from the command line, you can use:

new webpack.DefinePlugin({
  API_TYPE: JSON.stringify(process.env.API_TYPE)
})

And run with the environment variable API_TYPE set to withApi:

API_TYPE=withApi webpack-dev-server --inline --hot

and every API_TYPE will be replaced with the string 'withApi', if you don't specify it at all, it will just be undefined.




回答3:


In webpack.config.js, if you export configuration as a function (instead of an object) you can easily access the provided options:

module.exports = (env, argv) => {
    const customparam1 = argv.customparam1;
    // ...
}

webpack docs:

The function will be invoked with two arguments:

  • environment [...]
  • An options map (argv) [...] (which) describes the options passed to webpack

Note:

If you provide:

webpack-dev-server --customparam1=true --customparam2=42

typeof argv.customparam1  // string
typeof argv.customparam2  // number



回答4:


webpack-dev-server --customparam1=value does not work, only well-known arguments are allowed by webpack-dev-server.

However, it is possible to pass environmental parameters (not environment variables) into a webpack config, if it is returned as a function.

A command line parameter --env.param=value, as in:

webpack-dev-server --env.param=value

will be available in the webpack.config.js as follows:

module.exports = env => {
  console.log(env.param)
  return {
    // normal webpack config goes here, as e.g.
    entry: __dirname + "/src/app/index.js",
    output: {
      // ...
    },
    module: {
      // ...
    },
    plugins: [
      // ...
    ] 
    // ...
  }
}

Such parameters can obviously be passed into the app using webpack.DefinePlugin as outlined above in @AppleJam's answer.




回答5:


anyway, passing custom parameters is not allowed in webpack-dev-server.

but we can use some existed parameters, like --env --define --open, to pass our own values.

just write:

webpack-dev-server --env=someparams

then you can use the yargs to read your parameters.

done!



来源:https://stackoverflow.com/questions/42840422/webpack-dev-server-custom-parameters-from-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!