简体   繁体   中英

How to pass Parameters from Web-pack to Code?

I have a gulp task which takes in the parameter location using yargs. And i use webpack to give the entry point to my application

 webpackConfig.entry.push('BootStrapper.ts');

I have a webpack config which has entrypoint to bootstrapper.

module.exports = {
entry: [],
output: {
    path: require("path").resolve('./dist/'),
    filename: 'MyProcess.built.js'
 },
}

I want to pass a variable the location variable to Bootstrapper.ts is there a way to achieve it?

Yes, there is.

First, adjust your webpack config to receive parameters:

{
  plugins: [
    new webpack.DefinePlugin({
      'process.env.YOUR_UNIQUE_VARIABLE': JSON.stringify(process.env.YOUR_UNIQUE_VARIABLE)
    )
  ]
}

then, in your Bootstrapper.ts you can write something like this:

const buildVariable = process.env.YOUR_UNIQUE_VARIABLE;

If you now run your webpack script (I assume to run a npm script) passing the variable like:

cross-env YOUR_UNIQUE_VARIABLE=value webpack

your code will be compiled to:

const buildVariable = 'value';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM