javascript 将变量注入 webpack
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28145397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Injecting variables into webpack
提问by dtothefp
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
我试图在我的 webpack 包中的每个模块中注入一个变量,以便为每个文件的 JS 错误提供调试信息。我已启用
node: {
__filename: true
}
in my webpack.config, but I would like to inject something like
在我的 webpack.config 中,但我想注入类似
var filename = 'My filename is: ' + __filename;
into each module before compilation. I've seen the Banner Pluginwith 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.
编译前进入每个模块。我已经看到带有选项的横幅插件,raw
但似乎这只会在 webpack 闭包之外注入横幅,而不是我想要的将脚本注入每个模块的结果。
回答by Marcus R?dell
I use variables to resolve a couple of variables in my webpack.config.js
file:
我使用变量来解析webpack.config.js
文件中的几个变量:
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.
它可能不够动态,但如果是,那么您可能能够绕过该加载程序解决方案。
回答by Ricardo Stuven
Write your own loader:
编写自己的加载器:
my_project/my_loaders/filename-loader.js:
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.
请参阅有关如何编写加载程序的文档。