我正在使用webpack-dev-server进行开发,并使用html-webpack-plugin生成包含修订资源的index.html。问题是每次我更改index.html时,捆绑系统都不会再次重建。我知道index不在入口中,但有没有解决这个问题的方法?
问题在于Webpack没有监视index.html文件。它只会监视那些在你的代码中“需要”或“导入”到其他文件中并被加载器测试的文件。
解决方案包括两个部分。
首先,在入口点(entry point)中要求(require) 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"
}
原始加载器将把任何“required”文件转换为文本字符串,然后Webpack将观察它并在每次更改时刷新dev-server。
在加载阶段,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指令模板,但是我不必将它们添加到我的入口点开头。我只需在指令模板属性内部执行require,就像这样:
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!'
}
}
})
}
DefinePlugin
webpack жҸ’件жүҚиғҪеңЁеүҚз«Ҝ JavaScript д»Јз ҒдёӯдҪҝз”ЁзҺҜеўғеҸҳйҮҸгҖӮзұ»дјјиҝҷж ·пјҡnew webpack.DefinePlugin({ NODE_ENV: JSON.stringify(process.env.NODE_ENV) })
然еҗҺеңЁдҪ зҡ„ app.js
дёӯпјҡif (NODE_ENV === 'development') { ... }
дҪҶд№ҹи®ё @GabrielKunkel еҸҜд»Ҙжӣҙе…·дҪ“ең°иҜҙжҳҺ他们еҰӮдҪ•еңЁеүҚз«Ҝд»Јз ҒдёӯдҪҝз”Ё process.env.VARIABLE
... - adam-beck只需在你的devServer
配置中添加watchContentBase: true
即可。webpack-dev-server将监视位于contentBase
目录中的所有文件的更改。这里我们监视./src目录中的所有文件。
webpack.config.js:
...
devServer: {
port: 8080,
contentBase: './src',
watchContentBase: true
}
contentBase
更改为'./templates'
。这是一个简单的解决方案,一直在文档中,但没有注意到使用情况。感谢您提供的答案! - Chase Giuntawebpack > 5.x
开始,不再支持contentBase
和 watchContentBase
选项。devServer: {
watchFiles:['src/**/*'] // to detect changes on all files inside src directory
}
使用 webpack > 5.0
版本,需使用 watchFiles
选项
devServer: {
open: true,
watchFiles: ['src/**/*'],
},
npx webpack --watch
构建它,你可以将缓存设置为false,每次生成文件。new HtmlWebpackPlugin({
cache: false,
})
要进一步定制,请阅读此链接:htmlwebpackplugin。
import 'file-loader!../templates/index.html';
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'],
}
})
]