Martin Nordström
Martin Nordström

Reputation: 6025

Adding Typescript to existing React, Webpack and Babel project

I'm trying to add Typescript to a current React, Webpack and Babel project. I'd like to be able to have support for filetypes such as, [.js, .ts, .tsx] in my project since I want to successively migrate to Typescript.

I've made some progress, but currently, I can't solve this error:

enter image description here

I'm also not 100% certain if I need to keep Babel, or if I can remove it after this setup is completed.

My tsconfig.json looks like this:

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es6", "dom", "esnext.asynciterable", "es2015"],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        // "noEmit": true,
        "strictNullChecks": true,
        // "noImplicitAny": false,
        "jsx": "preserve"
    },
    "include": ["src"],
    "exclude": ["node_modules", "build", "scripts", "jest"]
}

And my webpack.conf.js is here: https://gist.github.com/Martinnord/981769791c3e5e3a261af459b81f2733

All help is greatly appriciated since I'm pretty stuck.

Thank you!

Upvotes: 2

Views: 2330

Answers (1)

Domenico Ruggiano
Domenico Ruggiano

Reputation: 587

webpack.config.js example:

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/dist/',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      { test: /\.tsx?$/, loader: 'ts-loader' },
    ],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx', '.ts', '.tsx'],
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  devServer: {
    contentBase: path.resolve(__dirname, './dist'),
    hot: true,
  },
}

also, in tsconfig:

{
  ...
  "jsx": "react",
  ...
}

Full article: here

Upvotes: 3

Related Questions