Javascript 将 JS 文件导入 Typescript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33525027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:11:21  来源:igfitidea点击:

Importing JS File into Typescript

javascripttypescript

提问by Nick White

I'm looking at moving over to Typescript and currently looking at doing this slowly if possible file by file.

我正在考虑转移到 Typescript,目前正在考虑在可能的情况下逐个文件地缓慢执行此操作。

Now the system I currently have is built with Webpack and I'm wanting to continue this for building my overall bundle.

现在我目前拥有的系统是用 Webpack 构建的,我想继续使用它来构建我的整个包。

I have a .d.ts file for the definition but I need my file to continue importing which currently is throwing an error.

我有一个用于定义的 .d.ts 文件,但我需要我的文件继续导入,但当前正在抛出错误。

/// <reference path="../../../../vendor/src/foo.d.ts" />
import foo = require('../../../../vendor/src/foo.js');

foo('something');

This currently is throwing errors I have also tried without the reference path and this seems to raise an error that it is not a module. Currently the only way I can have no errors raised is not importing and simply adding the reference but this will mean that webpack will not know the location of my file.

这目前正在抛出错误,我也在没有参考路径的情况下尝试过,这似乎引发了一个错误,即它不是模块。目前,我不会出现错误的唯一方法是不导入并简单地添加引用,但这意味着 webpack 将不知道我的文件的位置。

Any ideas I have searched quite a lot but I can't really make sense of importing JS files into Typescript.

我已经搜索了很多想法,但我真的无法将 JS 文件导入 Typescript。

回答by basarat

Any ideas I have searched quite a lot but I can't really make sense of importing JS files into Typescript.

我已经搜索了很多想法,但我真的无法将 JS 文件导入 Typescript。

For webpack all you need is to declarethe requirefunction and do what you are already used to:

对于所有的WebPack你需要的是declarerequire功能和做什么,你已经习惯了:

var foo = require('../../../../vendor/src/foo');

The requirefunction type definition is present here : https://github.com/TypeStrong/ts-loader#loading-other-resources-and-code-splitting

require功能类型定义为在座的:https://github.com/TypeStrong/ts-loader#loading-other-resources-and-code-splitting

If you want to use fooin a stronger manner... recommend porting it over to .tsas well instead of struggling to buildand then maintaina .d.tsfile for it.

如果你想以foo更强大的方式使用......建议将它移植到.ts以及而不是努力构建然后维护.d.ts它的文件。

回答by Martin Vseticka

What about simply rename foo.jsto foo.ts(it may require some additional stepsbut often it works fine) and then rewrite your snippet to:

简单地重命名foo.jsfoo.ts(它可能需要一些额外的步骤,但通常可以正常工作)然后将您的代码段重写为:

 /// <reference path="../../../../vendor/src/foo.d.ts" />

 foo('something');