0

是否可以将文件注册到加载器内部捆绑?

假设我有一个自己的.cmp.html文件加载器,我需要这样的文件:

require("component/index.cmp.html");

然后我希望我的加载器也需要“component/index.cmp.js”来捆绑,因此它将被所有适用的加载器解析并出现在最终的 bundle.js 输出中

装载机可以吗?

// 到目前为止的代码,它<StaticComponent name="xyz">在 html 文件中搜索标签,然后将其替换为 xyz 的 html 内容,最后要做的是捆绑 xyz.js

组件/静态/标题/index.cmp.html

<div class="some-html-of-this-component">
</div>

组件/静态/标题/index.cmp.js

// this file has to be required to whole bundle

loaders/static-component-loader.js - 这个加载器需要 html 字符串作为输入,请从下往上阅读

const fs = require("fs");
const JSDOM = require("jsdom").JSDOM;

const readFile = function(path) {
    this.addDependency(path);

    return fs.readFileSync(path, 'utf8');    
}

const getNodeAttrs = function(node) {
    const attributes = {};

    for ( const attr of node.attributes )
        attributes[attr.nodeName] = attr.nodeValue;

    return attributes;
}

const setNodeAttrs = function(node, attributes) {
    node.setAttribute("data-cmpid", attributes.id);
    node.setAttribute("data-cmpname", attributes.name);
    node.setAttribute("class", `cmp cmpstatic cmpid-${attributes.id} ${attributes.class || ""}`.trim());

    if ( attributes.style )
        node.setAttribute("style", attributes.style);
}

const replaceNode = function(node) {
    const nodeParent = node.parentElement;

    const nodeAttributes = getNodeAttrs(node);

    const componentPath = `${__dirname}/../src/components/static/${nodeAttributes.name}`;
    const componentPathHtml = `${componentPath}/index.cmp.html`;
    const componentPathJs = `${componentPath}/index.cmp.js`;
    const componentContentHtml = readFile.call(this, componentPathHtml);

    node.innerHTML = `<div>${componentContentHtml}</div>`;

    const nNode = node.children[0];

    nodeParent.replaceChild(nNode, node);

    setNodeAttrs(nNode, nodeAttributes);

    return nNode;
}

const processNode = function(targetNode) {
    const nodes = targetNode.querySelectorAll("static-component");

    for ( const node of nodes ) {
        const newNode = replaceNode.call(this, node);

        processNode.call(this, newNode);
    }
}

module.exports = function StaticComponentLoader(content) {
    const jsdom = new JSDOM(content);

    processNode.call(this, jsdom.window.document.body);

    return jsdom.serialize();
}

不知何故,我需要将路径中的文件包含componentPathJs到整个包中,然后找到一种在运行时需要它的方法

4

1 回答 1

1

是的,有一个加载器可以做到这一点(当它解析一个文件时,它也会require附加文件)。它被称为行李装载机:https ://github.com/deepsweet/baggage-loader 。它提供了文件名占位符以在其配置中使用,例如,无论何时加载,它都会根据您的配置xyz.js插入require()forxyz.scss或等。xyz.json

如果你看一下源代码,它实际上非常简单——基本上,加载器只是require()在它正在加载的代码中添加一个并返回结果。如果您不想使用baggage-loader,您可以轻松编写自己的自定义加载器来执行类似的操作,您所需要做的就是将require('whatever')作为字符串添加到加载器接收的代码中。

(免责声明:从技术上讲,我是 的维护者baggage-loader,我认为我已经有一段时间没有研究它了)

于 2019-10-10T17:29:44.233 回答