babel-plugin-specify-imports

1.1.1 • Public • Published

Specify Imports

A Babel plugin that allows you to specify your imports based off a config file.

A good use case for this plugin would be a project that will be built many different times, and each build requires a different set of components. Instead of inculding each component for every different build, you can use Specify Imports to import only the required modules for that build.

Installation

$ npm install babel-specify-imports

Usage

In your .babelrc, or wherever your plugins are defined, specify the imports by defining moduleListPath. This path is relative to process.cwd().

{
    plugins: [
        ["specify-imports", {
            "moduleListPath": "path/to/settings.js",
            "extensions" : 'js',
            }
        ]
    ]
}

settings.js should export the list of module names that you want to use

module.exports = {
    moduleList: [
        "myModule",
        "aCustomModule",
        "awesomeComponent"
    ]
}

However, a more useful way to export the module list would be something like this

const settings = {
    views: [
        {
            moduleName: "myModule",
            viewSettings: {}
        },
        {
            moduleName: "aCustomModule",
            viewSettings: {}
        },
        {
            moduleName: "awesomeComponent",
            viewSettings: {}
        }
    ]
}
module.exports = {
    settings: settings, // to be used elsewhere in the project
    moduleList: settings.views.map(view => view.moduleName) // used by specify-import
}

In the file that you want to import your modules into, indicate that you will be using Specify Imports by using the "[list]" identifier and a relative path. Specify Imports will not modify any other import statements.

import myModules from './modules/[list]'; 

This will cause the above import statement to transpile into:

const myModules = {};
import  myThirdModule2 from "./modules/myThirdModule.js";
myModules["myThirdModule"] =  myThirdModule2;
import  myOtherModule1 from "./modules/myOtherModule.js";
myModules["myOtherModule"] =  myOtherModule1;
import  myModule0 from "./modules/myModule.js";
myModules["myModule"] =  myModule0;

The modules can be referenced like any object member

myModules.myOtherModule1.doSomething();

But its typically most useful to iterate through the parent object with a for...in loop, or another method.

for(const myModule in myModules){
    // do something with each imported module
}

Other Features

Specify Imports checks for the existance of a file before including it.

Future Features

  • Allow for granular specification of file types, or, let users associate module names with file extensions
  • Support multiple list identifiers. eg: [list1], [list2]

References

Package Sidebar

Install

npm i babel-plugin-specify-imports

Weekly Downloads

1

Version

1.1.1

License

MIT

Unpacked Size

21.1 kB

Total Files

16

Last publish

Collaborators

  • ianband