简体   繁体   English

如何在 Node.js 中使用 typescript 模块

[英]How to use typescript modules in Node.js

It can seem banal for you but hopelessly I couldn't use one Typescript module ( device-detector-js ) in my Node.js project.这对你来说似乎很平庸,但我无法在我的 Node.js 项目中使用一个 Typescript 模块( device-detector-js )。

Now, Please know that I searched the web "How to use typescript modules in Node.js", all I find is "Building a Node.js App with TypeScript";现在,请知道我搜索了 web“如何在 Node.js 中使用 typescript 模块”,我发现的只是“使用 TypeScript 构建 Node.js 应用程序”; I think this is different, isn't it?我认为这是不同的,不是吗?

Now, back to my case, installing device-detector-js then putting import DeviceDetector = require("device-detector-js");现在,回到我的例子,安装device-detector-js然后将import DeviceDetector = require("device-detector-js"); yields this error:产生此错误:

SyntaxError: Cannot use import statement outside a module SyntaxError:不能在模块外使用 import 语句

That's not a "TypeScript module", it's an npm package.这不是“TypeScript 模块”,而是 npm package。

If your code is using CommonJS module format, then you can import a package with the syntax const DeviceDetector = require("device-detector-js") .如果您的代码使用 CommonJS 模块格式,那么您可以使用语法const DeviceDetector = require("device-detector-js")导入 package。

If it's using EcmaScript module format (ESM), so not in your case, you can import with import * as DeviceDetector from "device-detector-js" .如果它使用 EcmaScript 模块格式 (ESM),那么在您的情况下,您可以使用import * as DeviceDetector from "device-detector-js"

The syntax you are trying isn't valid in either case.您尝试的语法在这两种情况下都无效。

See here about how to tell Node that your code is using EcmaScript module format, if you wish to do that.如果您希望这样做,请参阅此处了解如何告诉 Node 您的代码正在使用 EcmaScript 模块格式。

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

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