最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Webpack's define plugin: variable is not defined - Stack Overflow

programmeradmin1浏览0评论

I'm trying to pass some environment related variables into my React ponents using Webpack's DefinePlugin. Client side part works great, server side part returns 'MYVARIABLE is not defined'.

I'm using Webpack's Node.JS api. Important parts are below. Am I doing something wrong? Thanks

webpack.config.js

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

server.js

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

ponent file

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

result

ReferenceError: MYVARIABLE is not defined
....

I'm trying to pass some environment related variables into my React ponents using Webpack's DefinePlugin. Client side part works great, server side part returns 'MYVARIABLE is not defined'.

I'm using Webpack's Node.JS api. Important parts are below. Am I doing something wrong? Thanks

webpack.config.js

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

server.js

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

ponent file

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

result

ReferenceError: MYVARIABLE is not defined
....
Share Improve this question asked Jun 24, 2016 at 12:08 user2595304user2595304 2362 gold badges6 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You have to JSON.stringify('your-value').

According https://webpack.js/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').

so your webpack.config.js should be...

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

评论列表(0)

  1. 暂无评论