猫码程序员让前端飞

8、webpack从0到1-基本的plugins

2020-03-16  本文已影响0人  ComfyUI

谈谈plugins,然后使用两个基本的plugins,一个是clean-webpack-plugin,一个是HtmlWebpackPlugin。
git仓库:webpack-demo

1、plugins初识

2、过程回顾

3、CleanWebpackPlugin

$ npm install clean-webpack-plugin --save-dev
+  const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const path = require("path");

module.exports = {
    mode: "development",
    devtool: "inline-source-map",
    entry: {
       main: "./src/index.js"
    },
    output: {
       filename: "[name].bundle.js",
       path: path.resolve(__dirname, "dist")
    },
+   plugins: [
+      new CleanWebpackPlugin()
+   ],
    ...
}

4、HtmlWebpackPlugin

$ npm install html-webpack-plugin --save-dev
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
+  const HtmlWebpackPlugin = require("html-webpack-plugin");

const path = require("path");

module.exports = {
    mode: "development",
    devtool: "inline-source-map",
    entry: {
       main: "./src/index.js"
    },
    output: {
       filename: "[name].bundle.js",
       path: path.resolve(__dirname, "dist")
    },
    plugins: [
       new CleanWebpackPlugin(),
+      // 可以为你生成一个HTML文件
+      new HtmlWebpackPlugin()
    ],
    ...
}

5、小进阶

const { CleanWebpackPlugin } = require("clean-webpack-plugin");
+  const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    ...
    plugins: [
       new CleanWebpackPlugin(),
       // 可以为你生成一个HTML文件
       new HtmlWebpackPlugin({
+        title: "webpack从0到1",
+        template: "./index.html"
       })
    ],
    ...
}
<!DOCTYPE html>
<html lang="en">

<head>
     <meta charset="UTF-8">
-    <title>webpack从0到1</title>
+    <title><%= htmlWebpackPlugin.options.title %></title>
</head>

<body>
-    <script src="./src/index.js"></script>
</body>

</html>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>webpack从0到1</title>
</head>

<body>
<script type="text/javascript" src="main.bundle.js"></script>
</body>

</html>

小结

参考链接:
webpack-html-webpack-plugin
html-webpack-plugin
output-management

上一篇下一篇

猜你喜欢

热点阅读