• Stars
    star
    567
  • Rank 78,634 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

babel-import-plugin TypeScript Implement

Financial Contributors on Open Collective npm version CircleCI codecov

ts-import-plugin

Modular import plugin for TypeScript, compatible with antd, antd-mobile and so on.

webpack template ./webpack.config.js, run: npm start to see the bundle analyzer.

This plugin is not work if your are using import * as _ from 'lodash' or import _ from 'lodash'

bundle-analyzer

Why use this

transform such code:

import { Alert, Card as C } from 'antd'

into:

import Alert from 'antd/lib/alert'
import 'antd/lib/alert/style/index.less'
import { default as C } from 'antd/lib/card'
import 'antd/lib/card/style/index.less'

Usage

With ts-loader

//tsconfig.json
{
  ...
  "module": "ESNext",
  ...
}
// webpack.config.js
const tsImportPluginFactory = require('ts-import-plugin')

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.(jsx|tsx|js|ts)$/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
          getCustomTransformers: () => ({
            before: [tsImportPluginFactory(/** options */)],
          }),
          compilerOptions: {
            module: 'es2015',
          },
        },
        exclude: /node_modules/,
      },
    ],
  },
  // ...
}

With awesome-typescript-loader ( >= 3.5.0 )

//tsconfig.json
{
  ...
  "module": "ESNext",
  ...
}
// webpack.config.js
const tsImportPluginFactory = require('ts-import-plugin')

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        options: {
          getCustomTransformers: () => ({
            before: [tsImportPluginFactory(/** options */)],
          }),
        },
        exclude: /node_modules/,
      },
    ],
  },
  // ...
}

With rollup

import typescript from 'rollup-plugin-typescript2' // or '@rollup/plugin-typescript'
import createTransformer from 'ts-import-plugin'

const transformer = createTransformer({
  libraryDirectory: 'es',
  libraryName: 'antd',
  style: true,
})

export default {
  input: `./test/fixtures/index.tsx`,
  plugins: [
    typescript({
      clean: true,
      transformers: [
        () => ({
          before: transformer,
        }),
      ],
    }),
  ],
  output: [
    {
      file: `./dist/rollup.dist.js`,
      format: 'esm',
    },
  ],
}

Options

