n 如何编写html,webpack4系列教程,如何编写plugin处理html代码逻辑?
本博客不歡迎:各種鏡像采集行為,請尊重知識產權法律法規。大家都是程序員,不要鬧得不開心。
在上一篇文章中,利用不同位置的publicPath,對html中的cdn地址,進行了處理。但是,遺留了一個小問題,就是css和js的cdn地址,并沒有分開。
webpack4系列教程,如何編寫plugin處理html代碼邏輯?(圖4-1)
本文測試環境:win10、node@14.2.0、npm@6.14.4、webpack@4.43.0。
不大不小的誤會
為了區分css和js的publicPath,蘇南大叔想了一些辦法,但是都失敗了。output的publicPath,設置為函數。
結果就只能收到一個對象,里面包含了一個沒啥用的hash。output: {
filename: 'js/[name].[hash:8].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: function (a, b) {
console.log(a,b);
return "//cdn/" + a.hash + "/";
}
},
webpack4系列教程,如何編寫plugin處理html代碼邏輯?(圖4-2)MiniCssExtractPlugin.loader的publicPath,設置為函數。
參數確實多了,不過,這個loader里面的publicPath,不是拿來設置css文件本身的地址的。而是用于處理css文件內部,引用的資源(例如圖片和字體)的地址的。{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: (resourcePath, context) => {
return path.relative(path.dirname(resourcePath), context) + '/';
},
},
},
'css-loader',
],
},試圖修改MiniCssExtractPlugin.loader
找到了一個函數,叫做mainTemplate.getAssetPath()。不會修改。試圖修改HtmlWebpackPlugin
沒分析出它的內部邏輯,不過在官網看到了一個hook它的html結果的例子。下面的代碼是github上面的原版例子:// If your plugin is direct dependent to the html webpack plugin:
const HtmlWebpackPlugin = require('html-webpack-plugin');
// If your plugin is using html-webpack-plugin as an optional dependency
// you can use https://github.com/tallesl/node-safe-require instead:
const HtmlWebpackPlugin = require('safe-require')('html-webpack-plugin');
class MyPlugin {
apply (compiler) {
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
console.log('The compiler is starting a new compilation...')
// Static Plugin interface |compilation |HOOK NAME | register listener
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
'MyPlugin', //
(data, cb) => {
// Manipulate the content
data.html += 'The Magic Footer'
// Tell webpack to move on
cb(null, data)
}
)
})
}
}
module.exports = MyPlugin
編寫一個plugin
最終,蘇南大叔通過編寫一個基于HtmlWebpackPlugin的webpack的plugin,成功的分開了css和js的publicPath。雖然代碼寫的并不是太好。但是畢竟解決了問題。下面是一些代碼要點:獲得配置中的outputcompilation.runtimeTemplate.outputOptions獲得插件本身的optionsconstructor(options) {
// console.log('插件被使用了')
this.options = options;
}獲得htmldata.html
webpack4系列教程,如何編寫plugin處理html代碼邏輯?(圖4-3)
代碼如下:
newsn.net:這里是【評論】可見內容
把上邊這個代碼保存到plugin/test.js文件。然后調用方式就是:
webpack.config.js:let MyPlugin = require(path.resolve(__dirname, 'plugin/test.js'));
module.exports = {
//...
output: {
//...
publicPath: "//cdn/",
},
plugins: [
new MyPlugin({ publicPath: '//css.cdn/' }),
//...
],
}
webpack4系列教程,如何編寫plugin處理html代碼邏輯?(圖4-4)
相關鏈接
總結
雖然在本文中,蘇南大叔是利用了一個replace解決了區分css和js的cdn地址的需求。但是,這個插件也為蘇南大叔打開了一扇門,對html模版,如果有什么不滿意,就可以在這個地方進行修改了。很方便不是?
下面的地址,是蘇南大叔寫的webpack系列經驗文章,歡迎點擊:
如果本文對您有幫助,或者節約了您的時間,歡迎打賞瓶飲料,建立下友誼關系。
本博客不歡迎:各種鏡像采集行為。請尊重原創文章內容,轉載請保留作者鏈接。
總結
以上是生活随笔為你收集整理的n 如何编写html,webpack4系列教程,如何编写plugin处理html代码逻辑?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微型计算机原理答案第四章,微机原理第四章
- 下一篇: 计算机应用基础专业自我鉴定范文毕业生,中