简体   繁体   English

如何将 js 模块导入 TypeScript 文件?

[英]How to import js-modules into TypeScript file?

I have a Protractor project which contains such a file:我有一个 Protractor 项目,其中包含这样一个文件:

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;

Path to the file is ./pages/FriendCard.js .该文件的路径是./pages/FriendCard.js

I have no problems with its import to another file using require() :使用require()将其导入另一个文件没有问题:

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

So, I've decided to import this file to the TypeScript file just like that:所以,我决定像这样将此文件导入 TypeScript 文件:

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

I'm using WebStorm.我正在使用 WebStorm。 It tells me that ( TS2305 ) it has no exported member 'FriendCard'.它告诉我 ( TS2305 ) 它没有导出成员“FriendCard”。

Maybe I have to configure tsconfig.json file somehow, but I still don't know how it works.也许我必须以某种方式配置 tsconfig.json 文件,但我仍然不知道它是如何工作的。 Could you help me?你可以帮帮我吗?

You can import the whole module as follows:您可以按如下方式导入整个模块:

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

For more details please refer the modules section of Typescript official docs.有关更多详细信息,请参阅 Typescript 官方文档的模块部分。

Recent Updated Solution : We need to tweak the tsconfig.json to allow JS modules import.最近更新的解决方案:我们需要调整tsconfig.json以允许 JS 模块导入。 credits to @paulmest, @ben-winding @crispen-gari solutions below.归功于@paulmest、@ben-winding @crispen-gari 解决方案。

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

I'm currently taking some legacy codebases and introducing minimal TypeScript changes to see if it helps our team.我目前正在使用一些遗留代码库并引入最少的 TypeScript 更改,以查看它是否对我们的团队有所帮助。 Depending on how strict you want to be with TypeScript, this may or may not be an option for you.根据您希望使用 TypeScript 的严格程度,这可能是也可能不是您的选择。

The most helpful way for us to get started was to extend our tsconfig.json file with this property:对我们来说最有用的入门方法是使用以下属性扩展我们的tsconfig.json文件:

// tsconfig.json excerpt:

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

This change lets our JS files that have JSDoc type hints get compiled.此更改允许编译具有 JSDoc 类型提示的 JS 文件。 Also our IDEs (JetBrains IDEs and VS Code) can provide code-completion and Intellisense.此外,我们的 IDE(JetBrains IDE 和 VS Code)可以提供代码完成和智能感知。

References:参考:

In your second statement在你的第二个陈述中

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

you are telling typescript to import the FriendCard class from the file './pages/FriendCard'您告诉打字稿从文件“./pages/FriendCard”中导入 FriendCard

Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.您的 FriendCard 文件正在导出一个变量,该变量正在引用匿名函数。

You have two options here.您在这里有两个选择。 If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file.如果您想以类型化的方式执行此操作,您可以重构要输入的模块(选项 1),或者您可以导入匿名函数并添加一个 d.ts 文件。 See https://github.com/Microsoft/TypeScript/issues/3019 for more details.有关更多详细信息,请参阅https://github.com/Microsoft/TypeScript/issues/3019 about why you need to add the file.关于为什么需要添加文件。

Option 1选项1

Refactor the Friend card js file to be typed.重构要输入的好友卡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();
}
};

Option 2选项 2

You can import the anonymous function您可以导入匿名函数

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

There are a few options for a d.ts file definition. d.ts 文件定义有几个选项。 This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?这个答案似乎是最完整的: How do you generate a .d.ts "typings" definition file from an existing JavaScript library?

2021 Solution 2021 解决方案

If you're still getting this error message:如果您仍然收到此错误消息:

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

Then you might need to add the following to tsconfig.json然后您可能需要将以下内容添加到tsconfig.json

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

This prevents typescript from trying to apply module types to the imported javascript.这可以防止 typescript 尝试将模块类型应用于导入的 javascript。

I tested 3 methods to do that...我测试了 3 种方法来做到这一点......

Method1:方法一:

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

Method2:方法二:

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

Method3:方法三:

if you can find something like this in tsconfig.json:如果你能在 tsconfig.json 中找到这样的东西:

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

then you can write: import FriendCard from './../pages/FriendCard';然后你可以写: import FriendCard from './../pages/FriendCard';

I've been facing this problem for long but what this solves my problem Go inside the tsconfig.json and add the following under compilerOptions我一直面临这个问题,但这解决了我的问题进入tsconfig.json并在compilerOptions下添加以下内容

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

The answers about adding allowJs: true to your tsconfig.json worked for me, but I also had to make sure the includes: [] block within the tsconfig.json included Javascript files.关于添加allowJs: true到你的tsconfig.json的答案对我有用,但我还必须确保includes: []块在tsconfig.json包含 Javascript 文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM