gpt4 book ai didi

javascript - Webpack 的定义插件 : variable is not defined

转载 作者:行者123 更新时间:2023-11-30 09:47:56 24 4
gpt4 key购买 nike

我正在尝试使用 Webpack 的 DefinePlugin 将一些与环境相关的变量传递到我的 React 组件中。客户端部分运行良好,服务器端部分返回“MYVARIABLE 未定义”。

我正在使用 Webpack 的 Node.JS api。重要部分如下。难道我做错了什么?谢谢

webpack.config.js

...
webpackConfig.plugins = [
new webpack.DefinePlugin({
MYVARIABLE: 'test-value'
})
]
...

服务器.js

...
import webpack from 'webpack'
import webpackConfig from '../config/webpack.config'
...
var compiler = webpack(webpackConfig)
...

组件文件

...
console.log(MYVARIABLE)
...

结果

ReferenceError: MYVARIABLE is not defined
....

最佳答案

你必须 JSON.stringify('your-value').

根据https://webpack.js.org/plugins/define-plugin/ :

because the plugin does a direct text replacement, the value given to it must include actual quotes inside of the string itself. Typically, this is done either with either alternate quotes, such as '"production"', or by using JSON.stringify('production').

所以你的webpack.config.js应该是...

webpackConfig.plugins = [
new webpack.DefinePlugin({
MYVARIABLE: JSON.stringify('test-value')
})
]

关于javascript - Webpack 的定义插件 : variable is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38013104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com