3

我在我的 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"
  ]
}

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

4

1 回答 1

1

我让它与我的配置一起工作,你能试试这些吗:

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

有了这些配置,我就可以对正常的死代码和样式组件进行树摇动(这有点像要开始工作,注意插件设置!)

环境:

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",
于 2019-02-21T10:59:50.720 回答