vue.js - vue 环境变量返回空对象
问题描述
我是 vue 和 webpack 的新手,当我在 vue 应用程序中使用 console.log(process.env.VUE_APP_API_URL) 时,会返回一个空对象。我有一个 .env.development 文件,其中包含:
VUE_APP_API_URL=http://localhost:8000/api
应用程序后端内置在 laravel 中,运行良好。但我希望能够将 api url 存储为环境变量。
我的 webpack.config.js
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
],
},
{
test: /\.sass$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
],
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': [
'vue-style-loader',
'css-loader',
'sass-loader'
],
'sass': [
'vue-style-loader',
'css-loader',
'sass-loader?indentedSyntax'
]
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
},
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
}),
])
}
我尝试运行 npm install dotenv-webpack --save-dev 并将其添加到 webpack 插件,但它仍然没有解决问题。我该如何解决这个问题?
解决方案
为了从 .env 文件加载配置,您需要先安装 dotenv 依赖项,并require("dotenv").config()
在调用变量之前调用。这将加载变量并使用process.env.YOUR_VARIABLES
推荐阅读
- r - R 使用数字 2 前缀 nrow 函数?
- javascript - 汉堡菜单未显示在移动视图中的图库页面上,在其他任何地方都可以使用
- python - 在 DataFrame 中搜索不完整的重复行时处理 NaN
- flutter - Dart 如何通过键过滤地图
- google-apps-script - 如何在 Google 表单中的单个问题上使用 Google Apps 脚本?
- python - 无法安装海妖(图像优化器)
- go - 寻找值开头的无效字符“R”
- javascript - Raspberry Pi Fask 服务器:无法使用 AJAX 和损坏的 id 搜索在文件夹中找到图像
- mongodb - 查询以在对象数组中的所有对象都匹配时返回结果
- laravel - 检查密码是否等于用户密码Laravel 7