此时
我拥有的((受react-boilerplate脚本启发)
const fs = require('fs');
const {
transform
} = require('@babel/core');
const readFile = fileName =>
new Promise((resolve, reject) => {
fs.readFile(
fileName,
'utf8',
(error, value) => (error ? reject(error) : resolve(value)),
);
});
const extractFromFile = async() => {
const presets = [
[
'@babel/preset-env',
{
modules: false,
},
],
'@babel/preset-react'
];
const plugins = [
'@babel/plugin-transform-modules-commonjs'
];
const filename = './xyz.js';
try {
const code = await readFile(filename);
const output = await transform(code, {
filename,
presets,
plugins
});
// Here ... !!
// if i write output.code to file and read it from, i can access the exported values
// but if i try something like this: const foo = require(output.code) or any other
// combination that i can think off, i get undefined or errors.
console.log(output)
}
}
问题:如何在不首先将其保存到文件并要求从文件中退回的情况下获取该文件的导出值?
谢谢
我可能会尝试通过更改需求或使用捆绑器来解决此问题。
但是要在列出的约束条件内回答问题,我想我会在CommonJS模块中使用动态import
。动态导入可在ESM模块之外运行,并且受所有主要的现代浏览器支持,这在Edge v44和更早的版本(“ Legacy Edge”)中并不令人遗憾。
动态导入返回一个承诺,该承诺由ESM模块的模块名称空间对象(具有其导出属性)实现:
import("/path/to/module") .then(mod => { // Use `mod.x` here }) .catch(error => { // Handle module load error });
如果愿意,您甚至可以为模块定义CommonJS包装器:
(async () => {
module.exports = await import("/path/to/module");
})
.catch(error => {
// Handle module load error
});