如何向 Nodejs 动态导入添加新的文件扩展名?我想添加我自己的文件类型,我们称之为 .jszip。(不,这只是一个例子,我真正想要的与 zip 无关)。
假设我有 package.json:
{
"name": "test",
"scripts": {
"zip": "node --experimental-modules test.js"
}
}
测试.js:
const fs = require('fs');
const Module = require('module');
function loadJsZip(module, filename) {
console.log('In loadJsZip');
const content = fs.readFileSync(filename, 'utf8');
// Do something to content
module._compile(content, filename);
}
require.extensions['.jszip'] = loadJsZip;
Module._extensions['.jszip'] = loadJsZip;
function loadJs(relativePath) {
import(f).then((module) => {
console.log(`imported from ${filename}:${module}`);
}).catch((err) => {
console.log(`While importing:${err}`);
});
}
loadJs('./testfile.jszip');
我正进入(状态:
(node:20412) ExperimentalWarning: The ESM module loader is experimental.
While importing:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension: c:\...\testfile.jszip