inline-source可以内联和压缩包含inline属性的标签内容。默认情况下支持<script>,<link>和<img>(包括*.svg sources)标记,并且可以轻松扩展以处理其他标记。注意:从版本6开始,API现在基于Promise并且兼容async/await,需要Node7.6+。
用法
inlineSource(htmlpath, [options]): Promise<string>:解析htmlpath中包含inline属性标签的内容,并替换为(可选的compress压缩)文件内容。
htmlpath可以是文件路径或html内容的字符串。
可用options包括:
- attribute:用于解析源的属性(如果设置为false,则将解析所有标签元素。默认值'inline')
- compress:启用/禁用内联内容压缩(默认true)
- fs:指定fs实现(默认为Node核心'fs')
- handlers:指定自定义处理程序(默认[])[请参阅自定义处理程序 ]
- ignore:基于标签,type来忽略禁用内联,例如:['css', 'png']跳过所有CSS类型和PNG格式
- (默认[])
- pretty:当options.compress为false时保持前导空白(默认为false)
- rootpath:用于解析可内联路径的目录路径(默认process.cwd())
- saveRemote:启用/禁用保存远程源的本地副本(默认true)
- svgAsImage:转换<img inline src="*.svg" />为<img>和非<svg>(默认false)
- swallowErrors:启用/禁用错误抑制(默认false)
我们还是以gulp4构建任务实例代码为基础来实现把css代码、js代码内联插入html中去。
下载安装inline-source:
npm install inline-source --save-dev
gulpfile.js头部引入inline-source
const { inlineSource } = require('inline-source');
基于swig前端模板引擎切入
const swigParser = function(){
// 设置加载器
swig.setDefaults({
cache: false,// 禁用内存缓存
loader: swig.loaders.fs(),
});
return through.obj(async function(file, enc, next){
let locals = {};
locals.file = path.parse(file.path);
locals.makeArray = lenth=>new Array(lenth);
let content = file.contents.toString();
let html = '';
try{
html = swig.render(content, {filename: file.path, locals});
} catch(e){
this.emit('error', new $.util.PluginError('swig-parser', e.message));
}
if(process.env.production){
html = await inlineSource(html, {
compress: false,
rootpath: path.resolve(process.cwd(), 'build'),
});
}
file.contents = Buffer.from(html);
next(null, file);
});
};
buid中任务执行顺序也要调整一下,在css、js任务之后执行html任务(html任务包含了swigParser):
exports.build = series(clean,parallel(sass,image,temp,js,assets),html,series(server,watchTask));
另外Webpack4中的plugins插件概念与使用中html-webpack-plugin插件结合html-webpack-inline-source-plugin可以实现同样的功能。
延伸:假如内联css背景图片资源与html不在同一资源目录下,如何做到快速替换背景图片引用资源,这时就用到了handlers自定义处理程序
1、先声明属性
<link rel="stylesheet" inline inline-path="//test.xinran001.com/images/" href="css/index.css">
2、inlineSource的options中添加handlers选项
html = await inlineSource(html, {
compress: false,
rootpath: path.resolve(process.cwd(), 'build'),
handlers:[function customjs(source) {
if(source.extension == 'css' && source.props.path){
source.fileContent = source.fileContent.replace(/\.\.\//g,source.props.path);
}
return Promise.resolve();
}]
});
这样原内联css代码中的背景图片引用
.reg_ul li,.sub_css{background:url(../images/icon2.png) no-repeat}
批量替换为
.reg_ul li,.sub_css{background:url(//test.xinran001.com/images/icon2.png) no-repeat}