options can be an object:

  • libraryName string - The name of the library in the import. e.g. If using import { foo } from 'Bar' the library should be set to 'bar'.

    default 'antd'

  • style boolean | string | ((path: string) => string)

    default false

  • libraryDirectory string | ((name: string) => string) - The directory within the library to replace the import with. e.g. If you have import { foo } from 'Bar', it will be replaced to import foo from `Bar/${libraryDirectory}/foo``

    default 'lib'

  • camel2DashComponentName boolean - Builtin method to use to transform the component name. This does transform the component name from camelCase to dashed. e.g. FooBar gets transformed to foo-bar

    default true

  • camel2UnderlineComponentName boolean - Builtin method to use to transform the component name. This does transform the component name from camelCase to snake_case. e.g. FooBar gets transformed to foo_bar

    default false

  • libraryOverride boolean - Setting to false (default) prepends the libraryName to the libraryDirectory (with a path separator) set to true if you want to use the libraryDirectory as the full path for the import.

    default false

  • failIfNotFound boolean - If the component is not found in the library, the full library is imported by default. set to true to fail the build.

    default false

example:

tsImportPluginFactory({
  libraryName: 'antd',
  libraryDirectory: 'lib',
  style: true,
})
{
  libraryName: '@material-ui/core',
  libraryDirectory: '',
  camel2DashComponentName: false
}

options can be an array:

example:

;[
  {
    libraryName: 'antd',
    libraryDirectory: 'lib',
    style: true,
  },
  {
    libraryName: '@material-ui/core',
    libraryDirectory: '',
    camel2DashComponentName: false,
  },
]

Compatible libs:

ant-design

const transformerFactory = require('ts-import-plugin')
// with less
transformerFactory({ style: true })
// with css
transformerFactory({ style: 'css' })
// without style
transformerFactory()

lodash

notice you should manual import 'lodash/core' in your project if your are using import { chain } from 'lodash' .

transformerFactory({
  style: false,
  libraryName: 'lodash',
  libraryDirectory: null,
  camel2DashComponentName: false,
})

antd-mobile

// with css.web
transformerFactory({ libraryName: 'antd-mobile', style: 'css', styleExt: 'css.web' })

// antd-mobile recently changed styleExt. If error occurs with prev, try next.
transformerFactory({ libraryName: 'antd-mobile', style: 'css' })

material-ui

import { Button } from '@material-ui/core'
import { Remove, Refresh, Add } from '@material-ui/icons'
transformerFactory({
  libraryName: '@material-ui/core',
  libraryDirectory: '',
  camel2DashComponentName: false,
})

// svg-icons
transformerFactory({
  libraryDirectory: (importName) => {
    const stringVec = importName
      .split(/([A-Z][a-z]+|[0-9]*)/)
      .filter((s) => s.length)
      .map((s) => s.toLocaleLowerCase())

    return stringVec.reduce((acc, cur, index) => {
      if (index > 1) {
        return acc + '-' + cur
      } else if (index === 1) {
        return acc + '/' + cur
      }
      return acc + cur
    }, '')
  },
  libraryName: '@material-ui/icons',
  style: false,
  camel2DashComponentName: false,
})

element-ui

import { Button } from 'element-ui'
transformerFactory({
  libraryName: 'element-ui',
  libraryDirectory: 'lib',
  camel2DashComponentName: true,
  style: (path: string) => join('element-ui', 'lib', 'theme-chalk', `${camel2Dash(basename(path, '.js'))}.css`),
})

RxJS

see rxjs-webpack-treeshaking-example for more details

only compatible for 5.5+

  • RxJS v5:
transformerFactory({
  libraryDirectory: '../_esm2015/operators',
  libraryName: 'rxjs/operators',
  style: false,
  camel2DashComponentName: false,
  transformToDefaultImport: false,
})
  • RxJS v6:
transformerFactory([
  {
    libraryDirectory: '../_esm5/internal/operators',
    libraryName: 'rxjs/operators',
    camel2DashComponentName: false,
    transformToDefaultImport: false,
  },
  {
    libraryDirectory: '../_esm5/internal/observable',
    libraryName: 'rxjs',
    camel2DashComponentName: false,
    transformToDefaultImport: false,
  },
])

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

More Repositories

1

canvas

High performance skia binding to Node.js. Zero system dependencies and pure npm packages without any postinstall scripts nor node-gyp.
Rust
1,635
star
2

learning-rxjs

Learning RxJS step by step
TypeScript
449
star
3

Image

Image processing library.
Rust
251
star
4

simple-git

Simple and fast git helper functions.
Rust
136
star
5

snappy

Fastest Snappy compression library in Node.js
Rust
119
star
6

uuid

Fastest RFC4122 UUIDs generator for Node.js
JavaScript
91
star
7

Clipboard

Manipulate Clipboard in Node.js via native API.
Rust
73
star
8

jsc-rs

JavaScript core Rust safe binding
Rust
67
star
9

redux-epics-decorator

Dumb decorators for redux & redux-observable & react-redux & redux-actions
TypeScript
59
star
10

blake-hash

Rust Blake hash bindings for Node.js.
Rust
36
star
11

sourcemap-decoder

https://github.com/getsentry/rust-sourcemap node bindings
Rust
33
star
12

woff-build

TTF to WOFF2
Rust
30
star
13

rust-to-nodejs-overhead-benchmark

Benchmark over Node.js binding frameworks in Rust
Rust
25
star
14

vercel-canvas

Sample Canvas App running on Vercel
HTML
23
star
15

ssh

https://github.com/warp-tech/russh Node.js binding
Rust
20
star
16

hns

Node.js http server framework powered by Hyper native binding.
TypeScript
19
star
17

sysinfo

System information
Rust
19
star
18

svg-to-pdf

Convert SVG to PDF
Rust
17
star
19

notify

https://github.com/notify-rs/notify Node.js binding via https://napi.rs
Rust
16
star
20

keyring-node

https://github.com/hwchen/keyring-rs Node.js binding via https://napi.rs. Including 100% compatible node-keytar alternative.
Rust
15
star
21

rxjs-webpack-treeshaking-example

Example for treeshaking
JavaScript
13
star
22

typescript-monorepo

Template project for typescript monorepo
JavaScript
12
star
23

lzma

https://docs.rs/lzma-rs binding to Node.js via https://napi.rs
Rust
10
star
24

wechat-api

JavaScript
9
star
25

ada-url

https://github.com/ada-url/ada Rust and Node.js binding
C++
9
star
26

Learning-Rx

在实践中学习 Rx
9
star
27

rxjs-in-react-demo

RxJS 在 React 中的应用示例项目
TypeScript
8
star
28

html-parser

Parse html string to AST.
JavaScript
8
star
29

crypto-wasm

rust-crypto wasm build
JavaScript
8
star
30

dog

Watch dog for Node.js development
Rust
8
star
31

vuex-rx

RxJS Plugins for vuex
TypeScript
7
star
32

wx-fetch

微信小应用的 fetch polyfill
JavaScript
7
star
33

datafusion-node

Apache DataFusion Node.js binding
Rust
6
star
34

WechatBot

TypeScript
5
star
35

summer-page

JavaScript
5
star
36

node-ed25519

JavaScript
5
star
37

pnpm-duplicate-packages

Reproduction for duplicate packages bundled in pnpm project
JavaScript
5
star
38

node-threadsafe-function-loom

Play the Loom
Rust
4
star
39

Build-Promise

Build your own Promise
TypeScript
4
star
40

puppeteer-screencast-to-video

Puppeteer screencast frames to video
Rust
4
star
41

resume

Resume
TypeScript
4
star
42

Rust-OSS

Aliyun OSS utils
3
star
43

xcx-fucker

3
star
44

dart-rs

Dart rust binding library
Rust
3
star
45

blog

blog
TypeScript
3
star
46

css-minify-comparation

JavaScript
3
star
47

napi-rs-cli-testing

Testing package for @napi-rs/cli
JavaScript
2
star
48

zig-linker-issue

JavaScript
2
star
49

wechat-dingding-cryptor

Wechat/ Dingding cryptor
JavaScript
1
star
50

TypeScript-Webworker-Plugin

Generate webworker codes
1
star
51

next.js-remix-benchmark

TypeScript
1
star
52

ts-import-plugin-example

ts-import-plugin example project with create-react-app
JavaScript
1
star
53

node-crypto

rust-crypto bindings to nodejs
Rust
1
star
54

Cassanova

Teambition & Gitlab & Jenkins Webhook Bridge
TypeScript
1
star
55

Appelsin-Scroll

A cross browers custom scroll bar
JavaScript
1
star
56

frontend-mesh

Connect, control, and observe frontend services. Inspired by Istio.
1
star
57

Learning-FSharp

1
star
58

yarn-bug

1
star
59

node-ref-object-leak

JavaScript
1
star
60

angular_with_typescript

JavaScript
1
star
61

nestjs-vercel

1
star
62

traceurs

Fetch your data, eagerly.
TypeScript
1
star
63

vue-worker-rendering

Rendering HTML in service worker
JavaScript
1
star
64

nodejs-worker-thread-constructor-attribute-issue

C++
1
star
65

typescript-example-projects

JavaScript
1
star
66

nft-pnpm

@vercel/nft with pnpm
JavaScript
1
star
67

intelligent-link

Generate universal link or urlschema or App download url
1
star