webpack之插件html webpack plugin

html-webpack-plugin插件

  1. 動態生成html文件並自動引入js文件javascript

  2. 靜態文件無需加載js或css文件,經過設置入口文件能夠將js文件自動添加進去,而相關的css文件在js中導入css

  3. 同時修改生成的js文件命名規則,利用hash碼命名js文件html

  4. 沒有改動時可讓瀏覽器緩存內容,當有改動從新部署後可讓瀏覽器緩存失效html5

安裝

cnpm install html-webpack-plugin --save-dev
複製代碼

經常使用的參數

title

打包生成的html文檔的標題java

配置該項,它並不會替換指定模板文件中的title元素的內容,除非html模板文件中使用了模板引擎語法來獲取該配置項值 <%= htmlWebpackPlugin.options.title %>node

template:模板路徑

指定你生成的文件所依賴哪個html文件模板,模板類型能夠是html、jade、ejs等webpack

可是要注意的是,若是想使用自定義的模板文件的時候,你須要安裝對應的loaderes6

爲template指定的模板文件沒有指定任何loader的話,默認使用ejs-loader。如template: './index.html',若沒有爲.html指定任何loader就使用ejs-loaderweb

filename:通常是相對路徑

輸出文件的文件名稱,默認爲index.html,還能夠爲輸出文件指定目錄位置(例如'html/index.html')正則表達式

filename配置的html文件目錄是相對於webpackConfig.output.path路徑而言的,不是相對於當前項目目錄結構的

指定生成的html文件內容中的link和script路徑是相對於生成目錄下的,寫路徑的時候通常是生成目錄下的相對路徑

templateContent: string|function

能夠指定模板的內容,不能與template共存。配置值爲function時,能夠直接返回html字符串,也能夠異步調用返回html字符串

minify: {....}|false

傳遞 html-minifier 選項給 minify 輸出,false就是不使用html壓縮

