coinhndp
coinhndp

Reputation: 2481

Treeshaking webpack 4 does not apply due to @babel/preset-typescript

I use typescript and babel 7 in my react project (I remove tsloader beacause of babel 7 is now support TS)

"@babel/preset-typescript": "^7.1.0",

The problem is that treeshaking does not working when I use this preset. My babel config

{
  "presets": [
    ["@babel/preset-env", {"modules": false}],
    "@babel/preset-react",
    "@babel/typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    "react-hot-loader/babel"
  ]
}

Anybody knows how to fix it and why? Thank you very much

Upvotes: 3

Views: 1533

Answers (1)

Maciej
Maciej

Reputation: 93

I got it working with my configuration, can you try those:

tsconfig.json:

{
"compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "target": "esnext",
    "moduleResolution": "node",
    "jsx": "react",
    "pretty": true,
    "noEmit": true,
    "strict": true,
    "isolatedModules": true,
    "esModuleInterop": true
},
"include": ["./src/**/*"]

}

.babelrc

{
"presets": [
    "@babel/react",
    "@babel/typescript",
    [
        "@babel/env",
        { 
            "modules": false,
            "targets": { "browsers": "last 2 versions" }
        }
    ]
],
"plugins": [
    [
        "babel-plugin-styled-components", 
        {
            "pure": true
        }
    ],
    "@babel/proposal-class-properties",
    "@babel/proposal-object-rest-spread"
]

}

and webpack.config.js:

rules: [
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            cacheDirectory: true,
                        },
                    }
                ]
            },
        ],

With that configs I'm able to tree shake both normal dead code as well as styled-components (that was a bit of a paint to get working, note plugin settings!)

Env:

node 8.10
"webpack": "^4.28.4",
"typescript": "^3.3.3",
"babel-loader": "^8.0.5",
"babel-plugin-styled-components": "^1.10.0",
"@babel/core": "^7.2.2",
"@babel/plugin-proposal-class-properties": "^7.3.0",
"@babel/polyfill": "^7.2.5",
"@babel/preset-env": "^7.2.3",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.1.0",

Upvotes: 1

Related Questions