詳解組件庫的webpack構(gòu)建速度優(yōu)化
背景
在公司的主要工作是組件庫(基于vue的ui組件庫,類似element-ui)的開發(fā),也已經(jīng)有兩個(gè)多月,期間一直覺得項(xiàng)目的開發(fā)構(gòu)建太慢,每次開發(fā)打開開發(fā)環(huán)境需要 40s 左右,簡直不能忍。前前后后嘗試了各種優(yōu)化手段,但是都不理想。終于在今天,找到了問題所在,構(gòu)建速度提升了 50% 以上,現(xiàn)在只需要 17s 左右,整個(gè)心情都好了。現(xiàn)在記錄一下所用到的各種優(yōu)化手段,因?yàn)槭情_發(fā)環(huán)境,所以只考慮構(gòu)建速度。
各種配置項(xiàng)的優(yōu)化
主要是對(duì)一些loader添加 include exclude之類的小優(yōu)化,其實(shí)這一點(diǎn)并沒有帶來多少性能的提升,只是一些安慰作用吧。
引入happypack
之前有看到相關(guān)文章介紹 happypack 采用多線程處理,能大大提升項(xiàng)目的構(gòu)建速度。嗯,我覺得這個(gè)靠譜??戳讼耮ithub上的文檔,趕緊試試水。
修改webpack一些loader配置,使用happypack
// config.dev.js
{
// ...
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: {
// 這里估計(jì)是都懶得寫lang='scss'
css: 'style-loader!css-loader!sass-loader',
// vue文件中基本不存在css代碼,所以只把js交給happypack處理
js: 'happypack/loader?id=babel'
}
}, {
test: /\.js$/,
use: 'happypack/loader?id=babel',
exclude: /node_modules/,
// components目錄是組件,examples目錄主要是markdown文檔,test目錄是單元測試
include: [utils.resolve('./components'), utils.resolve('./examples'), utils.resolve('./test')]
}, {
test: /\.scss$/,
use: 'happypack/loader?id=scss'
}]
},
plugins: [
new HappyPack({
id: 'babel',
threads: 4,
loaders: ['babel-loader']
}),
new HappyPack({
id: 'scss',
threads: 4,
loaders: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
path: utils.resolve('./postcss.config.js')
}
}
},
'sass-loader'
]
})
]
// ...
}
這里主要將組件庫中各種需要處理的文件都采用happypack處理,除了上面的 js scss vue 之外,也把 md (vue-markdown-loader)等進(jìn)行處理,配置都差不多,就不列出來了。
ok,配置完畢,趕緊跑起來試試水。結(jié)果就是報(bào)錯(cuò)了... oh no! 看了下官方文檔說明,不支持 vue-markdown-loader。好吧,把 md 文件的處理改回去,再跑。嗯這次跑起來了,但是時(shí)間也就少了 4s-5s 左右,emmmmm,并沒想象中多。
將運(yùn)行的命令加上--progress能發(fā)現(xiàn),主要耗時(shí)的就是處理 md 文件,很明顯一遇到 md 文件進(jìn)度條的跳動(dòng)就慢下來了。
知道了,優(yōu)化的主要目標(biāo)應(yīng)該是md文件的處理。
找到了 build/util.js 里面的一些處理,部分代碼如下
function render(tokens, idx) {
// tokens是markdown-it parse后的結(jié)果
var m = tokens[idx].info.trim().match(/^demo\s*(.*)$/);
if (tokens[idx].nesting === 1) {
let index = idx + 1;
var html = '';
var style = '';
var script = '';
while (tokens[index].nesting === 0) {
const content = tokens[index].content;
const tag = tokens[index].info;
if (tag === 'html') {
html = convert(striptags.strip(content, ['script', 'style'])).replace(
/(<[^>]*)=""(?=.*>)/g,
'$1'
);
script = striptags.fetch(content, 'script');
style = striptags.fetch(content, 'style');
} else if (tag === 'js' && !script) {
script = striptags.fetch(content, 'script');
} else if (
['css', 'style', 'scss'].indexOf(tag) !== -1 &&
!style
) {
style = striptags.fetch(content, 'style');
}
index++;
}
var description = m && m.length > 1 ? m[1] : '';
var jsfiddle = { html: html, script: script, style: style };
var descriptionHTML = description ? md.render(description) : '';
jsfiddle = md.utils.escapeHtml(JSON.stringify(jsfiddle));
return `
<demo-block class="demo-box" :jsfiddle="${jsfiddle}">
<div class="source" slot="source">${html}</div>
${descriptionHTML}
<div class="hljs highlight" slot="highlight">
`;
}
return '</div></demo-block>\n';
}
主要是將 tip 放到指定的 container 里。還有提取 tokens 里一些標(biāo)記為html js css代碼組成一個(gè)對(duì)象jsfiddle,傳給一個(gè) vue組件,用于提供jsbin的在線調(diào)試功能。利用markdown-it的 render方法,將其他采用markdown語法寫的文檔render成html代碼放到指定div里面,將 html 代碼(其實(shí)就是文檔中的示例代碼)作為slot分發(fā)給上面提到的 vue組件。
這里實(shí)在是沒找到優(yōu)化的手段。
引入dll
另外一個(gè)嘗試的手段是,采用webpack的 DllPlugin 和 DllReferencePlugin 引入dll,讓一些基本不會(huì)改動(dòng)的代碼先打包成靜態(tài)資源,讓 webpack 少處理一些東西
打包dll的配置
// config.dll.js
module.exports = merge(base, {
// ...
entry: {
vendor: ['vue', 'vue-router', 'vue-i18n', 'clipboard']
},
output: {
path: path.resolve(__dirname, './dll'),
filename: '[name].js',
library: '[name]_[hash]'
},
plugins: [
new webpack.DllPlugin({
name: '[name]_[hash]',
path: path.resolve(__dirname, './dll/vendor.manifest.json')
})
]
// ...
})
上面配置打包會(huì)在 build 目錄下生成 dll 目錄,里面有 vendor.dll.js 和 vendor.manifest.json
然后在 config.dev.js 中,引入 DllReferencePlugin
DllReferencePlugin配置
{
plugins: [
new webpack.DllReferencePlugin({
manifest: require('./dll/vendor.manifest.json')
})
]
}
然后記得將打包好的js文件引入,這里可以采用add-asset-html-webpack-plugin
{
plugins: [
new AddAssetHtmlPlugin({
filepath: require.resolve('./dll/vendor.js'),
includeSourcemap: false
})
]
}
這樣,在項(xiàng)目中 webpack 處理 vue vue-router vue-i18n clipboard時(shí),就不會(huì)去node_modules中拿了,會(huì)直接用 vendor.js
再次運(yùn)行 npm run dev 發(fā)現(xiàn)時(shí)間也只少了 1s(我覺得其實(shí)是時(shí)間的小波動(dòng)...根本不會(huì)少的) 畢竟大頭不在這。
單組件的開發(fā)模式
后來突然想到,好像每次開發(fā)組件的時(shí)候,不都是單個(gè)單個(gè)來的嗎,既然這樣,我只處理指定組件的md文件,速度不就起來了嗎。
嗯,這或許是個(gè)辦法,試試水
找到引入 md 文件的地方,也就是 examples/route.js,部分代碼如下
function loadDocs(path) {
return r => require.ensure([],
() => r(require(`./docs${path}.md`))
);
}
這個(gè)是 vue-router 的動(dòng)態(tài)加載,嗯,只要我把path給寫成一個(gè)固定的路徑(這里其實(shí)就是'/' + 組件名),不就能實(shí)現(xiàn)了嗎。
運(yùn)行命令大概是長這樣的
// package.json
{
"scripts": {
"dev:component": "cross-env RUN_ENV=component node build/dev-server.js",
}
}
由于在命令行中使用webpack-dev-server沒有辦法傳遞參數(shù)給process.argv,所以這里采用webpack-hot-middleware
// build/dev-server.js
const webpack = require('webpack');
const webpackConfig = require('./config.dev');
const express = require('express');
webpackConfig.plugins = webpackConfig.plugins || [];
// 全局開發(fā)模式采用webpack-dev-server 無需配置hmr,這里需要單獨(dú)給上
webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
webpackConfig.entry.push('webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000');
const compiler = webpack(webpackConfig);
const hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: false
});
const devMiddleware = require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true,
logLevel: 'silent'
});
const app = express();
app.use(hotMiddleware);
app.use(devMiddleware);
app.use('/build', express.static('./build'));
app.listen(webpackConfig.devServer.port || 8089, '127.0.0.1', () => {
console.log('Starting server on http://localhost:8089');
});
然后采用webpack的 DefinePlugin 動(dòng)態(tài)寫入一個(gè)組件名就搞定了,大致的思路是這樣的。部分實(shí)現(xiàn)如下:
const component = process.argv[2];
// 先判斷一下是不是單組件開發(fā)模式,是的話,必須指定運(yùn)行的組件
if (process.env.RUN_ENV === 'component' && !component) {
throw new Error('component is required, like: npm run dev:component slider');
}
// 然后通過DefinePlugin寫入
// 對(duì)了這里有個(gè)要注意的點(diǎn),path是個(gè)變量,不是字符串,所以不能是"'path'",真tm機(jī)智。
// config.dev.js
{
// ...
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: "'development'",
RUN_ENV: process.env.RUN_ENV === 'component' ? "'component'" : "''",
component: process.env.RUN_ENV === 'component' ? JSON.stringify('/' + component) : 'path'
}
})
]
// ...
}
// 然后再把 `route.js` 的源碼改下
function loadDocs(path) {
return r => require.ensure([],
() => r(require(`./docs${process.env.path}.md`))
);
}
萬事俱備,趕緊跑起來
> DONE Compiled successfully in 10792ms
不錯(cuò)不錯(cuò),只需要10s了,打開瀏覽器看看,也沒問題。嗯 不錯(cuò)。
關(guān)掉服務(wù),試試看原來的 dev 命令是不是也沒問題,嗯,終端是沒問題,但是瀏覽器上報(bào)錯(cuò)了 ???(黑人問號(hào)臉)

