5. webpack多入口配置及开发模式配置

138 阅读2分钟

多入口配置

目前,index.html 和 login.html 同时引用了 bundle.js,bundle.js对应入口文件src/index.js,该文件同时引用了index.html 和 login.html 的资源依赖,这样会导致src/index.js随着项目规模扩大越来越臃肿,要解决这个问题,需要指定index.html 和 login.html 分别引用不同的文件,这就需要涉及webpack多入口配置。

  1. 修改index.js,把import './css/login.css'去掉,这个是login.html依赖的资源

  2. 创建src/login.js,并增加login.html页面的依赖

import './css/public.css'
import './css/login.css'
  1. 修改webpack.config.js,增加多入口配置
entry: {
  index: './src/index.js',
  login: './src/login.js'
},
output: {
  path: path.resolve(__dirname, './dist'),
  filename: 'js/[name].js',
}
  1. 在HtmlWebpackPlugin中添加chunks配置
new HtmlWebpackPlugin({
  filename: 'index.html',
  template: './src/index.html',
  chunks: ['index']
}),
new HtmlWebpackPlugin({
  filename: 'login.html',
  template: './src/login.html',
  chunks: ['login']
})

在chunks属性里面加入入口文件的名称,在生成html的时候会自动把对应的js文件插入到html中。

tips: 一个入口配置一个HtmlWebpackPlugin

  1. 执行npm run build命令打包后,在dist/js文件下面就会生成index.js 和 login.js,然后index.html 和 login.html 分别引入各自的打包文件。

开发模式配置

  1. 安装 webpack-dev-server
npm install webpack-dev-server -D
  1. 在webpack.config.js中添加webpack-dev-server的配置
module.exports = {
  devServer: {
      static: {
        directory: path.join(__dirname, 'dist')
      },
      // 启动压缩
      compress: true,
      port: 9000,
      // 热启动
      hot: true
   },
}
  1. 在package.json中添加启动命令
"scripts": {
  "start": "webpack-dev-server",
  "build": "webpack"
},
  1. 通过npm start启动项目,发现图片资源加载失败,原因还是图片资源的路劲不对,解决思路就是把src/img文件夹移动到dist文件夹下,我们可以通过插件来完成。

解决方案如下:

  • 安装copy-webpack-plugin
npm install copy-webpack-plugin -D
  • 在webpack.config.js中配置copy-webpack-plugin
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, './src/img'),
          to: path.resolve(__dirname, 'dist/img')
        }
      ]
    })
  ]
}

从这里,就可以体现plugin的作用,它可以定制一些功能。

  • 执行npm start就能成功启动项目,并能正常访问图片。