无法在运行时使用webpack更新提供的变量。

huangapple go评论59阅读模式
英文:

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(&#39;background variables&#39;, backgroundVariables);
backgroundVariables.captureLogs = true;

<!-- end snippet -->

And it is throwing me this error.

无法在运行时使用webpack更新提供的变量。

答案1

得分: 0

`DefinePlugin` 用你的代码替换变量 --- 它不会设置任何变量,所以尝试:

    let localBackgroundVariables = backgroundVariables;
    // 实际上,上述行实际上被替换为:
    // let localBackgroundVariables = {&quot;recordingStatus&quot;:...};
    console.log(&#39;背景变量&#39;, localBackgroundVariables);
    localBackgroundVariables.captureLogs = true;

另外,我建议在这种情况下使用更明确的变量名,比如 `process.env.BACKGROUND_VARS`,以区分它来自 `DefinePlugin`。

    plugins: [
      new webpack.DefinePlugin({
        &#39;process.env.BACKGROUND_VARS&#39;: JSON.stringify(backgroundVariables),
      }),
    ]

-&gt;

    let localBackgroundVariables = process.env.BACKGROUND_VARS;
    console.log(&#39;背景变量&#39;, 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 = {&quot;recordingStatus&quot;:...};
console.log(&#39;background variables&#39;, 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({
    &#39;process.env.BACKGROUND_VARS&#39;: JSON.stringify(backgroundVariables),
  }),
]

->

let localBackgroundVariables = process.env.BACKGROUND_VARS;
console.log(&#39;background variables&#39;, localBackgroundVariables);
localBackgroundVariables.captureLogs = true;

huangapple
  • 本文由 发表于 2023年5月22日 21:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76306804.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定