有些场景下,希望能将引用的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.js
和a1.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.js
和a2.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.html
和dist/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文件。