minify: {
	collapseWhitespace: true, //打包後是否刪除空格(壓縮)
	removeAttributeQuotes: true // 移除屬性的引號
},
複製代碼
  • caseSensitive(默認false):以區分大小寫的方式處理屬性(適用於定製的HTML標記)

  • collapseBooleanAttributes(默認false):從布爾屬性中省略屬性值

  • collapseInlineTagWhitespace Don't leave any spaces between display:inline;elements when collapsing. Must be used in conjunction with collapseWhitespace=true false

  • collapseWhitespace 在顯示之間不要留下任何空格:內聯;崩潰時的元素。必須與摺疊空間結合使用=true ? false

  • conservativeCollapse 老是摺疊到1個空間(永遠不要徹底刪除它)。必須與摺疊空間結合使用=true ? false

  • customAttrAssign 容許支持自定義屬性分配表達式的正則表達式數組。 (e.g. '<div flex?="{{mode != cover}}">') [ ]

  • customAttrCollapse Regex指定自定義屬性以從(例如/ng-class/)刪除新行。

  • customAttrSurround 容許支持自定義屬性包圍表達式的正則表達式數組(e.g. <input {{#if value}}checked="checked"{{/if}}>) [ ]

  • customEventAttributes 容許爲minifyJS支持自定義事件屬性的正則表達式數組(例如,ng-click) [ /^on[a-z]{3,}$/ ]

  • decodeEntities 儘量使用直接的Unicode字符。false

  • html5 根據HTML5規範分析輸入。 true

  • ignoreCustomComments 當匹配時,容許忽略某些註釋的正則表達式數組。 [ /^!/ ]

  • ignoreCustomFragments 當匹配時,容許忽略某些片斷的正則表達式數組(例如,{ {…} },等等)。 [ /<%[\s\S]?%>/, /<?[\s\S]??>/ ]

  • includeAutoGeneratedTags 插入由HTML解析器生成的標記。 true

  • keepClosingSlash 保留單例元素的末尾斜槓。 false

  • maxLineLength 指定最大行長度。壓縮的輸出將在有效的HTML分割點上被換行。

  • minifyCSS 縮小CSS樣式元素和樣式屬性(usesclean-css) false (could betrue, Object,Function(text))

  • minifyJS 在腳本元素和事件屬性中縮小JavaScript(使用UglifyJS) false (could betrue, Object,Function(text, inline))

  • minifyURLs 在各類屬性中縮小url(使用relateurl) false (could beString, Object,Function(text))

  • preserveLineBreaks 當標記之間的空格包括換行符時,老是崩潰到1行中斷(永遠不要徹底刪除)。必須與摺疊空間結合使用=true ? false

  • preventAttributesEscaping 防止屬性值的溢出。 false

  • processConditionalComments 經過minifier處理條件評論的內容。 false

  • processScripts 經過minifier(例如text/ng-template、text/x-handlebars-template等)來處理腳本元素類型的字符串數組。 [ ]

  • quoteCharacter 用於屬性值的引用類型('or')

  • removeAttributeQuotes 在可能的狀況下刪除引號。 false

  • removeComments 帶HTML註釋 false

  • removeEmptyAttributes 刪除全部的屬性,只有whitespace-only的值。 false (could betrue,Function(attrName, tag))

  • removeEmptyElements 刪除全部含有空內容的元素。 false

  • removeOptionalTags 刪除可選的標記 false

  • removeRedundantAttributes 當值匹配默認值時刪除屬性。 false

  • removeScriptTypeAttributes 從腳本標籤中刪除type="text/javascript"。其餘類型的屬性值是完整的。false

  • removeStyleLinkTypeAttributes 從style和link標籤中刪除type="text/css"。其餘類型的屬性值是完整的。 false

  • removeTagWhitespace 儘量在屬性之間移除空間。注意,這將致使無效的HTML! false

  • sortAttributes 根據頻率屬性進行排序 false

  • sortClassName 按頻率分類樣式類。 false

  • trimCustomFragments 在ignoreCustomFragments周圍調整空白區域。 false

  • useShortDoctype 用short (HTML5) doctype替換doctype。 false

chunks

容許插入到模板中的一些chunk,不配置此項默認會將entry中全部的thunk注入到模板中

在配置多個頁面時,每一個頁面注入的thunk應該是不相同的,須要經過該配置爲不一樣頁面注入不一樣的thunk

chunks主要是選擇使用你頁面中呀加入的js

plugins: [
    new httpWebpackPlugin({
    chunks: ['index','main']
    })
]
複製代碼

那麼編譯後:

<script type=text/javascript src="index.js"></script>
<script type=text/javascript src="main.js"></script>
複製代碼

excludeChunks:排除掉一些js,用來配置不容許注入的thunk

chunksSortMode: none | auto| function,默認auto

容許指定的thunk在插入到html文檔前進行排序。

function值能夠指定具體排序規則

auto基於thunk的id進行排序

none就是不排序

inject有四個值: true body head false

向template或者templateContent中注入全部靜態資源,不一樣的配置值注入的位置不經相同

true 默認值或body,全部JavaScript資源插入到body元素的底部

head script標籤位於html文件的 head中

false 不插入生成的js文件,這個幾乎不會用到的

favicon

添加特定favicon路徑到輸出的html文檔中,這個同title配置項,須要在模板中動態獲取其路徑值

結果是將生成的html文件生成一個 favicon ,值是一個路徑 :favicon: 'path/to/my_favicon.ico',而後再生成的html中就有了一個 link 標籤

<link rel="shortcut icon" href="example.ico">
複製代碼

cache:true|fasle, 默認true

表示內容變化的時候生成一個新的文件

若是爲true表示在對應的thunk文件修改後就會emit文件

hash:布爾值,默認false

是否爲全部注入的靜態資源添加webpack每次編譯產生的惟一hash值,添加hash形式以下所示:

html <script type="text/javascript" src="common.js?a3e1396b501cdd9041be"></script>
複製代碼

xhtml: true|fasle, 默認false

是否渲染link爲自閉合的標籤,true則爲自閉合標籤

showErrors: true|false,默認true

是否將錯誤信息輸出到html頁面中

配置多個html頁面例子

應用中配置了三個入口頁面:index.html、course.html、about.html;而且每一個頁面注入的thunk不盡相同;

相似若是多頁面應用,就須要爲每一個頁面配置一個;

// 須要暴露在全局(模塊的導出)
// __dirname目錄就是E:\MyLocalProject\webpackDemo
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: {
    general: './src/skin/general/js/general.js',
    index: './src/skin/index/js/index.js',
    course: './src/skin/course/js/index.js',
    about: './src/skin/about/js/index.js',
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'skin/[name]/[name].js',  //必須是相對路徑
    publicPath: '../../'
},
module: {
    rules: [
        //配置babel,自動編譯es6語法
        {
            test: /\.js$/,
            exclude: /(node_modules)/,
            loader: 'babel-loader'
        },

    ]
},
//插件的相關配置
plugins: [
    //配置html文件
    new htmlWebpackPlugin({
        template: path.join(__dirname, '/src/static/index.html'),
        filename: 'static/index.html',
        minify: {
            collapseWhitespace: true
        },
        hash: true,
        favicon: 'favicon.ico',
        chunks: ['general', 'index']
    }),
    new htmlWebpackPlugin({
        template: path.join(__dirname, '/src/static/course/index.html'),
        filename: 'static/course/index.html',
        minify: {
            collapseWhitespace: true,
        },
        hash: true,
        favicon: 'favicon.ico',
        chunks: ['general', 'course']
    }),
    new htmlWebpackPlugin({
        template: path.join(__dirname, '/src/static/about/index.html'),
        filename: 'static/about/index.html',
        minify: {
            collapseWhitespace: true
        },
        hash: true,
        chunks: ['general', 'about'],
        favicon: 'favicon.ico'
    }),
]
}
複製代碼

項目目錄結構

使用glob 掃描路徑,自動配置html

// __dirname目錄就是E:\MyLocalProject\webpackDemo
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin')

//掃描入口目錄static的路徑
const glob = require("glob");
const staticHtmlPath = glob.sync('src/static/**/*.html');

//定義入口對象entrys
const entrys = {};
//設置公共的js入口文件
const commonJSObj = {
  general: './src/skin/general/js/general.js',
}
Object.assign(entrys, commonJSObj)

//定義html-webpack-plugin配置項
const htmlCfgs = [];
const htmlCfgsObj = {};
staticHtmlPath.forEach((filePath) => {
  let path = filePath.split('/')
  let pathLength = path.length
  //獲取文件名
  let filename = path[pathLength - 1].split('.')[0]

  //動態配置入口文件路徑
  let entryJSName = path[pathLength - 2] + '-' + filename
  entrys[entryJSName] = './src/skin/' + path[pathLength - 2] + '/js/' + filename + '.js';
  htmlCfgs.push( //動態配置入口文件插件
    new htmlWebpackPlugin({
      template: filePath,
      filename: filePath.replace('src', ''),
      minify: {
        collapseWhitespace: true
      },
      hash: true,
      favicon: 'favicon.ico',
      chunks: [entryJSName, 'general'],
    })
  )
});

module.exports = {
  devtool: 'inline-source-map',
  // 入口
  entry: entrys,
  // 出口
  output: {
    path: path.resolve(__dirname, 'dist'), //必須是絕對路徑
    filename: 'skin/[name]/[name].js',  //必須是相對路徑
    publicPath: '../../'
  },
  // 開發服務器
  devServer: {},
  // 模塊配置
  module: {
    rules: [
      //配置babel,自動編譯es6語法
      {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader'
      },
    ]
  },
  //插件配置
  plugins: htmlCfgs,
  //配置解析
  resolve: {}
}
複製代碼

參考文章: www.cnblogs.com/wonyun/p/60…

相關文章
相關標籤/搜索