Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[webpack] 第2038天 在webpack中,怎样做多页面打包? #6004

Open
haizhilin2013 opened this issue Nov 12, 2024 · 1 comment
Open
Labels

Comments

@haizhilin2013
Copy link
Collaborator

第2038天 在webpack中,怎样做多页面打包?

3+1官网

我也要出题

@Elylicery
Copy link

在Webpack中进行多页面打包可以通过配置多个入口(entry)来实现。多页面打包的结果通常是为每个页面生成独立的HTML文件和相应的资源文件(如JavaScript和CSS),每个页面都有自己的依赖,互不干扰。

下面是一个例子

  1. 目录结构
    my-project/ ├── src/ │ ├── page1/ │ │ ├── index.js │ │ └── index.html │ ├── page2/ │ │ ├── index.js │ │ └── index.html ├── dist/ ├── webpack.config.js └── package.json

  2. 确保安装了Webpack及其所需的插件:webpack webpack-cli html-webpack-plugin

  3. webpack.config.js 配置
    `const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: {
page1: './src/page1/index.js',
page2: './src/page2/index.js',
},
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true, // 每次构建时清理 /dist 文件夹
},
plugins: [
new HtmlWebpackPlugin({
template: './src/page1/index.html',
filename: 'page1.html',
chunks: ['page1'], // 仅打包 page1 的脚本
}),
new HtmlWebpackPlugin({
template: './src/page2/index.html',
filename: 'page2.html',
chunks: ['page2'], // 仅打包 page2 的脚本
}),
],
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader', // 如果需要支持 ES6 等,可使用 Babel
},
},
{
test: /.css$/,
use: ['style-loader', 'css-loader'], // 加载 CSS 文件
},
],
},
optimization: {
splitChunks: {
chunks: 'all', // 分割代码块
},
},
mode: 'development', // 或 'production'
};
`
4. 启动打包,运行webpack,设置脚本"scripts": { "build": "webpack" } 然后 npm run build

  1. 打包结果
    通过上述配置,Webpack 将生成以下文件:
    dist/page1.html 和其对应的 JavaScript 文件 dist/page1.[contenthash].js
    dist/page2.html 和其对应的 JavaScript 文件 dist/page2.[contenthash].js
    每个 HTML 文件都将引用各自的 JavaScript 文件,并且资源之间不会相互干扰。这是多页面打包的核心目标。

总结 多页面打包的关键在于为每个页面配置独立的entry入口和相应的 HtmlWebpackPlugin 实例

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants