webpack打包多页应用

2022-09-08 16:42:55 浏览数 (1)

目录结构

代码语言:javascript复制
│  package.json
│  webpack.config.js
│
└─src
        index.html
        index.js
        other.html
        other.js

项目有两个入口文件,对应两个html

我们在webpack.config.js进行如下配置

代码语言:javascript复制
let path = require('path')
let HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports={
    //多入口}
    mode:'development',
    entry:{
        home:'./src/index.js',
        other:'./src/other.js'
    },
    output:{
        //[name]=home/other
        filename:'[name].js',
        path:path.resolve(__dirname,'dist')

    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'./src/index.html',
            filename:'home.html',
            chunks:['home']//代码块,指定js文件
        }),
        new HtmlWebpackPlugin({
            template:'./src/other.html',
            filename:'other.html',
            chunks:['other']//代码块
        })
    ]
}

打包后的文件 dist

代码语言:javascript复制
//home.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>index</title>
</head>
<body>
    
<script src="home.js"></script></body>
</html>

//other.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<script src="other.js"></script></body>
</html>

0 人点赞