SWC plugin for transforming import path.

Overview

swc-plugin-transform-import

Inspired from babel-plugin-transform-imports

Installation

npm i -D swc-plugin-transform-import

Uses with webpack-config

// webpack.config.js

const PluginTransformImport = require('swc-plugin-transform-import').default;

module: {
    rules: [
      {
        test: /\.(ts|tsx|js|jsx)$/,
        exclude: /node_modules/,
        use: [{
          loader: 'swc-loader',
          options: {
            plugin: (m) => new PluginTransformImport({
              "lodash": {
                "transform": "lodash/${member}",
                "preventFullImport": true
              }
            }).visitProgram(m),
          }
        }]
      },
    ],
};
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.

That's stupid, why would you do that?

When SWC 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;

Some libraries, such as react-bootstrap and lodash, are rather large and pulling in the entire module just to use a few pieces 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

npm install --save-dev swc-plugin-transform-import

Advanced Transformations

In cases where the provided default string replacement transformation is not sufficient (for example, needing to execute a RegExp on the import name), you may instead provide a path to a .js file which exports a function to run instead. Keep in mind that the .js file will be required relative from this plugin's path, likely located in /node_modules/babel-plugin-transform-imports. You may provide any filename, as long as it ends with .js.

.babelrc:

{
    "plugins": [
        ["transform-imports", {
            "my-library": {
                "transform": "../../path/to/transform.js",
                "preventFullImport": true
            }
        }]
    ]
}

/path/to/transform.js:

module.exports = function(importName) {
    return 'my-library/etc/' + importName.toUpperCase();
};

Options

Name Type Required Default Description
transform string yes undefined The library name to use instead of the one specified in the import statement. ${member} will be replaced with the member, aka Grid/Row/Col/etc. Alternatively, pass a path to a .js file which exports a function to process the transform (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.
You might also like...

This package enables you to mount your Remix app at a different path than root

This package enables you to mount your Remix app at a different path than root

Remix Mount Routes This package enables you to mount your Remix app at a different path than root. 🛠 Installation npm install -D remix-mount-routes

Dec 17, 2022

Detect the executable python interpreter cmd in $PATH.

detect-python-interpreter Detect the executable python interpreter cmd in $PATH. Installation $ npm install --save detect-python-interpreter Usage con

Apr 12, 2022

Path-finding & Sorting algorithms Visualizer

Update - Changelog 📋 09.05.2022 AlgoVision is now fully mobile-responsive for all its features ! On mobile, the 'Mouse Chase' option in Dynamic Mode

Dec 18, 2022

Userland module that implements the module path mapping that Node.js does with "exports" in package.json

exports-map Userland module that implements the module path mapping that Node.js does with "exports" in package.json npm install exports-map Usage co

May 31, 2022

Sort imports by path - VS Code extension

Import sort by absolute path The sorting algorithm will group each item in the array and sort (alphabetically) its children that starts with the path

Feb 2, 2022

Find and parse the tsconfig.json file from a directory path

get-tsconfig Find and parse tsconfig.json files. Features Zero dependencies (not even TypeScript) Tested against TypeScript for accuracy Supports comm

Jan 2, 2023

A Multi-Agent Path Finding visualization website.

A Multi-Agent Path Finding visualization website.

MAPF Visualizer A visualization tool for multi-agent path finding algorithms. About The Project This project provides a visualization tool for Multi-A

Dec 29, 2022

A third-party messenger application for Path of Exile.

A third-party messenger application for Path of Exile.

PoE Instant Messenger Download (Windows) The latest release can be downloaded here Tool showcase Theme Setup Notifier Messenger Settings Light Dark Co

Jul 29, 2022

Easily create test fixtures at a temporary file-system path

fs-fixture Easily create test fixtures at a temporary file-system path. Support this project by ⭐ starring and sharing it. Follow me to see what othe

Dec 15, 2022
Comments
  • How to add to .swcrc

    How to add to .swcrc

    Not an issue but a question. I'm currently using @swc/register to transpile on the fly for local development. How do I add this plugin to the .swcrc config file? Or would I somehow add it as an option to @swc/register? Thanks.

    opened by yvuong 8
  • feat(styleTransform): add styleTransform opt

    feat(styleTransform): add styleTransform opt

    There are some cases we need to fine tune the transformed style import.

    I propose complementing the style opt as a function

    style: (transformedPath: string) => string

    Inspired from babel-plugin-import https://www.npmjs.com/package/babel-plugin-import#style

    opened by thienphanexcalibur 3
Releases(v1.2.0)
  • v1.2.0(Mar 8, 2022)

    What's Changed

    • feat(styleTransform): add styleTransform opt by @thienphanexcalibur in https://github.com/ankitchouhan1020/swc-plugin-transform-import/pull/2

    New Contributors

    • @thienphanexcalibur made their first contribution in https://github.com/ankitchouhan1020/swc-plugin-transform-import/pull/2

    Full Changelog: https://github.com/ankitchouhan1020/swc-plugin-transform-import/compare/v1.1.2...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.2(Mar 8, 2022)

    What's Changed

    • Add style option by @myklt in https://github.com/ankitchouhan1020/swc-plugin-transform-import/pull/1

    New Contributors

    • @myklt made their first contribution in https://github.com/ankitchouhan1020/swc-plugin-transform-import/pull/1

    Full Changelog: https://github.com/ankitchouhan1020/swc-plugin-transform-import/compare/v1.0.1...v1.1.2

    Source code(tar.gz)
    Source code(zip)
Owner
Ankit Chouhan
Ankit Chouhan
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till mÀnniskor pÄ flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
convert SWC to Babel AST

SWC-to-babel Convert SWC JavaScript AST to Babel AST. To use SWC parser with babel tools like: @babel/traverse @babel/types etc... The thing is @babel

coderaiser 23 Oct 28, 2022
Storybook add-on to enable SWC builds.

storybook-addon-swc Storybook addon that improves build time by building with swc. ?? Examples webpack4 webpack5 ?? Installation $ npm install -D stor

Karibash 49 Dec 20, 2022
💅 A ready-to-go with a well-thought-out structure Electron app boilerplate with ReactJS, TypeScript, CSS / SASS modules, SWC, Eslint, Prettier, GitHub Action releases and more.

Electron App ??  A ready-to-go with a well-thought-out structure Electron app boilerplate with ReactJS, TypeScript, CSS / SASS modules, SWC, Eslint, P

Dalton Menezes 155 Dec 29, 2022
An experimental transpiler to bring tailwind macros to SWC 🚀

stailwc (speedy tailwind compiler) This is an experimental SWC transpiler to bring compile time tailwind macros to SWC (and nextjs) a-la twin macro. T

Alexander Lyon 140 Jan 3, 2023
Snippets for securing, transforming, and optimizing GraphQL APIs.

StepZen Snippets Welcome! StepZen is a unique and declarative way to build & run any-sized Graph in minutes. Explore the docs View Demo Report Bug Req

StepZen 13 Nov 9, 2022
A meme generator plugin for Figma and FigJam. Import memes from all over the internet with customizable captions and share it far and wide.

Is This A Meme? ???? ?? A meme generator plugin for Figma and FigJam. Import memes from all over the internet, add your captions, and share it far and

Aashrey Sharma 6 Aug 30, 2022
A plugin that can query multiple APIs for movies, series, anime, games, music and wiki articles, and import them into your vault.

Obsidian Media DB Plugin A plugin that can query multiple APIs for movies, series, anime, games, music and wiki articles, and import them into your va

Moritz Jung 58 Dec 21, 2022