webpack中的html-loader


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/10/13/webpack%E4%B8%AD%E7%9A%84html-loader/

摘要

本文主要讲述了:

  1. 作用
  2. 安装
  3. 示例

正文

作用

webpack中读取 HTML 模板。

注意:

  1. 如果 HTML 中使用了图片等文件,必须另行配置相应的 loader

安装

1
2
3
#!/usr/bin/env bash

npm install --save-dev html-loader

示例

learn_webpack/webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
},
],
},
{
test: /\.jpg$/,
use: [
{
loader: 'file-loader',
},
],
},
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'learn_webpack',
template: 'public/index.html',
}),
],
};

learn_webpack/src/index.js

1
2
3
4
const loginHtml = require('./view/foo/foo.html');

// 输出:'<img src="bebba0086588d16f519c30e8dc767877.jpg" alt="foo.jpg">'
console.log(loginHtml);

learn_webpack/src/view/foo/foo.html

1
<img src="./img/foo.jpg" alt="foo.jpg">

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/10/13/webpack%E4%B8%AD%E7%9A%84html-loader/


本文对你有帮助?请支持我


支付宝
微信