programing

js-modules를 TypeScript 파일로 Import하는 방법

mytipbox 2023. 3. 9. 21:42
반응형

js-modules를 TypeScript 파일로 Import하는 방법

다음과 같은 파일이 포함된 프로젝터 프로젝트가 있습니다.

var FriendCard = function (card) {
    var webElement = card;
    var menuButton;
    var serialNumber;

    this.getAsWebElement = function () {
        return webElement;
    };

    this.clickMenuButton = function () {
        menuButton.click();
    };

    this.setSerialNumber = function (numberOfElements) {
        serialNumber = numberOfElements + 1;
        menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
    };

    this.deleteFriend = function () {
        element(by.css('[ng-click="deleteFriend(person);"]')).click();
        element(by.css('[ng-click="confirm()"]')).click();
    }
};
module.exports = FriendCard;

파일 경로는 다음과 같습니다../pages/FriendCard.js.

다음을 사용하여 다른 파일로 가져오는 데 문제가 없습니다.require():

var FriendCard = require('./../pages/FriendCard');

그래서 다음과 같이 이 파일을 TypeScript 파일로 Import하기로 했습니다.

import {FriendCard} from './../pages/FriendCard'

WebStorm을 사용하고 있습니다.(TS2305)에 내보낸 회원 'FriendCard'가 없다고 표시됩니다.

tsconfig.json 파일을 어떻게든 설정해야 할 것 같습니다만, 아직 어떻게 동작하고 있는지 모르겠습니다.좀 도와 주시겠습니까?

다음과 같이 모듈 전체를 Import할 수 있습니다.

import * as FriendCard from './../pages/FriendCard';

자세한 내용은 Typescript 공식 문서의 모듈 섹션을 참조하십시오.

최신 업데이트 솔루션 : JS 모듈이 아래의 @paulmest, @ben-winding @crispen-gari 솔루션으로 .credits를 Import할 수 있도록 tsconfig.json을 조정해야 합니다.

{
  "compilerOptions": {
    "allowJs": true
  }
}

현재 레거시 코드베이스를 사용하여 TypeScript의 최소한의 변경을 도입하여 팀에 도움이 되는지 확인하고 있습니다.TypeScript를 얼마나 엄격하게 사용하는지에 따라 이 옵션이 선택될 수도 있고 그렇지 않을 수도 있습니다.

우리가 시작할 수 있는 가장 유용한 방법은 우리의 비즈니스 환경을 확장시키는 것입니다.tsconfig.json다음 속성을 가진 파일:

// tsconfig.json excerpt:

{
  ...
  "compilerOptions": {
    ...
    "allowJs": true,
    ...
  }
  ...
}

이 변경을 통해 JSDoc 유형의 힌트가 있는 JS 파일을 컴파일할 수 있습니다.또, 델의 IDE(JetBrains IDE 및 VS Code)는, 코드 컴플리트와 인텔리센스를 제공합니다.

참고 자료:

2021년 솔루션

이 에러 메세지가 아직 표시되는 경우는,

TS7016: Could not find a declaration file for module './myjsfile'

그 후 다음 항목을 에 추가해야 할 수 있습니다.tsconfig.json

{
  "compilerOptions": {
    ...
    "allowJs": true,
    "checkJs": false,
    ...
  }
}

이를 통해 타이프스크립트가 Import된 Javascript에 모듈타입을 적용하려고 하지 않게 됩니다.

두 번째 진술에서

import {FriendCard} from './../pages/FriendCard'

파일 '.pages/FriendCard'에서 FriendCard 클래스를 가져오도록 타이프스크립트에 지시하고 있습니다.

FriendCard 파일이 변수를 내보내고 있고 해당 변수가 익명 함수를 참조하고 있습니다.

여기에는 두 가지 옵션이 있습니다.이를 입력된 방법으로 수행할 경우 모듈을 입력하도록 리팩터링하거나(옵션 1) 익명 함수를 Import하여 d.ts 파일을 추가할 수 있습니다.파일을 추가해야 하는 이유에 대한 자세한 내용은 https://github.com/Microsoft/TypeScript/issues/3019을 참조하십시오.

옵션 1

입력할 친구 카드 js 파일을 리팩터링합니다.

export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;

constructor(card) {
    this.webElement = card;
    this.menuButton;
    this.serialNumber;
}



getAsWebElement = function () {
    return this.webElement;
};

clickMenuButton = function () {
    this.menuButton.click();
};

setSerialNumber = function (numberOfElements) {
    this.serialNumber = numberOfElements + 1;
    this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};

deleteFriend = function () {
    element(by.css('[ng-click="deleteFriend(person);"]')).click();
    element(by.css('[ng-click="confirm()"]')).click();
}
};

옵션 2

익명 함수를 가져올 수 있습니다.

 import * as FriendCard from module("./FriendCardJs");

d.ts 파일 정의에는 몇 가지 옵션이 있습니다.이 답변이 가장 완벽한 것 같습니다.기존 JavaScript 라이브러리에서 .d.ts "typings" 정의 파일을 작성하려면 어떻게 해야 합니까?

그러기 위해 세 가지 방법을 테스트했습니다.

방법 1:

      const FriendCard:any = require('./../pages/FriendCard')

방법 2:.

      import * as FriendCard from './../pages/FriendCard';

방법 3:

tsconfig.json에서 다음과 같은 것을 찾을 수 있는 경우:

      { "compilerOptions": { ..., "allowJs": true }

이렇게 쓸 수 있어요.import FriendCard from './../pages/FriendCard';

오랫동안 문제에 직면했지만 해결 방법tsconfig.json으로 이동하여 컴파일러 옵션 아래에 다음을 추가합니다.

{
  "compilerOptions": {
      ...
      "allowJs": true
      ...
  }
}

「 」를 추가하는 .allowJs: trueyour tsconfig.json가 있었지만, ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★includes: [] the 내의 tsconfig.json자바스크립트

{
  "compilerOptions": {
      ...
      "include": ["src/**/*.js"]
      ...
  }
}

언급URL : https://stackoverflow.com/questions/41219542/how-to-import-js-modules-into-typescript-file

반응형