我正在使用 webpack-dev-server 进行开发,使用 html-webpack-plugin 生成带有修订源的 index.html。问题是每次我更改 index.html 时,捆绑系统都不会再次重建。我知道索引不在条目中,但是有没有办法解决这个问题?
6 回答
问题是 Webpack 没有监视 index.html。它只监视代码中某处“需要”或“导入”的文件,并且加载程序正在测试。
解决方案有两个部分。
首先需要入口点中的 index.html 文件。从技术上讲,您可以在应用程序的任何地方使用它,但这非常方便。如果您在 html-webpack-plugin 中使用模板,我相信您也可以只需要您的模板。
我在我的 index.js 文件中需要我的 index.html,这是我的入口点:
require('./index.html')
const angular = require('angular')
const app = angular.module('app', [])
//...so on and so forth
最后,安装raw-loader并将所有其他加载器添加到您的 Webpack 配置文件中。因此:
{
test: /\.html$/,
loader: "raw-loader"
}
原始加载器会将几乎任何“需要”的文件转换为文本字符串,然后,Webpack 会为您监视它并在您每次进行更改时刷新开发服务器。
Webpack 本身和您的程序都不会在加载 index.html 文件(或模板)的阶段对其进行任何实际操作。对于您的生产或测试环境来说,这是完全没有必要的,所以为了更好的衡量,我只在运行开发服务器时添加它:
/* eslint no-undef: 0 */
if (process.env.NODE_ENV === 'development') {
require('./index.html')
}
const angular = require('angular')
const app = angular.module('app', [])
//...so on and so forth
从理论上讲,您可以“要求”一堆您希望它观看的其他静态 html 文件。...或文本文件。我自己将 raw-loader 用于 Angular 指令模板,但我不必将它们添加到我的入口点的开头。我可以只在指令模板属性中要求,如下所示:
module.exports = function(app) {
app.directive('myDirective', function(aListItem) {
return {
template: require('./myTemplate.html'),
restrict: 'E',
controller: function($scope) {
$scope.someThingThatGoesInMyTemplate = 'I love raw-loader!'
}
}
})
}
只需添加watchContentBase: true
到您devServer
的配置中。contentBase
webpack-dev-server 将监视dir中所有文件的更改。在这里,我们查看 ./src 中的所有文件
webpack.config.js:
...
devServer: {
port: 8080,
contentBase: './src',
watchContentBase: true
}
如果您使用 just 构建它npx webpack --watch
,则可以将 cache 设置为 false 以每次生成文件。
new HtmlWebpackPlugin({
cache: false,
})
阅读此链接以进行进一步的定制,htmlwebpackplugin。
使用webpack > 5.0
, 使用watchFiles
选项
devServer: {
open: true,
watchFiles: ['src/**/*'],
},
从webpack > 5.0
,没有contentBase
和watchContentBase
选项
相反,您可以这样做:
devServer: {
watchFiles:['src/**/*'] // to detect changes on all files inside src directory
}
另一种解决方案是使用file-loader在入口javascript文件处导入html文件。
import 'file-loader!../templates/index.html';
您可以像往常一样进行 html-webpack-plugin配置
plugins: [
new HtmlWebPackPlugin({
template: path.resolve(__dirname, 'src/templates/index.html'),
filename: path.resolve(__dirname, 'dist/index.html'),
files: {
css: ['style.css'],
js: ['main.js'],
}
})
]
当webpack-dev-server运行时,这不会向光盘写入任何内容