大家在日常开发上线,上预发,测试环境的时候,一定遇到过不同环境,配置项不同的情况,比如不同的环境部署的代码一致,只有Host需要配置不同。这个时候,如果每次都要重新修改代码,不仅显得不专业,也容易在提交的时候忘记这个配置,提交错误就是上线灾难。所以,有必要在打包后的文件中生成配置文件,供在外部修改配置。本篇就是为了解决这个问题而写~~
这要用到一个webpack插件generate-asset-webpack-plugin
Install
npm install --save-dev generate-asset-webpack-plugin
在webpack.prod.cong.js中引入该插件
const GeneraterAssetPlugin = require('generate-asset-webpack-plugin')
在项目根目录下建立配置文件serverConfig.json
内部配置为{"baseUrl":""}
将该配置文件引入
const serverConfig = require('../serverConfig.json')
将Json中的配置项返回
const createJson = function(compilation) { return JSON.stringify(serverConfig) }
在webpackConfig -> plugin中写入
new GeneraterAssetPlugin({ filename: 'serverConfig.json',//输出到dist根目录下的serverConfig.json文件,名字可以按需改 fn: (compilation, cb) => { cb(null, createJson(compilation)); } })
在引入axios的文件中做如下配置
axios.get('serverConfig.json').then((result) => { window.localStorage['JSON_HOST'] = result.data.baseUrl }).catch((error) => { console.log(error) });
利用localStorage存储JSON_HOST配置值,需要取时再取出JSON_HOST,再将需要配置host的地方写成
host: window.localStorage['JSON_HOST']
打包后在根目录就会生成如下dist文件
外部就可以通过修改该配置文件,变更host了