1.0.2 • Published 5 years ago

specify-imports v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

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 use the required modules based off of a configuration file.

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"}]
    ]
}

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";
myModules["myThirdModule"] =  myThirdModule2;
import  myOtherModule1 from "./modules/myOtherModule";
myModules["myOtherModule"] =  myOtherModule1;
import  myModule0 from "./modules/myModule";
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
}

Future Features

  • Check for the existance of a file before including it
  • Allow the specification of file types, not just module names
  • Support multiple list identifiers. eg: [list1], [list2]

References

acornacorn-globalsababacorn-walkajvansi-escapesansi-regexansi-stylesanymatcharr-flattenargparsearray-equalarr-unionarr-diffarray-uniqueasn1assert-plusastral-regexasynckitaws-sign2aws4atobbabel-jestbabel-plugin-jest-hoistbabel-plugin-istanbulbalanced-matchbabel-preset-jestassign-symbolsbasebrace-expansionbcrypt-pbkdfbserbrowser-process-hrtimebracescache-basebrowser-resolvecallsitesbuffer-fromcamelcasecapture-exitchalkclass-utilscaselessci-infocliuicollection-visitcocollect-v8-coveragecolor-convertcomponent-emittercolor-namecombined-streamconcat-mapconvert-source-mapcopy-descriptorcross-spawncssomcore-util-iscssstyledashdashdebugdata-urlsdecamelizedecode-uri-componentdefine-propertydefine-propertiesdelayed-streamdeep-isdetect-newlinedomexceptionecc-jsbnemoji-regexdiff-sequenceses-to-primitiveend-of-streames-abstractescodegenescape-string-regexpesprimaesutilsestraverseexitexec-shexecaextendexpectexpand-bracketsextsprintffast-deep-equalextglobextend-shallowfast-levenshteinfill-rangefast-json-stable-stringifyfind-upfb-watchmanfor-inform-datafragment-cacheforever-agentfs.realpathfseventsgensyncfunction-bindget-streamget-valueget-caller-filegetpassglobglobalsgrowlyhar-schemagraceful-fshashar-validatorhas-symbolshas-valuehas-flaghas-valueshtml-escaperhttp-signaturehuman-signalshtml-encoding-sniffericonv-liteimurmurhashimport-localinflightinheritsip-regexis-callableis-accessor-descriptoris-ciis-data-descriptoris-bufferis-descriptoris-date-objectis-fullwidth-code-pointis-extendableis-generator-fnis-numberis-regexis-plain-objectis-streamis-symbolis-wslis-typedarrayisarrayis-windowsisobjectisexeisstreamistanbul-lib-coverageistanbul-lib-instrumentistanbul-reportsistanbul-lib-source-mapsistanbul-lib-reportjest-changed-filesjest-clijest-configjest-diffjest-docblockjest-environment-jsdomjest-environment-nodejest-eachjest-get-typejest-haste-mapjest-jasmine2jest-matcher-utilsjest-leak-detectorjest-mockjest-pnp-resolverjest-message-utiljest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-serializerjest-snapshotjest-validatejest-utiljest-workerjs-tokensjs-yamljsdomjsbnjson-schemajsescjson-schema-traversejson-stringify-safejson5jsprimkind-ofkleurlevnjest-watcherlocate-pathlodash.mergewithlevenlodashlodash.sortbymake-dirmakeerrorlolexmap-cachemap-visitmerge-streammime-dbmicromatchmime-typesmin-indentmimic-fnminimatchmixin-deepmsminimistmkdirpnanomatchnice-trynatural-comparenode-int64node-modules-regexpnode-notifiernormalize-pathnwsapinpm-run-pathoauth-signobject-copyobject-inspectobject-visitobject.assignobject-keysobject.pickobject.getownpropertydescriptorsonceonetimep-each-seriesp-finallyp-limitp-locatep-tryparse5optionatorpath-is-absolutepath-existspascalcasepath-keypath-parsepicomatchpiratespkg-dirpnposix-character-classesprelude-lsperformance-nowpromptspslpunycodeqspretty-formatreact-ispumpregex-notrealpath-nativerepeat-stringrequestrepeat-elementremove-trailing-separatorrequest-promise-nativerequire-directoryrequire-main-filenameresolve-cwdresolveresolve-fromresolve-urlretrimrafrequest-promise-corersvpsafe-buffersafer-buffersafe-regexsanesaxessemverset-valueshebang-commandset-blockingshellwordssignal-exitsisteransisnapdragon-nodesnapdragonshebang-regexsnapdragon-utilsource-mapsource-map-resolveslashsource-map-supportsource-map-urlsprintf-jssshpkstack-utilsstatic-extendstealthy-requirestring-lengthstring-widthsplit-stringstring.prototype.trimleftstrip-ansistring.prototype.trimrightstrip-bomstrip-eofstrip-final-newlinestrip-indentsupports-hyperlinkssupports-colorterminal-linksymbol-treethroattest-excludeto-fast-propertiestmplto-regexto-regex-rangeto-object-pathtough-cookietunnel-agenttweetnacltype-checktype-detecttype-festunion-valueunset-valuetr46uri-jsurixuuidutil.promisifyusetypedarray-to-bufferverrorw3c-hr-timev8-to-istanbulwalkerw3c-xmlserializerwhatwg-encodingwhatwg-mimetypewebidl-conversionswhatwg-urlwhichwhich-moduleword-wrapwrap-ansiwrappywrite-file-atomicwsxmlcharsxml-name-validatory18nyargsyargs-parser
1.0.2

5 years ago