玖叶教程网

前端编程开发入门

webpack5内容输出管理插件使用详解

平常我们引用打包后的文件,都是在配置文件中指定了输出的文件名,并手动在相应的html文件中通过script标签引入:

#webpack.config.js配置输出部分
output: {
    filename: "bundle.js"
}
#在页面html中引入
<script src="bundle.js"></script>

这对于单个入口文件,规定命名的输出文件,还可以适应。但是当使用hash规则对输出文件进行命名(未知文件名)或包含多个入口文件输出多个文件时,这种手动引用输出文件,就不适用了,这时就需要借助于webpack的插件来实现。

初始化示例工程

创建一个工程名称为:webpack-plugins,进行项目的初始化,并进行本地化安装webpack

mkdir webpack-plugins
cd webpack-plugins
npm init -y
npm install webpack webpack-cli --save-dev

工程结构

src/index1.js的文件内容:

console.log("index1")

src/index2.js的文件内容:

window.onload = function(){
    const index2Div = document.createElement("div")
    index2Div.innerText = "index2"
    document.body.appendChild(index2Div)
}

安装及使用HtmlWebpackPlugin插件

HtmlWebpackPlugin 会默认创建输出目录,并在输出目录中生成它自己的 index.html 文件(支持通过其template指定index.html的页面模板),这就意味着,我们不用在输出目录中创建index.html文件,同时该插件也会把输出的打包的文件自动引入index.html,而不需我们手动引入,即:不需要再关心输出文件的引用,只关注开发内容就行了。

想要了解HtmlWebpackPlugin插件的更多内容,请查看https://github.com/jantimon/html-webpack-plugin。

本地安装HtmlWebpackPlugin插件:

npm install html-webpack-plugin  --save-dev

在webpack的配置文件webpack.config.js文件中引入插件并进行相关属性的配置:

const path = require("path")
const HtmlWebpackPlugin = require("html-webpack-plugin")

module.exports = {
    entry: {
        index1: "./src/index1.js",
        index2: "./src/index2.js"
    },
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname,"dist")
    },
    // 引入插件
    plugins: [
        new HtmlWebpackPlugin({
            title: "Webpack 输出管理插件适用示例"
        })
    ]
}

执行npm run build对工程进行构建:

npm run build

> [email protected] build D:\project\mockjs\webpack-plugins
> webpack

asset index.html 304 bytes [compared for emit]
asset index2.bundle.js 114 bytes [emitted] [minimized] (name: index2)
asset index1.bundle.js 22 bytes [emitted] [minimized] (name: index1)
./src/index1.js 23 bytes [built] [code generated]
./src/index2.js 163 bytes [built] [code generated]

WARNING in configuration
The 'mode' option has not been set, webpack will fallback to 'production' for this value.
Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
You can also set it to 'none' to disable any default behavior. Learn more: https://webpack.js.org/configuration/mode/

webpack 5.28.0 compiled with 1 warning in 930 msconsole.log("index1")

可以看到工程的目录下多了个一个dist目录。目录内容如下:

输出目录内容

可以看到,自动生成了index.html,接着查看index.html的内容:

<!doctype html>
  <html>
  <head>
  <meta charset="utf-8">
    <title>Webpack 输出管理插件适用示例</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
  <script defer="defer" src="index1.bundle.js"></script>
<script defer="defer" src="index2.bundle.js"></script>
</head>
<body></body>
</html>

可以看到,对于输出内容的引用,全是自动完成的。然后用浏览器打开index.html,查看效果:

页面效果

发表评论:

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