今天我深入研究了Webpack的内部,并成功使用了它的许多有用功能(通过Webpack加载器),例如CSS
模块和Babel转译器。我希望利用这些来制作一个React应用程序(不使用create-react-app
)。
这是我的配置文件:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require('path');
module.exports = {
entry: {
main: './src/index.js',
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js'
},
module: {
rules: [
{
test: /\.js|jsx$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
exclude: /node_modules/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
})
]
};
由于现在我只有一个入口点,我的整个包被转换成一个单独的JS
文件。然而,随着我的React应用程序的增长,将捆绑包分割成多个块可能会更好,以便它们可以更快地下载(这是正确的术语吗?)。
问题:
- 将应用程序拆分为多个块时需要考虑哪些方面?
- 如何将应用程序拆分为多个块?我只需输入多个入口点(如果是这种情况,战术入口点是什么?)吗?
1. 当将应用程序拆分成多个块时,需要考虑以下几个方面: - 块之间的依赖关系 - 合理拆分代码,使得每个块都有足够的功能和性能 - 块的加载顺序 - 公共代码的提取
2. 将应用程序拆分为多个块的方法有多种,其中一种常见的方法是使用webpack进行代码拆分。可以通过以下步骤将应用程序拆分为多个块: - 使用`entry`属性定义多个入口点 - 使用`splitChunks`属性对公共代码进行提取 - 使用动态导入语法(例如`import()`)异步加载代码 - 使用webpack插件以更细粒度的方式控制代码拆分