Webpack 和 babel-loader 不解析 `ts` 和 `tsx` 模块

Webpack and babel-loader not resolving `ts` and `tsx` modules

我在我的项目中尝试实现 Typescript 时遇到了一些问题。

这些是我的配置。

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;

注意: firebase.ts 是导出 firebase app 对象的 .ts 文件。

当我执行 npm start 时,出现以下错误:

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'

同样的配置适用于 JS 个文件。

babel-loader issue 解决了我的问题。

您必须将此添加到您的 webpack.config.js 才能使其解析 tstsx 文件。

webpack.config.js

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

可在此处找到这些“入门”说明:

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