Home > Enterprise >  Do I need Babel if I want to support JavaScript in my TypeScript React project? (without CRA)
Do I need Babel if I want to support JavaScript in my TypeScript React project? (without CRA)

Time:11-08

The following code is my webpack config for my React project written in TypeScript,

module.exports = {
  mode: 'development',
  entry: ['./src/main.tsx'],
  module: {
    rules: [
      {
        // Only setup a rule for ts/tsx, but no rule for js/jsx yet.
        test: /\.tsx?$/,
        exclude: /(node_modules|\.webpack)/,
        use: {
          loader: 'ts-loader',
          options: {
            transpileOnly: true,
          },
        },
      },
    ],
  },
  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[name].chunk.js',
  },
  plugins: require('./webpack.plugins'),
  resolve: {
    extensions: ['.js', '.ts', '.json', '.jsx', '.tsx', '.css'],
    alias: {
      'react-dom': '@hot-loader/react-dom',
      ...require('./webpack.aliases'),
    },
  },
}

I have set the rule for ts & tsx extension, yet I haven't setup a js & jsx rule.

I'm wondering do I need to setup Babel config and a rule for js/jsx to load by babel-loader if I want to support both TypeScript & JavaScript in my React project which is not a CRA project?

Or, since I'm already seting up for a TypeScript project, can I just use ts-loader to load my js/jsx extensions?

CodePudding user response:

I just found the TS conversion guide from Microsoft.

In short, they just directly pass js/jsx together with ts/tsx into the ts-loader pipeline since TypeScript also offers transpiling to lower ECMAScript versions and JSX transpilation with a shorter build time in most cases.

module.exports = {
  ...
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"]
  },
  module: {
    rules: [
      { test: /\.(t|j)sx?$/, use: { loader: 'ts-loader' }, exclude: /node_modules/ }, // here
      { enforce: "pre", test: /\.js$/, exclude: /node_modules/, loader: "source-map-loader" }
    ]
  },
  ...
}
  • Related