近期公司有个多页面的网站需要开发,选择用webpack构建项目。
在编写webpack config 的过程中,发现html-webpack-plugin和html-loader有冲突。
如果使用html-loader来处理html模版文件中的url,会导致html-webpack-plugin的ejs模版语法失效。
经过研究发现html-loader会把原始的html模版,编译成一个js模块样式的字符串,导致html-webpack-plugin解析的时候,发现文件已经被编译了,会直接跳过模版语法的检测。
解决方案就是在html-loader执行之前,执行一个自定义的loader来预先编译自定义的模版语法。
下面是我自己用ts开发的一个html模版解析loader, include-template-loader。
目录结构
├── src
│ ├── index.ts
│ ├── interface.ts
│ ├── schema
│ │ └── schema.ts
│ └── utils
│ ├── options.util.ts
│ └── template-parser.util.ts
├── test
│ ├── __mock__
│ │ ├── footer.html
│ │ ├── header.html
│ │ ├── index.html
│ │ ├── invalid-params.html
│ │ ├── nested.html
│ │ ├── sub-sub.html
│ │ ├── sub.html
│ │ └── without-params.html
│ ├── include-htm-loader.spec.ts
│ ├── options.util.spec.ts
│ └── template-parser.util.spec.ts
├── LICENSE
├── README.md
├── package-lock.json
├── package.json
└── tsconfig.json
开始
webpack loader 实际上就是一个默认导出的函数
// index.ts
import * as webpack from 'webpack';
import {
Options} from './interface';
import {
validateOptions, mergeOptions} from './utils/options.util';
import {
templateParser} from './utils/template-parser.util';
export default function includeHtmlLoader(
this: webpack.loader.LoaderContext,
source: string
) {
const defaultOptions: Options = {
sign: ['{
{', '}}'],
deep: 5
};
const options = mergeOptions(defaultOptions, valida