ES6中的全球导入

时间:2018-06-21 18:53:07

标签: javascript es6-modules es6-module-loader

我有一个大型的第三方库,需要在两个项目之间共享。该项目有多个文件夹,其中多个文件包含多个导出。而不是像这样导入这些模块

import {BaseContainer} from '@company/customproject/src/containers/BaseContainer.js'

我想这样做

import { BaseContainer } from '@company/customproject'

我知道我可以将所有模块手动导入到基本目录中的单个index.js文件中,但是我想知道是否有一种更简便的方法来不显式导入所有模块

2 个答案:

答案 0 :(得分:2)

  

我知道我可以将所有模块手动导入到基本目录中的单个index.js文件中,但是我想知道是否有一种更简便的方法可以不显式地导入所有模块

您实际上应该只创建一个index.js文件并将其导入到您要导出的任何文件中,以便可以控制导出哪些API,而不导出私有API。

也就是说,有一个automated tool会自动为您生成一个index.js

> npm install -g create-index
> create-index ./src

这将为所有导出生成一个index.js

答案 1 :(得分:0)

另一个答案表明,您应该在每个目录中创建一个index.js并显式导出内容

@ company / customproject / index.js

import {BaseContainer, SomeOtherContainer} from './src/containers'

export {
  BaseContainer,
  SomeOtherContainer
}

@ company / customproject / src / containers / index.js

import BaseContainer from './BaseContainer'
import SomeOtherContainer from './SomeOtherContainer'

export {
  BaseContainer,
  SomeOtherContainer
}

另一个自动加载整个目录的选项是使用requiremodule.exports导出每个扫描的文件。使用ES6导入/导出以及module.exports和默认导出语句,您可能会遇到冲突。

@ company / customproject / index.js

const fs = require('fs')
const modules = {}

fs.readdirSync(__dirname+'/src/containers').forEach(file => {
  file = file.replace('.js', '')
  modules[file] = require('./src/containers/'+file)
  // map default export statement
  if (modules[file].default) {
    modules[file] = modules[file].default
  }
})

module.exports = modules

然后只需在任何ES5或ES6模块中使用它

const {BaseContainer} = require('@company/customproject')

import {BaseContainer} from '@company/customproject'
相关问题