【问题标题】:difference between export default { name } and named export { name }导出默认{名称}和命名导出{名称}之间的区别
【发布时间】:2019-04-09 14:33:56
【问题描述】:

我正在尝试弃用具有许多命名导出的模块,如下所示:

const Foo = () => 'foo';
const Bar = () => 'bar';

export { Foo };
export { Bar };

通过以下方式消费时很好:

import { Foo, Bar } from './something';

我关于启用弃用警告的想法是使用类型对象的默认导出,并为打印弃用然后返回模块的每个键使用属性 getter 覆盖。

然后形状变成这样:

const something = {};
Object.defineProperty(something, 'Foo', {
  get(){
    console.warn('Foo is deprecated soon');
    return Foo;
  }
});
// etc
export default something;

我的想法是解构导入会解决这个问题

import { Foo, Bar } from './something';

... 将继续像以前一样工作。相反,webpack 抱怨某些东西没有命名的导出 Foo 或 Bar

但是,使用它可以:

const { Foo, Bar } = require('./something');

我也可以拥有import something from './something'; const { Foo, Bar } = something,这很有效,但如果我必须重构每个存在的导入,它就达不到目的。

所以问题 真的 是关于 import { Foo, Bar } from './something';require() 相比如何工作 - 我曾认为如果默认导出是一个对象,它会弄清楚并解构,但没有快乐。

是否有一种简单的方法可以在不改变出口在其他地方的消费方式的情况下进行这种“代理”?

【问题讨论】:

  • 是否可以选择将Foo 的实现包装在函数调用中?
  • 不幸的是,没有。 Foo 是转换为 UMD 的 x30 旧“供应商”代码。它实际上是 'export { Foo } from 'Foo';'
  • 当您说 without changing how the exports are being consumed elsewhere 时,这是一个要求,还是它们只是在很多地方都被消费了,而您不想全部看完?
  • 正确,它们在多个应用程序中使用 - 这是一个遗留组件库的儿子,逐渐移植到'as and when' - 所以查看潜在的 100 多个导入。遗留库现在引用一个重新导出它的本地文件,我希望装饰组件,以便开发人员收到警告和console.trace(),以帮助识别需要更改的应用程序部分。
  • @Bergi 这个问题是关于 Javascript ES6 模块的。这是关于打字稿模块的。它们不是一回事。

标签: javascript webpack ecmascript-6


【解决方案1】:

我想我成功了。请记住,这是一种解决方法。

鉴于您说库正在从单个文件“重新导出”,您可以在“重新导出”中添加一个额外的“层”,我们将“重新导出”文件转换为 JS 文件并为它编写我们自己的关联打字文件。

工作回复:https://repl.it/@Olian04/CelebratedKlutzyQuotes

代码sn-ps:

// index.ts
// consuming the library
import { Foo } from './demo';

console.log(Foo());
// library.ts
// the library it self
const Foo = () => 'foo';

export { Foo }
// demo.js
// the workaround implementation 
const depricatedLibrary = require('./library');

const something = new Proxy(depricatedLibrary, {
  get(obj, key) {
    if (typeof key === 'string') {
      console.warn(key + ' is deprecated soon');
    }
    return obj[key];
  }
});

module.exports = something;
// demo.d.ts
// the workaround types
export * from './library';

【讨论】:

  • 是的代理上的好主意 - 尽管export * from './library' 在没有 TS 的情况下在我们当前的设置下失败。无论如何,谢谢,我会解决的。
  • @DimitarChristoff 如果您找到一个简单和/或令人满意的解决方案,请联系我。我想知道你是怎么解决的。祝你好运!
猜你喜欢
  • 2022-01-18
  • 2022-06-25
  • 2020-02-14
  • 2016-08-02
  • 2019-09-07
  • 2010-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-02-03
相关资源
最近更新 更多