应用场景
- 在实际工作中,为了调试方便,可能需要随时更换接口环境、加解密等相关配置。如果每次调试都重新打包,操作起来比较麻烦,且 webpack 打包之后的内容无法进行反向编译。
- 我们可以在全局暴露出一个配置文件,使这个文件不会被 webpack 打包,以此用来控制我们需要频繁更改的配置参数。
目录结构及使用
- 在 static 文件下新建一个 js 文件,我这里起名为 config.js
|-- public
|-- |-- js
|-- |-- static
|-- |-- |-- config.js
|-- |-- index.html
|-- dist
- 在 config.js 中,把需要控制的变量绑定到 window 上
window.global = {
somethingFlag: false,
baseUrl:'http://XXX.XXX.com',
// 。。。 其他需要配置的内容
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>test</title>
<!-- 引入全局配置文件 -->
<script src="static/config.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
- 代码中使用的时候,只需要访问 window 上绑定的这个对象即可
if(window.global.somethingFlag) {
// somethingFlag 为 true 时做一些事
} else {
// somethingFlag 为 false 时做一些事
}
// 创建axios实例
const service = axios.create({
baseURL: window.global.baseUrl,// 请求根目录
timeout: 20000 // 请求超时时间
})
- 配置好文件后,进行打包,就会发现 static 中添加的 config.js 没有被打包,并且修改 config.js 中的内容后,配置会生效。
|-- dist
|-- |-- css
|-- |-- fonts
|-- |-- img
|-- |-- js
|-- |-- static
|-- |-- |-- config.js
|-- |-- index.html
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。