webpack打包dist文件導出配置文件.json供外部配置

你們在平常開發上線,上預發,測試環境的時候,必定遇到過不一樣環境,配置項不一樣的狀況,好比不一樣的環境部署的代碼一致,只有Host須要配置不一樣。這個時候,若是每次都要從新修改代碼,不只顯得不專業,也容易在提交的時候忘記這個配置,提交錯誤就是上線災難。因此,有必要在打包後的文件中生成配置文件,供在外部修改配置。本篇就是爲了解決這個問題而寫~~webpack

這要用到一個webpack插件generate-asset-webpack-pluginios

Install

npm install --save-dev generate-asset-webpack-plugin

在webpack.prod.cong.js中引入該插件web

const GeneraterAssetPlugin = require('generate-asset-webpack-plugin')

在項目根目錄下創建配置文件serverConfig.json
內部配置爲{"baseUrl":""}
將該配置文件引入npm

const serverConfig = require('../serverConfig.json')

將Json中的配置項返回json

const createJson = function(compilation) {
  return JSON.stringify(serverConfig)
}

在webpackConfig -> plugin中寫入axios

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的地方寫成ui

host: window.localStorage['JSON_HOST']

打包後在根目錄就會生成以下dist文件spa

clipboard.png
外部就能夠經過修改該配置文件,變動host了 插件

clipboard.png

相關文章
相關標籤/搜索