ค้นหาเว็บไซต์

reactjs - Webpack และ babel-loader ไม่สามารถแก้ไขโมดูล `ts` และ `tsx` ได้


ฉันกำลังมีปัญหาเมื่อลองใช้งาน 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 เป็นไฟล์ .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'

การตั้งค่าระบบเดียวกันนี้ทำงานได้ดีสำหรับไฟล์ JS

คำตอบ #1

ปัญหา babel-loader นี้แก้ไขปัญหาของฉันได้

คุณต้องเพิ่มสิ่งนี้ลงใน webpack.config.js ของคุณเพื่อให้มันสามารถแก้ไขไฟล์ ts และ tsx ได้

webpack.config.js

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

คำแนะนำ "เริ่มต้นใช้งาน" เหล่านี้สามารถพบได้ที่นี่:

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

บทความที่เกี่ยวข้อง