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

cbd*_*per 5 typescript reactjs webpack babeljs babel-loader

我在尝试在项目中实现 Typescript 时遇到了一些麻烦。

  • 使用 Webpack 和 Babel 转译和捆绑文件
  • babel-loader与使用@babel/preset-typescript
  • 不使用tsc

这些是我的配置。

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;
Run Code Online (Sandbox Code Playgroud)

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
  });
};
Run Code Online (Sandbox Code Playgroud)

索引.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")
);

Run Code Online (Sandbox Code Playgroud)

应用程序.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;
Run Code Online (Sandbox Code Playgroud)

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

当我这样做时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'
Run Code Online (Sandbox Code Playgroud)

这个完全相同的配置可以很好地处理JS文件。

cbd*_*per 13

这个babel-loader 问题解决了我的问题。

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

webpack.config.js

resolve: {
  extensions: ['.ts', '.tsx', '.js', '.json']
}
Run Code Online (Sandbox Code Playgroud)

这些“入门”说明可以在这里找到:

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