Babel plugin to cherry-pick ES module imports.
npm install --save-dev babel-plugin-direct-import
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";
.babelrc
{
"plugins": [
[
"babel-plugin-direct-import",
{
"modules": ["@mui/system", "@mui/material", "@mui/icons-material"]
}
]
]
}
require("babel-core").transform("code", {
plugins: [
[
"babel-plugin-direct-import",
{
modules: ["@mui/system", "@mui/material", "@mui/icons-material"],
},
],
],
});
Namespace imports are hard to analyze, that's why we skip them.
import * as MUI from "@mui/material";
return (props) => <MUI.Checkbox {...props} />;
import * as colors from "./colors";
export const blue = colors.blue;
export const cyan = colors.cyan;
export const getDefaultColor = () => red;
{
"plugins": [
[
"babel-plugin-direct-import",
{
"modules": [
"@material-ui/lab",
"@material-ui/core",
"@material-ui/icons",
"@material-ui/system"
]
}
]
]
}
{
"plugins": [
[
"babel-plugin-direct-import",
{
"modules": [
"@mui/lab",
"@mui/system",
"@mui/material",
"@mui/icons-material"
]
}
]
]
}
// 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 };
};
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"] }]
]
}