Giter Club home page Giter Club logo

babel-transform-imports's Introduction

babel-plugin-transform-imports

Transforms member style imports:

import { Row, Grid as MyGrid } from 'react-bootstrap';
import { merge } from 'lodash';

...into default style imports:

import Row from 'react-bootstrap/lib/Row';
import MyGrid from 'react-bootstrap/lib/Grid';
import merge from 'lodash/merge';

Note: this plugin is not restricted to the react-bootstrap and lodash libraries. You may use it with any library.

Why?

When Babel encounters a member style import such as:

import { Grid, Row, Col } from 'react-bootstrap';

it will generate something similarish to:

var reactBootstrap = require('react-bootstrap');
var Grid = reactBootstrap.Grid;
var Row = reactBootstrap.Row;
var Col = reactBootstrap.Col;

Which causes the entire library to be loaded, even though only some components are needed. Some libraries are rather large and pulling in the entire module would cause unnecessary bloat to your client optimized (webpack etc.) bundle. The only way around this is to use default style imports:

import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';

But, the more pieces we need, the more this sucks. This plugin will allow you to pull in just the pieces you need, without a separate import for each item. Additionally, it can be configured to throw when somebody accidentally writes an import which would cause the entire module to resolve, such as:

import Bootstrap, { Grid } from 'react-bootstrap';
// -- or --
import * as Bootstrap from 'react-bootstrap';

Installation

yarn add git://github.com/ElMassimo/babel-transform-imports.git

Usage

In .babelrc:

{
    "plugins": [
        ["transform-imports", {
            "react-bootstrap": {
                "transform": "react-bootstrap/lib/${member}",
                "preventFullImport": true
            },
            "lodash": {
                "transform": "lodash/${member}",
                "preventFullImport": true
            }
        }]
    ]
}

Advanced Transformations

Using regular expressions

Sometimes, you may wish to use regular expressions in your transformation (for example, to enforce the same convention in all folder levels on the structure of your library).

.babelrc:

{
    "plugins": [
        ["transform-imports", {
            "my-library\/?(((\\w*)?\/?)*)": {
                "transform": "my-library/${1}/${member}",
                "preventFullImport": true
            }
        }]
    ]
}

Causes this code:

import { MyModule } from 'my-library';
import { App } from 'my-library/components';
import { Header, Footer } from 'my-library/components/App';

to become:

import MyModule from 'my-library/MyModule';
import App from 'my-library/components/App';
import Header from 'my-library/components/App/Header';
import Footer from 'my-library/components/App/Footer';

Using a function as the transformer

If you need more advanced or more specific transformation logic, and are using Babel 7+ with a .babel.config.js file, you may provide a function instead of a string for the transform option:

.babel.config.js:

module.exports = {
    presets: ['@babel/env'],
    plugins: [
        ['transform-imports', {
            'date-fns': {
                transform: importName => `date-fns/${camelCase(importName)}`,
                preventFullImport: true,
            },
            'my-library': {
                transform: function(importName, matches) {
                    return `my-library/etc/${importName.toUpperCase()}`;
                },
                preventFullImport: true,
            }
        }]
    ]
};

You may combine a regular expression in the library name with a function transform, any captures of the regex will be passed as a second argument (matches).

Webpack

This can be used as a plugin with babel-loader.

webpack.config.js:

module: {
    rules: [{
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
            loader: 'babel-loader',
            query: {
                plugins: [
                    [require('babel-plugin-transform-imports'), {
                        'my-library': {
                            transform: function(importName, matches) {
                                return 'my-library/etc/' + importName.toUpperCase();
                            },
                            preventFullImport: true
                        }
                    }]
                ]
            }
        }
    }]
}

Options

Name Type Required Default Description
transform string or function yes undefined The library name to use instead of the one specified in the import statement. ${member} will be replaced with the import name, aka Grid/Row/Col/etc., and ${1-n} will be replaced by any matched regular expression groups. If using a JS Babel config file, a function may be passed directly. (see Advanced Transformations)
preventFullImport boolean no false Whether or not to throw when an import is encountered which would cause the entire module to be imported.
skipDefaultConversion boolean no false When set to true, will preserve import { X } syntax instead of converting to import X.

babel-transform-imports's People

Contributors

elmassimo avatar gpittarelli avatar haroenv avatar jacobbuck avatar nachocodoner avatar timsnadden avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.