13

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.

Community
  • 1
  • 1
dtothefp
  • 1,364
  • 1
  • 16
  • 22

2 Answers2

21

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.

Marcus Rådell
  • 622
  • 7
  • 12
  • 1
    To pass in variables dynamically you can still use this plugin. Just say when building: webpack --define myurl="http://localhost:3000" – Richard May 11 '16 at 15:17
  • 1
    why do you use JSON.stringify on process.env.NODE_ENV? – Ryder Bergerud Jul 19 '16 at 02:57
  • If, say, VERSION is used as a variable in code, and JSON.stringify is not used (or another mechanism that added quotes), then you end up with something like this (a compiler error): console.log(VERSION) -> console.log(1.0.0), when you wanted console.log("1.0.0") – Prasad Silva Aug 18 '16 at 20:48
  • this is the best way to do it i think. – Hitori Mar 23 '18 at 03:16
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.

Ricardo Stuven
  • 4,704
  • 2
  • 34
  • 36
  • I created this loader https://github.com/optimizely/marketing-website/blob/dfoxpowell/jordan-webpack-try/loaders/inject-filename-loader.js which works great but it is not working for some reason in our prod CI build. I posted a question here http://stackoverflow.com/questions/29850802/webpack-loader-not-working-on-jenkins-ci-build and it's driving me crazy if you have any ideas? – dtothefp Apr 25 '15 at 19:35