5

I'm having some trouble when trying to implement Typescript in my project.

  • Using Webpack and Babel to transpile and bundle files
  • Using babel-loader with @babel/preset-typescript
  • Not using tsc

These are my configs.

webpack.dev.js

const config = {
  // (...) BUNCH OF OTHER CONFIG LINES
  module: {
    rules: [
      {
        test: /\.(js|jsx|ts|tsx)$/,               // USE THE babel-loader FOR THESE FILE EXTENSIONS
        include: path.resolve(__dirname, "src"),
        use: ['babel-loader']
      }
    ]
  }
}

module.exports = config;

babel.config.js

module.exports = function (api) {

  let presets = [];
  let plugins = [];

  presets = [                                 // NOTE: PRESET ORDER IS LAST TO FIRST
    [
      "@babel/preset-env", 
        { 
          targets: "> 0.25%, not dead" 
        }
    ],
    "@babel/preset-react",
    "@babel/preset-typescript"
  ];

  plugins = [
    "react-hot-loader/babel",
    "babel-plugin-styled-components"
  ];

  return ({
    presets,
    plugins,
    // overrides
  });
};

index.tsx

import React from "react";
import ReactDOM from "react-dom";
import firebase from './firebase/firebase';
import App from './App';

ReactDOM.render(
  <App
    firebase={firebase}
  />
  ,document.getElementById("root")
);

App.tsx

import React from "react";
import firebase from "firebase/app";

interface App_PROPS{
  firebase: firebase.app.App | null;
};

const App: React.FC<App_PROPS> = () => {
  return(
    <div>App</div>
  )
};

export default App;

NOTE: firebase.ts is a .ts file that exports a firebase app object.

When I do npm start, I'm getting these errors:

ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './App'

ERROR in ./src/index.tsx
Module not found: Error: Can't resolve './firebase/firebase'

This very same config works fine with JS files.

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

1 Answers1

13

This babel-loader issue solved my problem.

You've got to add this to your webpack.config.js in order to make it resolve ts and tsx files.

webpack.config.js

resolve: {
  extensions: ['.ts', '.tsx', '.js', '.json']
}

These "getting started" instructions can be found here:

https://github.com/Microsoft/TypeScript-Babel-Starter#create-a-webpackconfigjs

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336