Sha*_*hen 12 webpack webpack-html-loader html-webpack-plugin
我认为只有在某个资源被导入或需要某个资源并且资源与这样的加载器匹配时才会调用加载器.
但是在下面的代码中,没有html文件被导入到任何地方,但由于html中的下划线模板内容,仍然需要html-loader来进行编译.
所以我有以下问题:
插件是否使用加载程序的输出?但输出只是一个字符串,它怎么会有所作为?
//webpack.config.js
const webpack = require('webpack');
const path = require('path');
const htmlPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
a: './a.js'
},
output: {
filename: '[name].[chunkhash].js',
chunkFilename: '[name].[chunkhash].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.html$/,
loader: "html-loader"
}
]
},
plugins: [
new htmlPlugin({
template:path.resolve(__dirname,'index.html')
})
]
};
//index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script id="item-template" type="text/template">
<label><%= title %></label>
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)use*_*105 21
正如您所说,Webpack 仅在您“导入”文件时才知道文件,否则它不知道。
但是,Webpack 首先通过 .html 文件与您的 html 文件联系html-webpack-plugin。您可能html-webpack-plugin出于模板原因使用。我使用它纯粹是为了让 webpack 自动将生成的 JS 和 CSS 包插入到 html 中。我的包文件名包含“哈希”(例如 bundle.b88ef660a5aa8442f616.js)。我不想手工做这件事。
在这一点上,html-loader与 无关html-webpack-plugin。您可能会另外使用的原因html-loader如下所述。
如果您的模板包含图像怎么办?有些人所做的(这是错误的)是copy-webpack-plugin将图像文件夹复制到 output/dist 文件夹中,并引用 html 中相对于该文件夹的任何图像。这是错误的,因为你的图像绕过了 webpack 并失去了 webpack 的好处,比如为图像名称添加哈希、优化图像、摇树等。 如果你这样做,webpack 不知道你的图像,你必须手动照顾你的图像文件夹。
“正确”的方法是通过“要求”图像让 webpack 了解您的图像依赖性。因此<img src="./img/my-image.jpg">,您应该编写<img src="${require(./img/my-image.jpg而不是在 html 中)}" />。但是将所有图像引用更改为 require 版本很麻烦,因此当您使用 时html-loader,它会自动为您执行此操作。
这可能会立即导致错误。错误将类似于Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type.
所有这些错误意味着 webpack 不知道如何处理图像。并且告诉 webpack 如何处理它不知道的东西,你需要使用合适的加载器。在这种情况下,file-loader。
以上是我遇到的最常见的使用webpack-html-pluginand用法html-loader。
我将尽力回答您的问题:
HtmlWebpackPlugin 对 html-loader 没有依赖性。
当 webpack 在您的 javascript: 中检测到以下内容时,html-loader 就会发挥作用require('./app.component.html'),因为您有以下测试:/\.html$/。默认操作是将该文件中的 html 放在声明 require 的位置。
html-loader 独立于 HtmlWebpackPlugin。
我希望你能通过这个答案更好地理解 webpack。
| 归档时间: |
|
| 查看次数: |
4117 次 |
| 最近记录: |