webpack5 多入口

本文介绍了如何使用Webpack配置多个入口文件,如index.js和other.js,并结合html-webpack-plugin生成对应HTML文件。同时,详细讲解了如何设置输出文件的命名规则和在生产环境中使用clean-webpack-plugin清理输出目录。
摘要由CSDN通过智能技术生成

一、设置入口文件

// webpack.common.js

const srcPath = path.join(__dirname, '..', 'src');

module.exports = {
    entry: {
        index: path.join(srcPath, 'index.js'),
        other: path.join(srcPath, 'other.js')
    },
  
    // ...
}

设置入口文件为src目录下的index.js和other.js文件

二、配置对应的html文件

需要安装html-webpack-plugin插件

// webpack.common.js

const HtmlWebpackPlugin = require('html-webpack-plugin')
const srcPath = path.join(__dirname, '..', 'src');


module.exports = {
    // ...

    plugins: [

        // 多入口 - 生成 index.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'index.html'),
            filename: 'index.html',
            // chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
            chunks: ['index']  // 只引用 index.js
        }),
        // 多入口 - 生成 other.html
        new HtmlWebpackPlugin({
            template: path.join(srcPath, 'other.html'),
            filename: 'other.html',
            chunks: ['other']  // 只引用 other.js
        })
    ]
}

三、配置出口文件

// webpack.prod.js

const distPath = path.join(__dirname, '..', 'dist');

module.exports = merge(webpackCommonConf, {
    
    // ...

    output: {
        filename: '[name].[contenthash:8].js',
        path: distPath,
    },
       
    // ...
})

在打包前需要将输出目录,这里是dist目录,里面的文件清空,需要安装clean-webpack-plugin插件

// webpack.prod.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin')


module.exports = merge(webpackCommonConf, {
      
    // ....

    plugins: [
        new CleanWebpackPlugin(), // 会默认清空 output.path 文件夹
          
        // ...
    ]
})

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值