最近嘗試將vue項目中的后台URL抽離到打包后的配置文件中,看到有使用generate-asset-plugin在build時生成配置文件的做法,倒騰了一下午使該webpack plugin在vue-cli3中生效,雖然后面換了其他方法,也在此Mark一下,方便遇到的朋友快速過坑。
1.安裝插件
npm install -save generate-asset-webpack-plugin
2.使用插件
vue-cli3中webpack的打包配置都放在根目錄下vue.config.js中哦,vue-cli2放在build目錄下。
1)引入plugin
const GenerateAssetPlugin = require('generate-asset-webpack-plugin');
2)定義需要生成的配置內容,配置項在cfgJson對象中定義,該函數在plugin中用到
let createConfig = function(compilation){ let cfgJson = { server_url:"http://127.0.0.1" }; return JSON.stringify(cfgJson); }
3)在module.exports中調用plugin:在module.exports中增加屬性configureWebpack,configureWebpack的plugins中調用plugin(其他plugin也可以在這里引入,與vue-cli2方法一致)。小編在這里設置的時候看到了module.exports的chainWebpack屬性,這個屬性也可以用來配置webpack,但可能太高級了,搞了很久不知道怎么引入其他plugin,就放棄了直接使用configureWebpack。
module.exports = { configureWebpack: { plugins: [ new GenerateAssetPlugin({ filename: 'dynamicConfig.json', fn: (compilation, cb){ cb(null, createConfig(compilation)) } }) ] } }
3.編譯后,dist根目錄下就會出現dynamicConfig.json文件啦
generate-asset-webpack-plugin