玖叶教程网

前端编程开发入门

前端架构-玩转webpack5(三「2」)(web前端开发主流框架)

接着上一节的内容,我们继续我们的webpack搭建路程。

上一节生成的目录

webpack-template
  |- build
    |- webpack.common.js
    |- webpack.dev.js
    |- webpack.prod.js
  |- public
    |- index.html
  |- src
    |- index.js
  |- package.json
  |- yarn.lock

上一节我们只是实现了js文件的打包,这一节我们需要把js引入到我们创建好的html文件里面,并且打包生成这个html文件。

1、安装html-webpack-plugin。

$ yarn add html-webpack-plugin -D

2、引入使用html-webpack-plugin。

// build/webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname, '../src/index.js'),
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: 'static/js/[name].[contenthash:8].js',
        clean: true
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '../public/index.ejs'),
            title: 'webpack 模版'
        })
    ],
}

3、修改public下面的index.html为index.ejs。

4、修改index.ejs内容如下。

// public/index.ejs
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <meta content="width=device-width,initial-scale=1,user-scalable=no" name="viewport">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-touch-fullscreen" content="yes">
  <meta name="format-detection" content="telephone=no,address=no">
  <meta name="apple-mobile-web-app-status-bar-style" content="white">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" >
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

5、配置package.json打包命令

// package.json
{
  "name": "webpack-template",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "webpack --config build/webpack.common.js"
  },
  "repository": {
    "type": "git",
    "url": "https://gitee.com/codingcoder/webpack-template.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^5.5.0",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1",
    "webpack-merge": "^5.8.0"
  }
}

6、此时我们已经将html-webpack-plugin这个插件配置好了,此时我们可以运行如下命令开始打包。

$ yarn build

这个时候在生成的dist文件夹下面就可以看到生成了一个index.html文件,它里面的内容跟index.ejs模版里面的内容基本上一致,并且还引入了/dist/static/js/下面的js文件。

打开index.html可以看到页面已经打印出了hello webpack字样。

打包生成的index.html运行内容

关注博主不迷路,下节更精彩。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言