HtmlWebpackPlugin實現資源的自定義插入


目前碰到的問題

我們用html-webpack-plugin的inject屬性去自動插入打包后的js, css到頁面中,但是如果想給script標簽添加一個crossorigin屬性呢,

例如:

<script type="text/javascript" src="/static/js/debug.f04ad197.js"></script>

想改為:

<script crossorigin="anonymous" type="text/javascript" src="/static/js/debug.f04ad197.js"></script>

或者相對css做一個內聯,這些都無法通過html-webpack-plugin直接配置生成

 

解決問題

查看webpack的一些文檔資料,發現在issue中其實也有人提到,https://github.com/jantimon/html-webpack-plugin/issues/157

是一個內聯的問題,然而插件作者只提供了html-webpack-plugin的響應事件:

html-webpack-plugin-before-html-processing
html-webpack-plugin-after-html-processing
html-webpack-plugin-after-emit

順着找到了這個插件:

https://github.com/lcxfs1991/blog/issues/2 

插件:html-res-webpack-plugin

通過這個插件,可以實現資源的自定義插入

https://github.com/lcxfs1991/html-res-webpack-plugin/blob/v3/README_ZH.md

最終實現

let chunks = {};
chunks['vendor.js'] = { attr: "crossorigin=\"anonymous\"" // attributes for js file in index chunk } chunks['index.js'] = { attr: "crossorigin=\"anonymous\"" // attributes for js file in index chunk } chunks['index.css'] = {} result.push( new HtmlResWebpackPlugin({ filename: path + name + '.njk', template: template, chunks: chunks }) )

最終效果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM