I have a large third party library that I need to share between two projects. The project has multiple folders with multiple files that contain multiple exports. Instead of importing these modules like this
import {BaseContainer} from '@pany/customproject/src/containers/BaseContainer.js'
I would like to do this
import { BaseContainer } from '@pany/customproject'
I know I can manually import all the modules into a single index.js file in the base directory but i am wondering if there is an easier way to do not have import them all explicitly
I have a large third party library that I need to share between two projects. The project has multiple folders with multiple files that contain multiple exports. Instead of importing these modules like this
import {BaseContainer} from '@pany/customproject/src/containers/BaseContainer.js'
I would like to do this
import { BaseContainer } from '@pany/customproject'
I know I can manually import all the modules into a single index.js file in the base directory but i am wondering if there is an easier way to do not have import them all explicitly
Share Improve this question asked Jun 21, 2018 at 18:53 josephmisitijosephmisiti 9,99412 gold badges57 silver badges72 bronze badges2 Answers
Reset to default 3I know I can manually import all the modules into a single index.js file in the base directory but i am wondering if there is an easier way to do not have import them all explicitly
You should really just create an index.js
file and import into that whatever you want to export so that you can control what APIs get exported and to not export private APIs.
That said there is an automated tool that generates an index.js
automatically for you:
> npm install -g create-index
> create-index ./src
Which will generate an index.js
with all the exports.
As the other answer suggests, you should create an index.js
within each directory and explicitly export contents
@pany/customproject/index.js
import {BaseContainer, SomeOtherContainer} from './src/containers'
export {
BaseContainer,
SomeOtherContainer
}
@pany/customproject/src/containers/index.js
import BaseContainer from './BaseContainer'
import SomeOtherContainer from './SomeOtherContainer'
export {
BaseContainer,
SomeOtherContainer
}
Another option to autoload an entire directory is using require
and module.exports
to export every scanned file, however. You would likely run into conflicts using both ES6 import/export along with module.exports
and default export statements.
@pany/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
Then simply use it in any ES5 or ES6 module
const {BaseContainer} = require('@pany/customproject')
or
import {BaseContainer} from '@pany/customproject'