ES6模块导入具有单独导出的文件组
我想将一些模块组合成一个可导入的文件。 这些是本地文件,不是npm模块的一部分。
模块小猫(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)主宠物文件和b)调用Feed()
没有做Kitten.Feed()
?
以下不起作用,因为它不是一个有效的path。 如果是npm模块,这可能会成为'宠物/小猫' – 我不确定。
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中使用它。 我看到很多类似的问题,但他们都使用默认输出,我不使用。
但是,这不允许我导入选定的function。
当然是的。 相对path导入与模块导入相同。 你可以解构结果一样。
import { Play } from 'Pet/Puppy'; // is identical to import { Play } from '../node_modules/Pet/Puppy';
如果你看一下import
语法(s15.2.2) ,你可以看到from
部分需要一个string。 它并不关心string中的内容,取决于模块系统(浏览器,节点等)。
对象解构..忘了那个。
import { Kitten, Puppies } from './pets' const {Feed, Play} = Kitten;