webpack 之 配置多入口

文件结构:

src:  index.html  other.html index.js  other.js 

配置文件:

文件内容:

 index.html 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p>index page</p>
</body>
</html>

 index.js 

console.log('index')

 other.html 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p>other page</p>
</body>
</html>

 other.js 

console.log('other')

 path.js 

/**
 * @description 常用文件夹路径
 * @author 山间
 */

const path = require('path')
const srcPath = path.join(__dirname, '..', 'src')
const distPath = path.join(__dirname, '..', 'dist')

module.exports = {
  srcPath,
  distPath
}

接下来看如何配置:

第一步:修改  webpack.common.js  的入口配置

entry 这块的单一入口就需要从 path.join(srcPath, 'index')  修改为多入口

const path = require('path')
const { srcPath, distPath } = require('./paths')

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

第二步:修改出口配置,即 output 的配置,那是在  webpack.prod.js 

const path = require('path')
const { srcPath, distPath } = require('./paths')

module.exports = {
  // ...
  output: {
    filename: '[name].[contenthash:8].js', // name 即多入口时 entry 的 key,在这里就是 index 和 other
    path: distPath
  }
  // ...
}

第三步:因为有两个页面,所以需要在  webpack.common.js  中配置多入口的   HtmlWebpackPlugin 

// ...
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  // ...
  plugins: [
    // 多入口 - 生成 index.html
    new HtmlWebpackPlugin({
      template: path.join(srcPath, 'index.html'),
      filename: 'index.html',
      // chunks 表示该页面引用哪些 chunk (即上面的 index 和 other)
      // 如果不写 chunks , 会把入口的两个 chunk - index 和 other 都引入
      chunks: ['index'] // 只引用 index.js
    }),

    // 多入口 - 生成 other.html
    new HtmlWebpackPlugin({
      template: path.join(srcPath, 'other.html'),
      filename: 'other.html',
      chunks: ['other']
    })
  ]
}

好了,一共就这三步配置,就可以实现 Webpack 的多入口啦。总结一下,首先是配置 entry ,然后是 output ,最后配置多页面。

配置好以后可以尝试 run 和 build 一下,可以看到在页面中,index.html 只会引入 index.js,other.html也是只会引入 other.js;在打包的dist文件夹中,会打包出index.html、index[contenthash:8].js、other.html、other[contenthash:8].js 四个文件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值