好像是 webpack 不能正常的處理,最后是改成了下面這樣才能正常工作
function loadDocs(path) {
return r => require.ensure([],
() => {
if (process.env.RUN_ENV === 'component') {
r(require(`./docs${process.env.component}.md`));
} else {
r(require(`./docs${path}.md`));
}
}
);
}
另外,除了md文件只需要處理一個(gè)組件的之外,組件源碼也有很多是不需要處理的,所以,繼續(xù)修改下代碼
應(yīng)用的入口處將全局引入ui庫的方式換成按需
// 原來的代碼 import Vue from 'vue' import gsui from 'components' // ... Vue.use(gsui)
// 修改后的
import Vue from 'vue'
// ...
if (process.env.RUN_ENV === 'component') {
// 一些頁面共用的組件
// 只能用require 不能import 因?yàn)槭庆o態(tài)處理
Vue.use(require(`components/submenu`).default);
Vue.use(require(`components/menu`).default);
Vue.use(require(`components/layout`).default);
Vue.use(require(`components/menu-item`).default);
Vue.use(require(`components/header`).default);
Vue.use(require(`components/icon`).default);
Vue.use(require(`components/tooltip`).default);
Vue.use(require(`components/modal`).default);
Vue.use(require(`components/message`).default);
Vue.use(require(`components${process.env.component}`).default);
} else {
// 不是單組件開發(fā)模式引入全部
Vue.use(require('components').default);
}
優(yōu)化后的單組件開發(fā)模式和全局開發(fā)模式的對(duì)比


