访问Vue.js上的“ process.env”时出现语法错误

时间:2019-07-05 12:10:04

标签: node.js vue.js webpack

当我尝试访问变量:process.env时遇到问题。它告诉我语法错误,而且我100%确定我的代码正确。 我想知道它有什么问题

我试图一遍又一遍地检查我的代码。我找不到任何语法错误。顺便说一句,当我访问proceess变量时就可以了。但是,当我尝试访问process.env时,它开始执行eval,这引起了我前面提到的错误。

我的代码是这样的:

src/global.vue

console.log(process.env);

我得到的错误:


Uncaught SyntaxError: Unexpected token :
    at Object../node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue (app.js:1170)
    at __webpack_require__ (app.js:679)
    at fn (app.js:89)
    at eval (App.vue?9e04:1)
    at Object../src/App.vue (app.js:5245)
    at __webpack_require__ (app.js:679)
    at fn (app.js:89)
    at eval (main.js:5)
    at Object../src/main.js (app.js:5357)
    at __webpack_require__ (app.js:679)

app.js:1170做到了:

eval("/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__components_headers__ = __webpack_require__(\"./src/components/headers.vue\");\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_blogfooter__ = __webpack_require__(\"./src/components/blogfooter.vue\");\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n// import axios from 'axios'\n\n\n/* harmony default export */ __webpack_exports__[\"a\"] = ({\n  name: 'App',\n  components: { 'headers': __WEBPACK_IMPORTED_MODULE_0__components_headers__[\"a\" /* default */],\n    'blog-footer': __WEBPACK_IMPORTED_MODULE_1__components_blogfooter__[\"a\" /* default */]\n  },\n  created: function created() {\n    this.$store.dispatch('GET_BASIC');\n    console.log(Object({\"NODE_ENV\":\"development\",\"SERVER\":http://localhost:8000}));\n  }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcyEuL25vZGVfbW9kdWxlcy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7Ozs7Ozs7QUFhQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQURBO0FBR0E7QUFDQTtBQUNBO0FBQ0E7QUFSQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue\n");

我通过在变量SERVER的值上加上双引号来解决它:

旧代码

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  SERVER: 'http://localhost:8000'
})

新代码

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  SERVER: '"http://localhost:8000"'
})

我不知道为什么没有提示告诉我那件事。配置文件的语法太奇怪了,您需要将引号放在现有引号之外。

谁能告诉我为什么?

2 个答案:

答案 0 :(得分:1)

在检查了app.js:1170中的错误之后,您可以看到您的process.env.server以某种方式错过了-为什么这没有头绪,但我认为现在应该可以解决了^^ < / p>

当前:

{server: http://localhost:8000}

但应该是

{server:"http://localhost:8000"}

答案 1 :(得分:0)

我在使用 webpack 的项目中工作时遇到了类似的问题,我将 .env 配置为 node 和测试环境,但是在 web 环境中运行时,同样的错误消息,好像过程。 envdid not exist. In my case I was using the dotenv lib, so it was pretty simple to solve, I just saw that theJSON.stringifysetting inDefinePlugin` 缺失。

以这种方式解决了配置问题:

new webpack.DefinePlugin({
  "process.env": JSON.stringify(dotenv.parsed),
})