0

我正在尝试创建一个仅解析此语法的内容的加载器:

{{ 'assets/someimage.png'|theme }}

每个匹配项都应作为 webpack 依赖项从根 webpack 目录添加,而不会对最终内容进行任何更改(CMS 模板需要此语法)

这是我去过的地方:

let path = require('path'),
    themeRegex = /\{\{[\s?]*["|'|`](.*[\.[png|jpe?g|gif|ico])["|'|`][\s?]*\|[\s?]*theme[\s?]*\}\}/g;

module.exports = function (content, map, meta) {
    while ((themeFilterRequest = themeRegex.exec(content)) !== null) {
        var srcPath = path.join(this.rootContext, 'src')
        this.resolve(srcPath, './'+themeFilterRequest[1], (err, result) => {
            if (err) throw err
            console.log(result)
        })
    }

    return 'module.exports = [\n' +
        JSON.stringify(content) +
        '\n].join();'
};

但目前,该文件没有加载到正确的位置。它实际上是在我的 dist 文件夹中创建的,但仅在 png 扩展文件中包含文本“assets/someimage.png”...

如何二进制加载文件?

谢谢!

4

1 回答 1

1

当你需要一个 then 以外的文件时js,webpack 会为每个文件类型应用一个特殊的加载器(检查你的 webpack 配置)。

根据您的描述,已file-loader为图像导入激活。

您可以使用 webpack 内联加载器语法,并指定应该处理您的需求的确切加载器。 !!file-loader!path/to/file.png(开头的 !! 告诉 webpack 只运行指定的加载器)。

const fs = require('fs');
const path = require('path');

module.exports = function (content, map, meta) {
    // parse your content to get a list of paths to files
    filePaths.forEach(fileToLoad => {
       const file = fs.readFileSync(fileToLoad);
       const fileName = path.basename(fileToLoad);
       this.emitFile(fileName, file)
    });

    return content;
};

于 2020-01-13T20:23:55.803 回答