ES6模块化导入一组文件,具有个别导出。

17 浏览
0 Comments

ES6模块化导入一组文件,具有个别导出。

我想将一些模块组合成一个可以导入的单个文件。这些是本地文件,不是npm模块的一部分。

模块 Kitten (kitten.js)

export function Feed() {}
export function Play() {}

在我的代码中,我可以访问“Feed”和“Play”:

// This works but I would like to avoid this due to my paths
import { Feed, Play } from './some/long/path/kitten.js'
// Then use it
Feed()

由于我有很多“宠物”,我可以在主文件中将它们连接起来 - 比如说 pets.js

export * as Kitten from './some/long/path/kitten.js'
export * as Puppies from './some/long/path/puppies.js'
...

然后在我的代码中,我可以这样做:

import { Kitten, Puppies } from './pets'
// Then use it as
Kitten.Feed()

是否可以同时拥有a)主pets文件和b)不需要做Kitten.Feed()的调用Feed()

以下内容无法工作,因为它不是有效的路径。如果它是npm模块,“pets/Kitten”可能会起作用- 我不确定。

import { Feed, Play } from './pets/Kitten'

我想到了以下内容:

import * as Pets from from './pets'
import { Feed, Play } from Pets.Kitten // or 'Pets/Kitten'

但很明显那无法工作。我想知道是否有可能。

我在使用具有Babel 6和ES6模块加载的Node。我看到许多类似的问题,但它们都使用默认导出,而我没有使用。

admin 更改状态以发布 2023年5月21日
0
0 Comments

啊.. 对象解构.. 忘记了这个。

import { Kitten, Puppies } from './pets'
const {Feed, Play} = Kitten;

感谢 https://stackoverflow.com/a/30132149/856498

0
0 Comments

但这并不允许我导入选定的函数。

当然可以。相对路径导入与模块导入相同。你可以使用相同的解构结果。

import { Play } from 'Pet/Puppy';
// is identical to
import { Play } from '../node_modules/Pet/Puppy';

如果你查看import语法(s15.2.2),你会发现from部分期望一个字符串。它不关心字符串中的内容,这是由模块系统(浏览器,节点等)决定的。

0