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

javascript - Typescript การนำเข้า index.ts ไม่ใช่โมดูล


ฉันพยายามที่จะนำเข้าไฟล์ index.ts ในโฟลเดอร์ย่อยซึ่งมีการนำเข้าอื่น ๆ แต่ฉันยังคงได้รับข้อผิดพลาดของ TypeScript

รีโพเต็ม: https://github.com/Shavindra/webpack-react-sw

(5,32): error TS2306: File 'C:/../src/reducers/index.ts' is not a module.

ฉันไม่แน่ใจว่าฉันทำอะไรผิดที่นี่ ฉันกำลังใช้ TS 2.4.1 ฉันได้ลองรีสตาร์ทคอมพิวเตอร์/VSCode แล้ว แต่ดูเหมือนว่าจะไม่ช่วยอะไร :-|

// ./src/reducers/counter.reducer.ts    
export const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};


// ./src/reducers/index.ts
export * from './counter.reducer';


// ./src/app.ts
import * as React from 'react';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Counter } from './components/counter/counter.component';
import { counterReducer } from './reducers';


const store = createStore(counterReducer);
const rootEl = document.getElementById('root');

const render = () => ReactDOM.render(
    <Counter
        value={store.getState()}
        onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
        onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
    />,
    rootEl
);

render();
store.subscribe(render);

// tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "jsx":"react",
    "lib": [
      "webworker",
      "es6",
      "scripthost",
      "dom"
    ]
  },
  "files": [ "node_modules/@types/react-dom/index.d.ts", "node_modules/@types/react/index.d.ts", "typings/file-loader.d.ts"  ],
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}

คำตอบ #1

แนวคิดบางอย่าง ได้แก่:

  • reducers เป็นโฟลเดอร์และ tsc กำลังพยายามค้นหา ./reducers/index.ts
  • reducers เป็นไฟล์และไม่สามารถอ่านได้โดย tsc
  • recuders เป็นไฟล์ที่ถูกต้องแต่มีระบบการส่งออกที่แตกต่าง ตรวจสอบ UMD, systemjs, commonjs รวมอยู่ด้วย

คุณสามารถรวมพวกมันได้ผ่าน: import counterReducer=require('./recuders'); import * as counterReducer from './recuders';

ถ้าคุณต้องการรวมโมดูลเพียงตัวเดียวผ่าน import { mod } from 'file'; ตรวจสอบให้แน่ใจว่าคุณได้ส่งออกฟังก์ชัน คลาส หรืออะไรก็ตามที่คุณต้องการใน reducers.ts

ฉันหวังว่าความคิดเหล่านี้จะช่วยได้ บอกฉันนะ!

คุณช่วยโพสต์ไฟล์ tsconfig.json ของคุณได้ไหมเพื่อให้แน่ใจว่าทุกอย่างถูกตั้งค่าอย่างถูกต้อง?

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