Search code examples
typescriptwebpackbabel-loader

webpack - tsx files width babel-loader error


when i use babel-loader to complie my react project, tell me parse failed. this is my webpack.config.js file.

module: {
            rules: [
                {
                    test: /^\.([jt])sx$/,
                    include: path.resolve(__dirname, 'src'),
                    use: [
                        {
                            loader: "babel-loder",
                            options: {
                               "presets": [
                                  ["@babel/preset-env"],
                                  "@babel/preset-react",
                                  ["@babel/preset-typescript"]
                              ]
                            }
                        }
                    ]
                }
            ]
        }

when I run webpack cli, errors like this:

Module parse failed: Unexpected token (3:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to 
process this file. See https://webpack.js.org/concepts#loaders
| import React, {PureComponent} from 'react';
> export interface ILazyImageProps extends React.DetailsHTMLAttributes<HTMLImageElement>

It looks like "export interface" throw the errors.

But use babel cli,it's ok. Who can tell me why?


Solution

  • This configuration should help you:

    webpack.config.js

    module.exports = {
        // Your configuration of entry and output
        module: {
            rules: [
                {
                    test: /\.(j|t)sx?$/,
                    exclude: /node_modules/,
                    use: [
                        {
                            loader: "babel-loader",
                            options: {
                                presets: [
                                    "@babel/env",
                                    "@babel/react",
                                    "@babel/typescript"
                                ]
                            }
                        }
                    ]
                }
            ]
        }
    };