标签: module-export

CommonJS 命名导出什么时候可以被 ES 模块导入?

我有一个 ES 模块,它使用我编写的 CommonJS 模块的命名导出。

es.mjs

import { MyNamedExport } from './commonjs.cjs';

console.log(MyNamedExport);
Run Code Online (Sandbox Code Playgroud)

commonjs.cjs(不错)

exports.MyNamedExport = 'OK';
Run Code Online (Sandbox Code Playgroud)

当我像这样在 Node.js 中运行 ES 模块时,一切都很好。

> node ./es.mjs
OK
Run Code Online (Sandbox Code Playgroud)

无论如何,如果 CommonJS 模块中的导出部分以某种看似无关的方式更改,即添加一对括号,则命名导出将停止工作。

commonjs.cjs(不好的)

> node ./es.mjs
OK
Run Code Online (Sandbox Code Playgroud)
> node ./es.mjs
file:///path/to/current/folder/es.mjs:1
import { MyNamedExport } from './commonjs.cjs';
         ^^^^^^^^^^^^^
SyntaxError: Named export 'MyNamedExport' not found. The requested module './commonjs.cjs' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, …
Run Code Online (Sandbox Code Playgroud)

javascript commonjs node.js es6-modules module-export

12
推荐指数
1
解决办法
1万
查看次数

ES6 typescript 将所有导出的常量导入为数组

我正在尝试导出许多常量,稍后可以将它们导入并映射为数组。我无法将它们全部放入一个对象中并导出它们,因为我正在使用泛型(OptionInterface)并且我希望保留类型验证。

目前,我将每个对象导出为命名导出,然后将所有对象导出为数组。问题是另一个开发人员可能不知道他必须向导出的数组添加新元素。

一个例子:

//ElemSettings.tsx
export interface ElemProps<OptionInterface = any> {
  title: string,
  key: string,
  options: OptionsInterface[] 

export interface SpecialOption {
 s1: string,
 s2: number
}


//Elements.tsx - what I wish to export
export const elemOne: ElemProps {
  title: 'element One',
  key: elemOne'
  options: [1,2,3]
}

export const elemTwo: ElemProps {
  title: 'element Two',
  key: elemTwo'
  options: [1,2,3]
}

export const elemThree: ElemProps<SpecialOption> {
  title: 'element Two',
  key: elemTwo'
  options: [{s1:'one',s2:1},{s1:'two',s2:2}]
}

//This is how I export now
export const elems: …
Run Code Online (Sandbox Code Playgroud)

typescript ecmascript-6 webpack module-export

3
推荐指数
1
解决办法
5107
查看次数