cgreact-loader
Version:
CGReact与Webpack配套的loader
113 lines (110 loc) • 2.89 kB
JavaScript
/** 从style-loader获得的module content是这样的:
exported.use = .....
exported.unuse = .....
module.exports = exported;
cgreact-loader会把 module.exports替换为const cg_exports
根据ESModule的语法规范,最终加载的模块以module.exports=为准
因此我们偷梁换柱,把下面的代码片段拼接到style-loader加载的module content之后
这样最终导出的就是我们想要的模块类型
*/
let result = {};
result.print = () =>
{
console.log(exported);
}
// 启用CssModule,克隆所有local
for (let key in exported.locals)
{
// 对于-链接的要特殊处理
let sp = key.split("-");
if (sp.length > 1)
{
let rkey = sp[0];
for (let i = 1; i < sp.length; i++)
{
rkey += sp[i].substring(0, 1).toUpperCase() + sp[i].substring(1);
}
result[rkey] = exported.locals[key];
}
result[key] = exported.locals[key];
}
// 添加affect,invalid,bind函数
result.affect = (context) =>
{
exported.use();
if (context)
{
result.bind(context);
}
return result;
};
result.invalid = () =>
{
exported.unuse()
return result;
};
// 重载上下文的钩子函数,做离开页面自动移除的效果
result.bind = (context) =>
{
if (context && context.CssAndJSList && typeof context.CssAndJSList.push == "function")
{
context.CssAndJSList.push(result);
}
return result;
};
module.exports = result;
/** css-loader返回的记过是这样的:
exports.push([
module.id,
"h2 { .....]);
exports.locals = {
"cg": "cg" };
module.exports=exports;
cgreact-loader会替换最后的module.exports为const cg_exports
构建的目标tag标签是:<link rel="stylesheet" href="xxx.css" />
*/
let result = {
tag: "XXXfile_nameXXX", // tag默认是文件名
path: "XXXpublic_pathXXX", // 这个路径会由cgreact-laoder替换为public_path
dom: document.createElement("link")
};
// 注入affect,invalid和bind方法
result.affect = (context) =>
{
// 构造表情细节
result.dom.setAttribute("data-css", "");
result.dom.setAttribute("data-meta", result.tag);
result.dom.setAttribute("rel", "stylesheet");
result.dom.setAttribute("href", result.path);
// 添加到body节点
if (document.getElementById("user"))
{
document.getElementById("user").appendChild(result.dom);
} else
{
window.setTimeout(() =>
{
document.getElementById("user").appendChild(result.dom);
}, 100);
}
if (context)
{
result.bind(context);
}
return result;
};
result.invalid = () =>
{
result.dom.remove();
return result;
};
// 重载上下文的钩子函数,做离开页面自动移除的效果
result.bind = (context) =>
{
if (context && context.CssAndJSList && typeof context.CssAndJSList.push == "function")
{
context.CssAndJSList.push(result);
}
return result;
};
module.exports = result;