但是很快就感到不實(shí)用,因?yàn)橛泻芏嘟M件是需要依賴其他組件的,有時(shí)候需要看其他組件的文檔,單組件模式就沒法做到了
只能再找別的手段了
意外發(fā)現(xiàn),原來是vue-loader的版本原因帶來的性能消耗
前天也不知道在哪發(fā)現(xiàn)了一個(gè)UI庫at-ui,下意識(shí)點(diǎn)進(jìn)去看了下他們的構(gòu)建配置,發(fā)現(xiàn)和我們的很像(其實(shí)webpack配置也都差不多的),也是用了 vue-markdown-loader ,出于好奇,clone了下來本地構(gòu)建了一下。結(jié)果出乎意料,他們的構(gòu)建只需要 16s 16s 16s 怎么會(huì)差這么多,看了下他們的文檔,還是中文和英文雙份的(我們的組件庫暫時(shí)沒有英文文檔),雖然組件沒有我們的多,但是文檔絕對(duì)是多幾十個(gè)的,而且耗時(shí)不也是在md文件的解析上嗎(再次問號(hào)臉)。再仔細(xì)看了他們的配置和對(duì)md文件的處理,確實(shí)對(duì)md文件的處理代碼會(huì)少很多,但是這是因?yàn)橹С值膶懛ú煌乙膊恢劣趯?dǎo)致時(shí)間相差那么多。
找不出原因,干脆用他們的配置來構(gòu)建我們的項(xiàng)目試試看吧。把build目錄完全copy了過來,修改了一點(diǎn)配置如 entry alias,安裝一些這邊不存在的依賴,其他基本都不需要?jiǎng)恿?,總之跑起來看看?/p>
磕磕碰碰修改幾個(gè)報(bào)錯(cuò)問題后,跑起來了,但是時(shí)間還是沒變(37s),奇了怪了。再試試另一種,用我們的配置去跑他們的項(xiàng)目看看。
把他們項(xiàng)目的src和docs目錄copy了過來,同樣把我們的配置修改一些配置 entry alias 再加點(diǎn)loader,他們需要處理yml文件,跑起來看看。結(jié)果更納悶了,時(shí)間是40s(再次問號(hào)臉)。最后在我們的項(xiàng)目中,用他們的配置去跑他們的項(xiàng)目,我這想驗(yàn)證一件事,會(huì)不會(huì)是某個(gè)依賴的版本不同引起的,結(jié)果確實(shí)是這么回事...
接下來就是找出是哪個(gè)依賴帶來的了,這里需要注意一點(diǎn)package.json中依賴的版本 如^1.0.0,以 ^ 開頭的依賴,安裝時(shí)總是會(huì)按照這個(gè)大版本下的最新版本的 也就是 ^1.0.0 ^1.1.0 都是裝 1.x 下的最新版本。而 ^1.0.0和^2.0.0 才是不一樣的。最后主要嘗試的幾個(gè)不同版本依賴主要有 webpack(2.x和3.x) vue-markdown-loader(1.x和2.x),但是這兩個(gè)換掉之后還是很慢,最后在同事的提醒下,可能是 vue-loader 因?yàn)?vue-markdown-loader 是依賴 vue-loader的,而且無論是 1.x還是2.x 都是用的 vue-loader 12.x 的版本,而我們用的是 13.x 最后功夫不負(fù)有心人,是從 vue-loader 的 v13.1.0 開始, 構(gòu)建速度會(huì)變慢。
變慢的原因
下面這個(gè)結(jié)果是公司的一位牛人發(fā)現(xiàn)的
最后發(fā)現(xiàn)是 v13.1.0 以上的 vue-loader 采用 prettier 來格式代碼,替代了原來的 js-beautify, 是這個(gè)導(dǎo)致了性能問題。
最后的配置
// config.base.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
path: utils.resolve('./postcss.config.js')
}
}
}
]
},
{
test: /\.md$/,
loader: 'vue-markdown-loader',
options: {
use: [
utils.mdAnchor,
utils.demoContainer,
utils.tipContainer
],
preprocess: utils.mdPreprocess
}
},
{
test: /\.scss$/,
use: 'happypack/loader?id=scss'
},
{
test: /\.jsx?$/,
exclude: exclude: [/node_modules/, /^dll$/],
use: 'happypack/loader?id=babel',
include: [utils.resolve('./components'), utils.resolve('./examples'), utils.resolve('./test')]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.(jpg|png|gif|eot|svg|ttf|woff|woff2)(\?.*)?(#.*)?$/,
loader: 'url-loader?name=[name].[hash].[ext]'
},
{
test: /\.vue$/,
// use: 'happypack/loader?id=vue'
loader: 'vue-loader',
options: {
loaders: {
css: 'style-loader!css-loader!sass-loader',
js: 'happypack/loader?id=babel'
}
}
}
]
},
resolve: {
extensions: ['.js', '.vue', '.json', '.scss', '.css'],
alias: {
'gs-ui': utils.resolve('./'),
components: utils.resolve('./components'),
examples: utils.resolve('./examples')
}
},
plugins: [
new HappyPack({
id: 'babel',
threads: 4,
loaders: ['babel-loader']
}),
new HappyPack({
id: 'scss',
threads: 4,
loaders: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
config: {
path: utils.resolve('./postcss.config.js')
}
}
},
'sass-loader'
]
})
]
};
// config.dev.js
module.exports = merge(config, {
entry: entry,
output: {
path: '/',
publicPath: '',
filename: '[name].js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: "'development'",
RUN_ENV: process.env.RUN_ENV === 'component' ? "'component'" : "''",
component: process.env.RUN_ENV === 'component' ? JSON.stringify('/' + component) : 'path'
}
}),
new HtmlWebpackPlugin({
template: utils.resolve('examples/index.html'),
filename: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin(),
new OpenBrowserPlugin({
url: 'http://localhost:' + PORT
}),
new webpack.DllReferencePlugin({
manifest: require('./dll/vendor.manifest.json')
})
],
devServer: {
disableHostCheck: true,
host: '0.0.0.0',
port: PORT,
quiet: true,
hot: true,
historyApiFallback: true
},
devtool: 'cheap-eval-source-map'
});
最后優(yōu)化后的構(gòu)建速度 16-17s,結(jié)果還是比較理想的,

