[英]webpack split and import modules
webpack 的新手,特別是代碼拆分。
我開始使用以下內容創建vendor.js
:
...
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
...
這很容易理解,在我的 index.html 中導入main.js
和vendor.js
,效果很好,但我的vendor.js
文件仍然太大。
我在這里找到了一個教程,它建議拆分每個包:
https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758
這讓我拆分了模塊,而不僅僅是創建一個大的vendor.js
文件https://gist.github.com/davidgilbertson/838312f0a948423e4c4da30e29600b16
...
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`;
},
},
},
},
},
...
我這樣做了,而且效果很好! 我可以按預期在/dist/bundles
文件夾中看到我的所有包。
所以現在怎么辦? 在我的 index.html 中手動列出124
包似乎真的很愚蠢我理想情況下只想在需要的地方導入它們——這是否意味着更改我的所有組件(我這樣做很酷,但是如何? )
我有一個導入以下內容的組件:
import React, { Component } from 'react';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
看起來這些是相關文件:
/dist/bundles/npm.react.myApp.bundle.js
/dist/bundles/npm.material-ui.myApp.bundle.js
我可以/應該如何在我的組件中導入這些?
我添加了html-webpack-plugin
https://github.com/jantimon/html-webpack-plugin我指定了一個具有以下正文的模板:
<body>
<div id="appRoot"></div>
</body>
結果如下:
<body>
<div id="appRoot"></div>
<script ......many..... />
</body>
FWIW,我還使用以下內容更新了webpack.config
output
道具:
filename: 'main.myApp.[contenthash].bundle.js',
chunkFilename: 'bundles/[name].myApp.bundle.js'
我喜歡將contenthash
添加到main.js
以便在我推送新構建時它會破壞緩存,並且我的 S3 存儲桶中有備份/歷史記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.