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

标签 babeljs webpack-4 tree-shaking

我在我的 React 项目中使用了 typescript 和 babel 7(我删除了 tsloader 因为 babel 7 现在支持 TS)

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

问题是当我使用这个预设时,treeshaking 不起作用。我的 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"
  ]
}

有人知道如何修复它以及为什么吗?非常感谢

最佳答案

我用我的配置让它工作,你能试试那些吗:

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,
                        },
                    }
                ]
            },
        ],

有了这些配置,我能够对正常的死代码和样式化组件进行 tree shake(这需要一些技巧才能开始工作,请注意插件设置!)

环境:

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

关于babeljs - 由于@babel/preset-typescript,Treeshaking webpack 4 不适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53865304/

相关文章:

gulp - 如何获取 gulp+babel+browserify+uglify 的源映射

webpack - 如何修复 import/no-unresolved eslint 以查看 package.json "module"而不是 "main"

javascript - 在 webpack 中更好的 TreeShaking 的正确方法是什么?

reactjs - 如何在 create-react-app 项目中为 lodash 执行 Tree Shaking?

webpack - 如果以最少的输出以监视模式运行,如何将当前时间戳添加到 webpack4 中的输出

reactjs - 如何确认 Tree Shaking 是否适用于 Webpack 2?

javascript - 未捕获的不变违规 : Target container is not a DOM element

ReactJS - Babel 版本问题

javascript - 旧网站上的 Gulp 到 Webpack 迁移 - 从非 npm 依赖项生成 vendor

javascript - Webpack 4 拆分块术语