babel-plugin-reimport v0.1.0
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:
import {AutoSizer, Table} from 'react-virtualized';
Basing on your build type, you want to get in your code:
CommonJS
const AutoSizer = require('react-virtualized/dist/commonjs/AutoSizer').default;
const Table = require('react-virtualized/dist/commonjs/Table').default;
ES
import AutoSizer from 'react-virtualized/dist/es/AutoSizer';
import Table from 'react-virtualized/dist/es/Table';
To get it you have to define following function:
const isCommonjs = process.env.BUILD_TYPE === 'commonjs';
function transform (token, library) {
switch (token) {
case 'AutoSizer':
case 'Table':
return {
default: true,
module: `${library}/dist/${isCommonjs ? 'commonjs' : 'es'}/${token}`,
};
default:
return library; // in case you still have something to import from 'react-virtualized' itself
}
}
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:
module.exports = {
plugins: [
[require('babel-plugin-reimport'), {
'react-virtualized': {
transform(token, library) {
// your transformation code
},
},
}],
],
};
Using old Babel JSON configuration (path starts from cwd
):
{
"plugins": [
["reimport", {
"react-virtualized": {
"transform": "./path/to/your/transform.js"
}
}]
]
}
Known limitations
- Plugin won't work with default import. It may change in future versions.
6 years ago