【发布时间】:2019-08-27 03:05:09
【问题描述】:
我想要什么:
在我的 Vue 项目中,当执行 vue run build 时,所有内容都被打包(webpack)到 dist 目录中。
我可以将整个包部署到测试服务器,但由于测试服务器需要另一组凭据(用于数据库等),因此每个环境中必须有一个文件,即 config.js。
我的策略:
- 排除
config.js被打包到 app.12314...js 包中 - 将
config.js定义为作为文件原样发出(通过webpack 的file-loader)
我做了什么:
在需要配置数据的Vue组件文件中,配置通过:
<script>
import config from '@/config/config.js';
</script>
我创建了一个vue.config.js 文件来修改默认的 webpack 设置,如下所示:
const path = require("path");
// vue.config.js
module.exports = {
publicPath: '/',
configureWebpack: {
module: {
rules: [
{
test: /config.*config\.js$/,
use: [
{
// exclude config file from being packed. The config file should simply reside as a plain file on the
// file system, since it must be replaced with the target environoment specific config file on the server,
// e.g. for setting the correct database connection
loader: 'file-loader',
options: {
name: 'config/config.js'
},
}
]
}
]
}
}
}
我的预期:
-
config.js将作为普通文件发出,而不是捆绑 =>dist文件夹将包含一个捆绑的app....js文件和一个单独的config.js文件 - 我可以将
dist文件夹的内容部署到测试服务器,生成的代码将负责加载config.js,以便组件可以使用配置数据李>
问题:
当然,config.js 现在作为文件发出,所以我的 dist 文件夹如下所示:
.
├── config
│ └── config.js
├── css
│ ├── app.eb377513.css
│ └── chunk-vendors.2da46af1.css
├── favicon.png
├── index.html
└── js
├── app.724607ed.js
├── app.724607ed.js.map
├── chunk-vendors.426dad42.js
└── chunk-vendors.426dad42.js.map
如您所见,一个单独的文件config.js!所有其他 JS 代码已捆绑到 app.724607ed.js。到目前为止,一切顺利。
但是,测试服务器上的应用程序不会加载config.js,因此每个尝试使用其中变量的组件都会失败。
我注意到在 Chrome 的开发者工具中,config.js 没有网络流量。显然,webpack 代码并没有尝试从文件系统中实际加载文件。我预计会自动出现这种情况。
- 我做错了什么,我错过了什么?
- 这是排除配置文件被打包的最佳做法吗?
【问题讨论】: