'import ... ='只能在TypeScript文件中使用

编程入门 行业动态 更新时间:2024-10-04 09:31:01

'import ... ='只能在TypeScript<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件中使用"/>

'import ... ='只能在TypeScript文件中使用

错误:-
'import ... =' 只能在 TypeScript 文件中使用。
'=' 预期。
';'预期。
意外的关键字或标识符。

package.json
“类型”:“模块”

代码--

Index.cjs

import msg as msg from "./tm.js"
// module imprted
// function called with integers for their sum
console.log(tm.msg(5,6))
// expected output-
// Function Imported
// 11

模块文件--
tm.js

exports.msg = function (a,b) {
    console.log("Function Imported")
    return a+b;
}

在使用 Node.js 时,我遇到了这个错误。
所以,我希望任何人都可以帮助我。

我尝试了很多东西并研究了这个错误。
最后我得到了解决方案和发生此错误的不同原因。
所以,我在下面分享了我的答案,希望对您有所帮助!

回答如下:

这种类型的错误可能是由不同类型的错误引起的。
确保在使用 import 语句时,您的文件类型必须是模块。
这可以通过使用 '.mjs' 扩展名来实现,比如 tm.mjs OR
通过在 package.json 中使用 "type": "module"
对于模块文件,使用“.cjs”扩展名
首先使用类型模块创建文件 Index.js 或将其创建为 Index.mjs

答案 1-
从“./tm.js”导入味精作为味精
Ans.- 愚蠢的错误
使用它来摆脱大部分错误-

import * as tm from "./tm.cjs"
console.log(tm.msg(5,6))

Ans.2-

import {msg} from "./tm.cjs"
console.log(msg(5,6))

如果你正在使用 VS Code 那么
您可以安装“流语言支持”以方便工作。

更多推荐

'import ... ='只能在TypeScript文件中使用

本文发布于:2024-05-30 22:16:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   只能在   import   TypeScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!