vue.config.js
中chainWebpack
反对异步数据
前言
我的项目背景
- 我的项目应用
vue-cli4
搭建的,如需批改Webpack
的配置,须要批改vue.config.js
。 - 我的项目中,在
chainWebpack
中调用了html-webpack-plugin
生成dev.html
文件。 html-webpack-plugin
的配置templateParameters
反对模板参数注入,反对对象和办法。本文就是基于这个配置做文章。如何配置可参考:templateParameters demo在html页面接管foo参数,即可取得
bar
值:<script><%= foo %></script>
需要
- 须要在
dev.html
注入一些数据,而这些数据是异步获取的(调用接口或者其余形式)。我这里是须要通过Node.js的child_process
执行git命令,获取分支信息。
尝试
templateParameters
反对function
。能够尝试传入async
办法,通过await
获取到数据后,再返回。
遇到问题
chainWebpack
和templateParameters
均不反对异步。chainWebpack
改为异步后,打包报错。templateParameters
改为异步后,虽不影响打包,然而变量不失效。
苦于vue-cli-service
和html-webpack-plugin
均不反对异步,只能另想办法。
解决
查阅材料
先通过百度,国内貌似没有相似的记录文章。而后Google,果然找到了相似需要:
Vue config async support
有人提出了相似的issue,尽管作者没有间接解决,然而也给出了一个work around:
改代码
这个办法的思路,实际上将npm run serve
包了一层wrap,在外层拿到数据后,再通过代码调用npm run serve
开始打包。接下来咱们来实现这个wrap。
首先新建一个文件
serve.prehandle.js
,用于wrap。先获取异步数据,待拿到之后再开始打包:const getGitDevInfo = require('./src/pages/demo/webpack-plugin/git-info')const isDevEnv = process.env.NODE_ENV !== 'production'module.exports = (api, options) => { api.registerCommand('serve:prehandle', async (args) => { if (isDevEnv) { const def = await getGitDevInfo() process.asyncParamter = def } await api.service.run('serve', args) })}module.exports.defaultModes = { 'serve:prehandle': 'development'}
而后批改
package.json
批改
serve
命令{ "scripts": { "serve": "vue-cli-service serve:prehandle" }}
减少
vuePlugins
,对应下面的serve.prehandle
命令,为这条命令指定解决文件{ "vuePlugins": { "service": ["serve.prehandle.js"] } }
批改
vue.config.js
去接收数据。这里我存在process
全局变量中:config.plugin('html').use(HtmlWebpackPlugin, [{ filename: 'dev.html', template: 'src/pages/demo/index.html', templateParameters: { config: `window.devGitInfo=${JSON.stringify(process.asyncParamter || {})}` }, chunks: ['chunk-vendors', 'chunk-common', 'dev'],}])
接下来,执行后可失效!
npm run serve
相干知识点
vue-cli Service Plugin
vue-cli
反对导入自定义的Service Plugin
,具体参考上面文档:
Project local plugin
Add a new cli-service command