将es6转换为内存中的commonjs并使用它

问题描述 投票:0回答:1

此时

  1. 我有一个用ES6编写的文件,供create-react-app应用程序使用。
  2. 我想将该文件加载到内存中,将其转换为commonJS,并在我的需要commonJS的脚本之一中使用导出的值。

我拥有的((受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)

  }
}

问题:如何在不首先将其保存到文件并要求从文件中退回的情况下获取该文件的导出值?

谢谢

javascript ecmascript-6 babel commonjs
1个回答
0
投票

我可能会尝试通过更改需求或使用捆绑器来解决此问题。

但是要在列出的约束条件内回答问题,我想我会在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
});
© www.soinside.com 2019 - 2024. All rights reserved.