Home

Awesome

babel-plugin-direct-import

Main npm version npm downloads Maintainability Test Coverage

Babel plugin to cherry-pick ES module imports.

Installation

npm install --save-dev babel-plugin-direct-import

Example

In

import { Button, colors, ThemeProvider } from "@mui/material";
import {
  ChevronLeft as ChevronLeftIcon,
  ChevronRight as ChevronRightIcon,
} from "@mui/icons-material";

Out

import Button from "@mui/material/Button/Button.js";
import * as colors from "@mui/material/colors/index.js";
import ThemeProvider from "@mui/system/esm/ThemeProvider/ThemeProvider.js";
import ChevronLeftIcon from "@mui/icons-material/esm/ChevronLeft.js";
import ChevronRightIcon from "@mui/icons-material/esm/ChevronRight.js";

Usage

Via .babelrc (Recommended)

.babelrc

{
  "plugins": [
    [
      "babel-plugin-direct-import",
      {
        "modules": ["@mui/system", "@mui/material", "@mui/icons-material"]
      }
    ]
  ]
}

Via Node API

require("babel-core").transform("code", {
  plugins: [
    [
      "babel-plugin-direct-import",
      {
        modules: ["@mui/system", "@mui/material", "@mui/icons-material"],
      },
    ],
  ],
});

Limitations

Transformation of namespace imports:

Namespace imports are hard to analyze, that's why we skip them.

import * as MUI from "@mui/material";

return (props) => <MUI.Checkbox {...props} />;
Mapping of variable exports:
import * as colors from "./colors";

export const blue = colors.blue;
export const cyan = colors.cyan;
export const getDefaultColor = () => red;

Tested Packages

Material UI (v4)
{
  "plugins": [
    [
      "babel-plugin-direct-import",
      {
        "modules": [
          "@material-ui/lab",
          "@material-ui/core",
          "@material-ui/icons",
          "@material-ui/system"
        ]
      }
    ]
  ]
}
Material UI (v5)
{
  "plugins": [
    [
      "babel-plugin-direct-import",
      {
        "modules": [
          "@mui/lab",
          "@mui/system",
          "@mui/material",
          "@mui/icons-material"
        ]
      }
    ]
  ]
}

Integrations

Next.js

// babel.config.js

module.exports = (api) => {
  const target = api.caller((caller) => caller.target);

  api.cache.using(() => JSON.stringify({ target }));

  const presets = ["next/babel"];
  const plugins = [];

  // Enable optimizations only for the `web` bundle.
  if (target === "web") {
    plugins.push([
      "babel-plugin-direct-import",
      { modules: ["@mui/lab", "@mui/material", "@mui/icons-material"] },
    ]);
  }

  return { presets, plugins };
};

Migration

0.5.0 to 0.6.0

After migration to Babel v7 it's impossible to pass arrays as configs, and now you have to pass an object with modules property:

Before:

{
  "plugins": [["babel-plugin-direct-import", ["@material-ui/core"]]]
}

After:

{
  "plugins": [
    ["babel-plugin-direct-import", { "modules": ["@material-ui/core"] }]
  ]
}

Heavily inspired by: