[英]How to optimize webpack/es6 overhead?
正如一些評論已經指出的那樣,我們必須區分構建和運行時。 來自webpack文檔的參考指南是關於構建性能的 。
雖然不使用像源映射和最小化代碼這樣的devtools會對執行速度產生影響,但我認為最重要的一個是分塊/延遲加載 (如estus已經指出的那樣)。
您應該確定初始渲染不需要應用程序的哪些部分。 這些部分應該移到另一個塊中,並通過require.ensure()
延遲加載。
通常,您的路由器是典型的異步加載內容的地方:
<Router>
<Route
path="/dashboard"
getComponent={loadPage("Dashboard")}
/>
</Router>
function loadPage(page) {
return (location, cb) => pages[page](cb);
}
const pages = {
Dashboard(cb) {
require.ensure(
["./Dashboard.js"],
require => cb(null, require("./Dashboard.js").default)
// .default is required in case you are using ES2015 modules
);
}
};
現在, Dashboard
只需要的所有模塊都將移到一個單獨的塊中。
甚至可以通過將所有頂級組件(在這里稱為“ pages
)移動到專用pages
例如pages
)中來優化冗長的require.ensure
部分。 然后,您可以將webpack配置為始終使用bundle-loader異步加載這些內容:
// webpack.config.js
...
{
test: /\.jsx$/,
include: [
path.resolve("path", "to", "pages"),
],
loaders: [
"bundle-loader?" + JSON.stringify({
lazy: true
})
]
},
然后您的路由器看起來像:
// This does not actually import the Dashboard,
// but a function which loads the dashboard.
import Dashboard from "path/to/pages/Dashboard";
function loadPage(page) {
return (location, cb) => pages[page](module => {
cb(null, module.default);
});
}
const pages = {
Dashboard
};
而且,如果您超級懶惰,並且只想引用相同的文件名而無需手動創建pages
-Object,則還可以使用require上下文 :
function loadPage(page) {
return (location, cb) =>
require("./path/to/pages/" + page + ".jsx")(
module => cb(null, module.default)
);
}
您可以做的一件事是使用devTool配置並更改生成源映射的方式。 這應該以加快調試速度為代價來加快速度。
Webpack實際上在此處提供了有關如何優化性能的出色指南, 網址為http://webpack.github.io/docs/build-performance.html 。
基本上,它歸結為您覺得需要多少調試信息。
通過設置
{
devtool: "#source-map"
}
您保留了原始代碼,這顯然是最容易調試的,但這是以文件大小/構建時間為代價的。
更新:根據克里斯下面的評論,這是另一本指南
我不相信你的時間表來源於縮小代碼(比較__webpack_require__
在馬培德文件和f
在縮小代碼)。
我將展示minify和某些插件可以減少此腳本運行時間的兩倍。 在webpack配置中,我將僅顯示與配置之間的主要區別。
webpack.config.js
devtool: 'cheap-module-eval-source-map',
cache: true,
debug: true,
時間軸-473毫秒
webpack.config.js
plugins: [
'transform-react-remove-prop-types',
'transform-react-constant-elements',
'transform-react-inline-elements'
],
cache: false,
debug: false,
plugins: [
// Search for equal or similar files and deduplicate them in the output
// https://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
new webpack.optimize.DedupePlugin(),
// Minimize all JavaScript output of chunks
// https://github.com/mishoo/UglifyJS2#compressor-options
new webpack.optimize.UglifyJsPlugin({
compress: {
screw_ie8: true,
warnings: false,
},
}),
// A plugin for a more aggressive chunk merging strategy
// https://webpack.github.io/docs/list-of- plugins.html#aggressivemergingplugin
new webpack.optimize.AggressiveMergingPlugin(),
]
時間軸-228毫秒
如果您想從此說明中深入分析webpack.config.js
,可以查看react-starter-kit中的源代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.