babel-plugin-reimport
Working with huge libraries prepared for two environments - es
and commonjs
is hard. You are not
able to import only component you want - you have to import whole library. And time to time even
tree-shaking cannot handle it.
This Babel plugin does all work for you. You just have to define rules it follows.
Installation
$ npm install --save-dev babel-plugin-reimport
Usage
Imagine you have a library that should be compiled to es
and commonjs
. You want to split an import declaration
from a huge library, e.g. react-virtualized
, to separate parts.
You have following import in your code:
;
Basing on your build type, you want to get in your code:
CommonJS
const AutoSizer = default;const Table = default;
ES
;;
To get it you have to define following function:
const isCommonjs = processenvBUILD_TYPE === 'commonjs'; { }
Transform function
Arguments:
-
token: string
Import specifier name,AutoSizer
orTable
for our example. -
library: string
Library name.
Returns one of:
-
Object with following params:
default: boolean
- indicates that you want to make your current token imported by default (i.e.import x from 'y'
instead ofimport {x} from 'y'
).module: string
- path to module you want to import from. You can build it basing on current environment, so paths fores
andcommonjs
will differ.
-
String. It is only module name, and all imports will be not default (
import {x} from 'y'
).
Babel configuration
Using new Babel configuration based on JS:
moduleexports = plugins: 'react-virtualized': { // your transformation code } ;
Using old Babel JSON configuration (path starts from cwd
):
Known limitations
- Plugin won't work with default import. It may change in future versions.