結(jié)語
最后發(fā)現(xiàn)是依賴版本帶來的構(gòu)建性能問題,不能算是webpack構(gòu)建的優(yōu)化。算是一個(gè)踩坑吧
其他在項(xiàng)目中可以用到的優(yōu)化點(diǎn)應(yīng)該主要就是 happypack dll了,能夠有效的提升構(gòu)建速度,其他還需要多多嘗試
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
通過button將form表單的數(shù)據(jù)提交到action層的實(shí)例
下面小編就為大家?guī)硪黄ㄟ^button將form表單的數(shù)據(jù)提交到action層的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
js中int和string數(shù)據(jù)類型互相轉(zhuǎn)化實(shí)例
在本篇文章里小編給大家分享了關(guān)于js中int和string數(shù)據(jù)類型互相轉(zhuǎn)化實(shí)例和代碼,需要的朋友們學(xué)習(xí)下。2019-01-01
每天一篇javascript學(xué)習(xí)小結(jié)(RegExp對(duì)象)
這篇文章主要介紹了javascript中的RegExp對(duì)象知識(shí)點(diǎn),對(duì)RegExp對(duì)象的基本使用方法,以及各種方法進(jìn)行整理,感興趣的小伙伴們可以參考一下2015-11-11
JavaScript中的Window.open()用法示例詳解
這篇文章主要給大家介紹了關(guān)于JavaScript中Window.open()用法的相關(guān)資料,今天在項(xiàng)目中用到了彈出子窗口,就想到了用JavaScript實(shí)現(xiàn)的兩種方法,其中一個(gè)就是window.open(),需要的朋友可以參考下2023-07-07
詳解微信圖片防盜鏈“此圖片來自微信公眾平臺(tái) 未經(jīng)允許不得引用”的解決方案
這篇文章主要介紹了詳解微信圖片防盜鏈“此圖片來自微信公眾平臺(tái) 未經(jīng)允許不得引用”的解決方案,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-04-04
javascript下搜索子字符串的的實(shí)現(xiàn)代碼(腳本之家修正版)
由于我的項(xiàng)目中要求到要對(duì)一個(gè)字符串進(jìn)行查找,其查找要求有點(diǎn)BT了2009-12-12

