繁体   English   中英

在 memory 中将 es6 转换为 commonjs 并使用它

[英]transform es6 to commonjs in memory and use it

在此刻

  1. 我有一个用 ES6 编写并由 create-react-app 应用程序使用的文件。
  2. 我想在 memory 中加载该文件,将其转换为 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) } }

问题:一个人应该如何获得该文件的导出值而不先将其保存到文件中并从其中取回?

编辑:

“...在我的一个需要为 commonJS 的脚本中使用导出的值...”

我试图实现的是有一个脚本可以从我的项目中提取 react-intl 消息。

我找到了一个由 react-boilerplate 项目人员编写的非常有用的脚本,并在我的项目中使用了它。

我尝试加载的文件是i18n.js,在他们的项目中,它是用 commonJS 编写的,带有注释

重要提示:此文件由内部构建 * 脚本extract-intl使用,并且必须使用 CommonJS 模块语法 * 您不能在此文件中使用导入/导出。

但是:我使用 create-react-app 并且据我所知(以及我测试的内容)我不能使用 modules.exports,因为它破坏了“yarn run build”脚本,我不想退出应用程序。

谢谢

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

但是在列出的约束范围内回答问题,我想我会在 CommonJS 模块中使用动态import 动态导入在 ESM 模块之外工作,所有主要的现代浏览器都支持,但 Edge v44 及更早版本(“Legacy Edge”)并不可悲。

动态导入返回一个 promise ,它通过 ESM 模块的模块命名空间 object 实现(具有导出属性):

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
});

在您对问题的更新中,您说过:

我尝试加载的文件是 i18n.js,在他们的项目中,它是用 commonJS 编写的,带有注释

重要提示:此文件由内部构建 * 脚本 extract-intl 使用,并且必须使用 CommonJS 模块语法 * 您不能在此文件中使用导入/导出。

但是:我使用 create-react-app 并且据我所知(以及我测试的内容)我不能使用 modules.exports,因为它破坏了“yarn run build”脚本,我不想退出应用程序。

没关系,您应该能够通过import语法使用它(使用捆绑器 - 在您的情况下,Webpack,这是 create-react-app 使用的); 它只是说您不能文件中使用import / export语法。

如果您将文件安装到node_modules ,您的 create-react-app 构建应该能够使用它,这要归功于 Webpack 的模块处理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM