关注各种黑科技
B站UP主,编程教学,游戏玩家,挂B,金牛座

使用webpack打包前端工程5 打包html

目前我们直接编辑了一个html文件在dist里,现在我们删除它,用打包的方式自动生成

npm install --save-dev html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')

  plugins: [
     new HtmlWebpackPlugin({
       title: 'Output Management'
     })
   ],

清理dist

npm install --save-dev clean-webpack-plugin
const CleanWebpackPlugin = require('clean-webpack-plugin');

 plugins: [
    new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],

自动生成的html如下

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Output Management</title>
</head>
<body>
<script type="text/javascript" src="bundle.js"></script></body>
</html>

自动生成的html,我们可以用自定义模板

在src里建一个 顺便添加 <img src="./icon.png"/> 试试html-loader
index.html

<!doctype html>
<html>
<head>
    <title>Getting Started</title>
    <style>
    </style>
</head>
<body>
<img src="./icon.png"/>
</body>
</html>

npm i -D html-loader

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
    entry: './src/index.js',
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new HtmlWebpackPlugin({
            template: 'src/index.html',
        })
    ],
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                use: [
                    'file-loader'
                ]
            },
            {
                test: /\.html$/,
                use: [ {
                    loader: 'html-loader',
                    options: {
                        minimize: true
                    }
                }],
            }
        ]
    }
};

再build后生成的html如下

 <!doctype html> <html> <head> <title>Getting Started</title> <style></style> </head> <body> <img src=f1b22c1302733468166d7ff3eeb39633.png /> <script type="text/javascript" src="bundle.js"></script></body> </html> 


filename: 'index.html', // 配置输出文件名和路径

多个html 多次new 实例化多个 html-webpack-plugin

转载请注明出处
分享到: 更多 (0)

评论 0