CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-babel-plugin-named-asset-import

Babel plugin for named asset imports in Create React App

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

babel-plugin-named-asset-import

babel-plugin-named-asset-import is a Babel plugin that transforms named imports from asset files (particularly SVG files) by rewriting import paths according to a configurable loader map. It enables webpack-style loader syntax in import statements, specifically designed for Create React App to handle assets like SVG components through @svgr/webpack.

Package Information

  • Package Name: babel-plugin-named-asset-import
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install babel-plugin-named-asset-import

Core Imports

const namedAssetImportPlugin = require("babel-plugin-named-asset-import");

Basic Usage

Configure the plugin in your Babel configuration:

// babel.config.js
module.exports = {
  plugins: [
    [
      "babel-plugin-named-asset-import",
      {
        loaderMap: {
          svg: {
            ReactComponent: "@svgr/webpack?-svgo![path]"
          }
        }
      }
    ]
  ]
};

With this configuration, the plugin transforms:

// Input
import { ReactComponent as Logo } from "./logo.svg";

// Output
import { ReactComponent as Logo } from "@svgr/webpack?-svgo!./logo.svg";

Architecture

babel-plugin-named-asset-import is built around the Babel plugin architecture and AST transformation principles:

  • Plugin Factory Pattern: The main export is a factory function that receives Babel's API and returns a plugin object
  • Visitor Pattern: Uses Babel's visitor pattern to traverse and transform specific AST nodes
  • AST Transformation: Operates on ImportDeclaration and ExportNamedDeclaration nodes
  • Configuration-Driven: Behavior is controlled through the loaderMap configuration object
  • Idempotent Processing: Uses WeakSet tracking to prevent duplicate transformations
  • Path Rewriting: Transforms import/export paths by applying webpack loader syntax

The plugin integrates into Babel's compilation pipeline, intercepting module import/export statements and conditionally rewriting them based on file extensions and named import patterns defined in the configuration.

Capabilities

Plugin Factory Function

The main export is a Babel plugin factory function that creates a Babel plugin with visitor methods.

/**
 * Creates a Babel plugin that transforms named asset imports
 * @param {Object} babel - Babel object containing types (t)
 * @param {Object} babel.types - Babel types utilities (destructured from babel param)
 * @returns {Object} Babel plugin object with visitor methods
 */
function namedAssetImportPlugin({ types: t }): BabelPlugin;

interface BabelPlugin {
  visitor: {
    ExportNamedDeclaration(path: NodePath, state: PluginState): void;
    ImportDeclaration(path: NodePath, state: PluginState): void;
  };
}

Plugin Configuration

The plugin accepts configuration through Babel's options system.

interface PluginOptions {
  /** Maps file extensions to loader configurations */
  loaderMap: LoaderMap;
}

interface LoaderMap {
  /** File extension (without dot) */
  [extension: string]: {
    /** Named import to loader string mapping */
    [namedImport: string]: string;
  };
}

Configuration Example:

{
  loaderMap: {
    svg: {
      ReactComponent: "@svgr/webpack?-svgo![path]"
    },
    png: {
      WebpImage: "webp-loader![path]"
    }
  }
}

Import Declaration Transformation

Transforms import declarations from asset files when they match the loader map configuration.

Supported Import Patterns:

  • Named imports: Transforms specific named imports according to loader map
  • Default imports: Left unchanged
  • Mixed imports: Splits into multiple import statements

Examples:

// Named import transformation
import { ReactComponent } from "./logo.svg";
// Becomes:
import { ReactComponent } from "@svgr/webpack?-svgo!./logo.svg";

// Mixed import splitting
import logo, { ReactComponent as Logo } from "./logo.svg";
// Becomes:
import logo from "./logo.svg";
import { ReactComponent as Logo } from "@svgr/webpack?-svgo!./logo.svg";

// Multiple named imports (from test case)
import logo, { logoUrl, ReactComponent as Logo } from "logo.svg";
// Becomes:
import logo from "logo.svg";
import { logoUrl } from "logo.svg";
import { ReactComponent as Logo } from "@svgr/webpack?-svgo!logo.svg";

Export Declaration Transformation

Transforms export declarations from asset files when they match the loader map configuration.

Supported Export Patterns:

  • Named exports: Transforms specific named exports according to loader map
  • Default exports: Left unchanged
  • Mixed exports: Splits into multiple export statements

Examples:

// Named export transformation
export { ReactComponent } from "./logo.svg";
// Becomes:
export { ReactComponent } from "@svgr/webpack?-svgo!./logo.svg";

// Mixed export splitting (from test case)
export { logoUrl, ReactComponent as Logo } from "logo.svg";
// Becomes:
export { logoUrl } from "logo.svg";
export { ReactComponent as Logo } from "@svgr/webpack?-svgo!logo.svg";

Plugin Behavior

File Extension Matching

The plugin only processes files with extensions defined in the loaderMap configuration:

  • Files without matching extensions are ignored
  • Extension matching is case-sensitive
  • Extensions are extracted using Node.js path.extname() and normalized by removing the leading dot

Loader String Processing

Loader strings support path placeholder substitution:

  • [path] placeholder is replaced with the original import path
  • Loader strings can contain webpack loader syntax and options
  • Multiple loaders can be chained using ! syntax

Duplicate Processing Prevention

The plugin uses a WeakSet to track processed AST nodes:

  • Prevents infinite loops during transformation
  • Skips files already containing webpack loader syntax (paths with !)
  • Ensures idempotent transformations

AST Node Transformation

The plugin transforms specific Babel AST node types:

  • ImportDeclaration: Handles import statements from external modules
  • ExportNamedDeclaration: Handles named export statements with source (re-exports only)
  • Specifier types: ImportDefaultSpecifier, ImportSpecifier, ExportDefaultSpecifier, ExportSpecifier

Types

interface NodePath {
  node: ImportDeclaration | ExportNamedDeclaration;
  replaceWithMultiple(nodes: Array<ImportDeclaration | ExportNamedDeclaration>): void;
}

interface PluginState {
  opts: PluginOptions;
}

interface ImportDeclaration {
  type: "ImportDeclaration";
  source: StringLiteral;
  specifiers: Array<ImportSpecifier | ImportDefaultSpecifier>;
}

interface ExportNamedDeclaration {
  type: "ExportNamedDeclaration";
  source: StringLiteral | null;
  specifiers: Array<ExportSpecifier | ExportDefaultSpecifier>;
}

interface StringLiteral {
  type: "StringLiteral";
  value: string;
}

docs

index.md

tile.json