Injecting variables into webpack

2020-06-12 03:31发布

问题:

I'm trying to inject a variable into each module within my webpack bundle in order to have debugging information for JS errors per file. I've enabled

node: {
   __filename: true
}

Current file path in webpack

in my webpack.config, but I would like to inject something like

var filename = 'My filename is: ' + __filename;

into each module before compilation. I've seen the Banner Plugin with the raw option but it seems this would only inject the banner outside of the webpack closure rather than my desired result of injecting script into each module.

回答1:

I use variables to resolve a couple of variables in my webpack.config.js file:

plugins: [
    new webpack.DefinePlugin({
      ENVIRONMENT: JSON.stringify(process.env.NODE_ENV || 'development'),
      VERSION: JSON.stringify(require('./package.json').version)
    })
]

It might not be dynamic enough, but if it is, then you might be able to bypass that loader solution.



回答2:

Write your own loader:

my_project/my_loaders/filename-loader.js:

module.exports = function(source) {
  var injection = 'var __filename = "' + this.resourcePath + '";\n';
  return injection + source;
};

Add it to your pipeline and make sure to add also the configuration:

resolveLoader: {
  modulesDirectories: ["my_loaders", "node_modules"]
}

See the documentation on how to write a loader.