[英]Use Javscript libraries in typescript?
Im quite new to typescript, so I´m sorry if the question is pretty easy.我对打字稿很陌生,所以如果问题很简单,我很抱歉。 I want to use JS libraries in a .ts file.
我想在.ts文件中使用 JS 库。 Also, I´m using node.js to run my program in my console.
此外,我正在使用 node.js 在我的控制台中运行我的程序。
In Javascript I used the following line of code:在 Javascript 中,我使用了以下代码行:
const example = require('lodash'); // example
After that, I typed the following command in my terminal:之后,我在终端中输入以下命令:
npm i loadsh
Now I have an example.ts file, where I want to use the exact same library.现在我有一个example.ts文件,我想在其中使用完全相同的库。 Could anyone provide me with an example, of how to do that ?
谁能给我一个例子,说明如何做到这一点? Thanks a lot
非常感谢
Look at this article - https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3看看这篇文章 - https://medium.com/@steveruiz/using-a-javascript-library-without-type-declarations-in-a-typescript-project-3643490015f3
Please before asking a question, do a bit of search yourself请在提问之前,先自己搜索一下
You will need a TSConfig file, https://www.typescriptlang.org/tsconfig您将需要一个 TSConfig 文件, https ://www.typescriptlang.org/tsconfig
You can create one with npx tsc --init
您可以使用
npx tsc --init
创建一个
If you want to run the code without building it consider using ts-node
instead of node
如果您想在不构建的情况下运行代码,请考虑使用
ts-node
而不是node
You can then do your imports in a tsx file with import {map} from lodash;
然后,您可以使用
import {map} from lodash;
在 tsx 文件中进行import {map} from lodash;
Be sure to have "allowJs": true
in your tsconfig.确保在您的 tsconfig 中有
"allowJs": true
。
Most of npm libraries, including lodash, have typescript definitions provided by developers team.大多数 npm 库,包括 lodash,都有开发团队提供的打字稿定义。 Types for javascript libraries come as separate package, so you need to install it too.
javascript 库的类型作为单独的包提供,因此您也需要安装它。
npm i -D @types/lodash
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.