1.0.7 • Published 2 years ago

inline-chunk-html-webpack-plugin v1.0.7

Weekly downloads
-
License
ISC
Repository
-
Last release
2 years ago

InlineChunkHtmlWebpackPlugin

npm.io npm.io npm.io

介绍

把外联资源转成页内形式。使用场景:对于单页html的,开发时为了开发体验好,把css,js分离到独立文件中,等上线时候,考虑减少网络请求,会把外联资源,移动到页内,并可能还会做压缩混淆。这个webpack 插件就解决这个问题。

软件架构

  • 层次上: InlineChunkHtmlWebpackPlugin > html-webpack-plugin的hooks > webpack 的钩子
  • webpack 插件机制: webpack 打包的过程,可以想象成是一条生产作业的流水线,原材料经过流水线上的每个环节,最后输出成品,这个成品就是浏览器可以直接认识的东西了。
  • webpack 的 hooks: webpack 把流水线上各个环节之间预留了很多坑位,这些个坑位(钩子)里,你可以插入自己的执行逻辑,对中间形态的半成品做定制化的加工处理!用到的机制跟浏览器的事件模型是一样的,也是发布订阅模式。 js里我们注册一个事件是 'on' 什么事件,这里是'tap' 什么自定义插件。
  • html-webpack-plugin 基于一个模板文件作为输入源头,经过html-webpack-plugin处理后输出到指定目录。

安装教程

npm i inline-chunk-html-webpack-plugin -D

使用说明

  1. 你的项目结构应该是这样的:
|--demo
	|--src
		|--index.html
		|--js/index.js
		|--style/index.css
	|--webpack.config.js
	|--package.json
  1. src/index.html 是固定的。暂时不支持配置。你只能这样写。
  2. webpack.config.js 里插件配置字段:

    	plugins:[
    	new InlineChunkHtmlWebpackPlugin(),
    	]

    注意: 我们插件是基于HtmlWebpackPlugin,不要忘记对他的配置。所以完整的配置:

    plugins:[
      new HtmlWebpackPlugin({
        template:'./src/index.html'
      }),
      new InlineChunkHtmlWebpackPlugin(),
    ]
  3. package.json里配置好脚本

"scripts": {
	"dev": "webpack"
},
  1. cmd里执行: npm run dev

之后会在当前项目目录下生成一个 webpack_dist文件夹,包含加工过的目标文件index.html

案例

index.html 源文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="./style/index.css"/>
    <script src="./js/index.js"></script>
    <script src="./js/page.js"></script>
  </head>
  <body>

    <div class="wrapper">
      <div class="bg">
        <h1>hell I am Macrolam</h1>
      </div>
 
    </div>

  </body>
</html>

输出后:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style type="text/css">
      h1 {
        color: red;
        font-size: 18px;
      }
    </style>
    <script type="text/javascript" defer="defer">
      /* 使用uglify压缩 */
      console.log("我是indexJS");
    </script>
    <script type="text/javascript" defer="defer">
      /* 使用uglify压缩 */
      console.log("我是pagejs1");
    </script>
  </head>
  <body>
    <div class="wrapper">
      <div class="bg">
        <h1>hell I am Macrolam</h1>
      </div>
    </div>
  </body>
</html>

资源地址

html-webpack-plugin文档

参与贡献

  1. Fork 本仓库
  2. 新建 Feat_xxx 分支
  3. 提交代码
  4. 新建 Pull Request