Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

esbuild does not tree shake implicit type import #1092

Closed
hardfist opened this issue Mar 31, 2021 · 3 comments
Closed

esbuild does not tree shake implicit type import #1092

hardfist opened this issue Mar 31, 2021 · 3 comments

Comments

@hardfist
Copy link
Contributor

It seems that esbuild shake the explicit import type { Draft} from 'immer' , but does not shake import { Draft } from 'immer' even though Draft is type only and I configure "importsNotUsedAsValues": "remove" in tsconfig.json. you can see the problem here reduxjs/redux-toolkit#957 (comment)

@evanw
Copy link
Owner

evanw commented Mar 31, 2021

When bundling is disabled, TypeScript files are compiled one-at-a-time so it's not possible to determine whether this is a type or not. You need to enable "isolatedModules": true in your tsconfig.json file: https://esbuild.github.io/content-types/#isolated-modules.

This is the case regardless of whether you use esbuild, Babel, or TypeScript's own compiler API:

const ts = require('typescript')
const es = require('esbuild')
const bc = require('@babel/core')

const code = `
  export { Draft } from 'immer'
  import { someType, someValue } from 'example'
  var someVar: someType = someValue
`

console.log('// TypeScript:\n' + ts.transpileModule(code, {
  compilerOptions: {
    module: ts.ModuleKind.ESNext,
    importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove,
  }
}).outputText)

console.log('// esbuild:\n' + es.transformSync(code, {
  loader: 'tsx',
  tsconfigRaw: `{
    "compilerOptions": {
      "importsNotUsedAsValues": "remove",
    },
  }`,
}).code)

console.log('// Babel:\n' + bc.transform(code, {
  plugins: [['@babel/plugin-transform-typescript', {
    onlyRemoveTypeImports: false,
  }]]
}).code)

The code above prints the following:

// TypeScript:
export { Draft } from 'immer';
import { someValue } from 'example';
var someVar = someValue;

// esbuild:
export {Draft} from "immer";
import {someValue} from "example";
var someVar = someValue;

// Babel:
export { Draft } from 'immer';
import { someValue } from 'example';
var someVar = someValue;

@hardfist
Copy link
Contributor Author

but this happens when bundling is enabled

@hardfist
Copy link
Contributor Author

i dont know whether the shake could be done even when immer is external here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants