zoukankan      html  css  js  c++  java
  • webpack.config.js====插件html-webpack-plugin

    更多内容已经迁移至掘金,欢迎来指导学习:

    https://juejin.im/post/5d64c358518825121f661cee

     

    # html-webpack-plugin插件

    1. 动态生成html文件并自动引入js文件
    2. 静态文件无需加载js或css文件,通过设置入口文件可以将js文件自动添加进去,而相关的css文件在js中导入
    3. 同时修改生成的js文件命名规则,利用hash码命名js文件
    4. 没有改动时可以让浏览器缓存内容,当有改动重新部署后可以让浏览器缓存失效
     

    # 安装

    cnpm install html-webpack-plugin --save-dev
     

    # 插件常用的参数

    ## title

    打包生成的html文档的标题。配置该项,它并不会替换指定模板文件中的title元素的内容,除非html模板文件中使用了模板引擎语法来获取该配置项值
    <title><%= htmlWebpackPlugin.options.title %></title>

    ## template:模板路径

    • 指定你生成的文件所依赖哪一个html文件模板,模板类型可以是html、jade、ejs等。但是要注意的是,如果想使用自定义的模板文件的时候,你需要安装对应的loader
    • 为template指定的模板文件没有指定任何loader的话,默认使用ejs-loader。如template: './index.html',若没有为.html指定任何loader就使用ejs-loader

    ## 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}}"></div>')  [ ]
    • 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   当匹配时,允许忽略某些片段的正则表达式数组(例如<?php……吗?>,{ {…} },等等)。 [ /<%[sS]*?%>/, /<?[sS]*??>/ ]
    • 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:MyLocalProjectwebpackDemo
    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'
            }),
        ]
    }

    项目结构:

    # 配置自定义的模板

    参考:https://www.cnblogs.com/wonyun/p/6030090.html

     
    # 使用glob 扫描路径,自动配置html
    // __dirname目录就是E:MyLocalProjectwebpackDemo
    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: {}
    }
    View Code

    glob自动扫描路径参考:https://blog.csdn.net/qq593249106/article/details/84964816

     
     
     
     
  • 相关阅读:
    我的shell脚本
    Shell中[]里面的条件判断
    编写shell脚本需要特别关注的注意点
    Excel文本获取拼音
    netsh wlan start hostednetwork
    windows cmd 看服务cpu、内存
    cmd cvf war包
    PLSQL查询最近编绎、创建、修改过的过程函数
    根据sid或sqlID查询SQL
    JS字符串类型转日期然后进行日期比较
  • 原文地址:https://www.cnblogs.com/songxia/p/10295765.html
Copyright © 2011-2022 走看看