webpack教程:如何从头开始设置 webpack 5( 二 )

创建配置的plugins属性,然后将插件,文件名添加到输出(index.html),并链接到将基于该模板的模板文件 。
const path = require('path')const HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = {  /* ... */  plugins: [    new HtmlWebpackPlugin({      title: 'webpack Boilerplate',      template: path.resolve(__dirname, './src/template.html'), // template file      filename: 'index.html', // output file    }),  ],}现在再次运行构建,会看到dist文件夹现在包含一个index.html,里面也自动引入了我们打包好的 js 文件 。用浏览器打开 index.html,会在控制台看到 Interesting! 。
接着,在index.js中我们动态插入一些 dom 元素到页面中,内容如下:
// Create heading nodeconst heading = document.createElement('h1')heading.textContent = 'Interesting!'// Append heading node to the DOMconst app = document.querySelector('#root')app.append(heading)重新构建,在进入 dist 目录下面,用 http-server 运行 html 文件 。
http-server可以在页面上看到,我们注入的 "Interesting!",还会注意到捆绑文件已缩小 。

注意:在安装HtmlWebpackPlugin后,你会看到一个DeprecationWarning,因为插件在升级到webpack 5后还没有完全摆脱deprecation警告 。
Clean我们还需要设置clean-webpack-plugin,在每次构建后清除dist文件夹中的所有内容 。这对于确保不遗留任何旧数据很重要 。
clean-webpack-plugin-删除/清理构建文件夹
const path = require('path')const HtmlWebpackPlugin = require('html-webpack-plugin')const {CleanWebpackPlugin} = require('clean-webpack-plugin')module.exports = {  /* ... */  plugins: [    /* ... */    new CleanWebpackPlugin(),  ],}Modules and Loaderswebpack 使用 loader 预处理一些加载的文件,如 js 文件、静态资源(如图像和CSS样式)和编译器(如TypeScript和Babel) 。webpack 5也有一些内置的资产加载器 。
在我们的项目中,有一个HTML文件,该文件可以加载并引入一些 JS ,但实际上并没有执行任何操作 。那么这个webpack配置要做的主要事情是什么?
  • 将 JS 编译为浏览器可以理解的版本
  • 导入样式并将 SCSS 编译为 CSS
  • 导入图像和字体
  • (可选)设置React或Vue
Babel (JavaScript)Babel是一个工具,可让使用最新的 JS 语法 。
建立一个规则来检查项目中(node_modules之外)的任何.js文件,并使用babel-loader进行转换 。Babel 还有一些其他的依赖项:
  • babel-loader-使用 Babel 和 webpack 传输文件 。
  • @babel/core-将ES2015+ 转换为向后兼容的 JavaScript
  • @babel/preset-env-Babel 的智能默认设置
  • @babel/plugin-proposal-class-properties-自定义 Babel 配置的示例(直接在类上使用属性)
npm i -D babel-loader @babel/core @babel/preset-env @babel/preset-env @babel/plugin-proposal-class-propertieswebpack.config.js
module.exports = {  /* ... */  module: {    rules: [      // JavaScript      {        test: /.js$/,        exclude: /node_modules/,        use: ['babel-loader'],      },    ],  },}
如果是 TypeScript 项目,使用的是typescript-loader而不是babel-loader 。
现在Babel已经设置好了,但是我们的Babel插件还没有 。可以在index.js中添加一些新的语法来证明它还不能正常工作 。
// 创建没有构造函数的类属性class Game {  name = 'Violin Charades'}const myGame = new Game()// 创建 p 节点const p = document.createElement('p')p.textContent = `I like ${myGame.name}.`const heading = document.createElement('h1')heading.textContent = 'Interesting!'const app = document.querySelector('#root')app.append(heading, p)


推荐阅读