JIGZEG.INFO

使用Webpack内联CSS JS

发布



有些场景下,希望能将引用的CSS文件内联至style标签中,将JS文件内联至script标签中,这样就可以减少网络请求数量,提升页面加载速度。尤其是在页面引用到了众多小型的资源文件时,嵌入到一个html文件中,页面首次加载速度会有明显提高。

我们可以配置Webpack,借助插件:html-bundler-webpack-plugin,将这些小型文件都内联化,配置打包到一个html文件中就可以了。下面是一个简单用例:

假如项目目录如下:

.
├── package.json
└── src
    ├── a.html
    ├── b.html
    ├── scripts
    │   ├── a1.js
    │   └── a2.js
    └── styles
        ├── a1.css
        └── a2.css

其中,a.html引用了a1.jsa1.css

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page a</title>
    <link rel="stylesheet" href="styles/a1.css">
</head>
<body>
    <script src="scripts/a1.js"></script>
</body>
</html>

b.html引用了a2.jsa2.css

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page a</title>
    <link rel="stylesheet" href="styles/a2.css">
</head>
<body>
    <script src="scripts/a2.js"></script>
</body>
</html>

我们希望将两个html文件各自所引用到的文件,分别打包到各自所在的html文件中,最终得到dist/a.htmldist/b.html两个文件,那么,可以按如下步骤来进行配置操作:

首先安装Webpack、html-bundler-webpack-plugin以及css-loader等依赖:

npm install html-bundler-webpack-plugin css-minimizer-webpack-plugin css-loader webpack webpack-cli -D

然后创建webpack.config.js配置文件:

// webpack.config.js
import path from 'path';
import HtmlBundlerPlugin from 'html-bundler-webpack-plugin';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url); // 获取当前文件路径
const __dirname = path.dirname(__filename);

export default {
  mode: 'production',

  output: {
    path: path.join(__dirname, 'dist/'),
  },

  plugins: [
    new HtmlBundlerPlugin({
      entry: {
        'a': './src/a.html',
        'b': './src/b.html',
      },
      css: {
        inline: true,
      },
      js: {
        inline: true,
      },
      minify: true,
    }),
    new CssMinimizerPlugin(), // 压缩CSS
  ],

  module: {
    rules: [
      {
        test: /\.css$/,
        use: ['css-loader'],
      },
    ],
  },

  performance: false,
};

然后编辑package.json,加入一个打包指令:

{
  "name": "_proj",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack build --mode=production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "css-loader": "^7.1.2",
    "css-minimizer-webpack-plugin": "^7.0.0",
    "html-bundler-webpack-plugin": "^4.4.1",
    "webpack": "^5.96.1",
    "webpack-cli": "^5.1.4"
  },
  "type": "module"
}

终端运行:

npm run build

会在dist目录下生成两个内嵌了所引用的CSS/JS文件内容的HTML文件。


此文被收纳在#Webpack#类目下,被贴上了#Webpack#标签