英文:
Not able to update variable provided during runtime using webpack
问题
I am using webpack to provide variable during runtime into a js file.
将变量在运行时传递到一个js文件中。
And changing variable through js file like this.
然后通过js文件来改变变量,像这样。
And it is throwing me this error.
但是它抛出了这个错误。
英文:
I am using webpack to provide variable during runtime into a js file.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
plugins: [
new webpack.DefinePlugin({
backgroundVariables: JSON.stringify(backgroundVariables),
}),
]
<!-- end snippet -->
And changing variable through js file like this.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
console.log('background variables', backgroundVariables);
backgroundVariables.captureLogs = true;
<!-- end snippet -->
And it is throwing me this error.
答案1
得分: 0
`DefinePlugin` 用你的代码替换变量 --- 它不会设置任何变量,所以尝试:
let localBackgroundVariables = backgroundVariables;
// 实际上,上述行实际上被替换为:
// let localBackgroundVariables = {"recordingStatus":...};
console.log('背景变量', localBackgroundVariables);
localBackgroundVariables.captureLogs = true;
另外,我建议在这种情况下使用更明确的变量名,比如 `process.env.BACKGROUND_VARS`,以区分它来自 `DefinePlugin`。
plugins: [
new webpack.DefinePlugin({
'process.env.BACKGROUND_VARS': JSON.stringify(backgroundVariables),
}),
]
->
let localBackgroundVariables = process.env.BACKGROUND_VARS;
console.log('背景变量', localBackgroundVariables);
localBackgroundVariables.captureLogs = true;
英文:
DefinePlugin
replaces the variable with your code --- it doesn't setup any such variable, so try:
let localBackgroundVariables = backgroundVariables;
// essentially the above line is actually replaced by:
// let localBackgroundVariables = {"recordingStatus":...};
console.log('background variables', localBackgroundVariables);
localBackgroundVariables.captureLogs = true;
Also I would recommend using more defined variable names in this case, like process.env.BACKGROUND_VARS
to distinguish it came from DefinePlugin
.
plugins: [
new webpack.DefinePlugin({
'process.env.BACKGROUND_VARS': JSON.stringify(backgroundVariables),
}),
]
->
let localBackgroundVariables = process.env.BACKGROUND_VARS;
console.log('background variables', localBackgroundVariables);
localBackgroundVariables.captureLogs = true;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论