【问题标题】:Webpack and babel-loader not resolving `ts` and `tsx` modulesWebpack 和 babel-loader 无法解析 `ts` 和 `tsx` 模块
【发布时间】:2020-11-18 22:46:43
【问题描述】:

尝试在我的项目中实现 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;

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 文件。

【问题讨论】:

    标签: reactjs typescript webpack babeljs babel-loader


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 2017-08-04
      • 2016-11-09
      • 2017-11-13
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2020-04-07
      相关资源
      最近更新 更多