由于@ babel / preset-typescript,Treeshaking Webpack 4不适用

时间:2018-12-20 08:56:49

标签: babel webpack-4 tree-shaking

我在我的react项目中使用了打字稿和babel 7(因为babel 7现在支持TS,我删除了tsloader)

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

问题是,当我使用此预设时,无法进行树状摇动。我的babel配置

{
  "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"
  ]
}

任何人都知道如何解决它,为什么?非常感谢

1 个答案:

答案 0 :(得分:0)

我可以在配置中使用它,您可以尝试以下方法吗:

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"
]

}

和webpack.config.js:

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

有了这些配置,我就可以摇晃普通的死代码以及样式化的组件(要工作,需要一点油漆,注意插件设置!)

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",