node.js - 在coffeescript中使用es6模块

标签 node.js coffeescript

es6 模块应该可以在 Coffeescript 中工作(请参阅 https://coffeescript.org/#modules ),但即使是一个非常简单的项目,它对我来说也不起作用。我:

  1. 创建了一个新目录

  2. 在其中运行“npm init -y”

  3. 在我的 package.json 中添加了键 "type": "module"

  4. 创建了 2 个文件:index.coffee 和 utils.coffee

    从“utils.coffee”导入 {myprint}
    myprint(“你好,世界!”)

    导出 myprint = (str) ->
    控制台.log(str)

当我尝试执行index.coffee(通过“coffee index.coffee” - 我已经在 Windows 和 PowerShell 上尝试过 git 的 bash shell)时,我收到以下错误消息:

(node:1856) 警告:要加载 ES 模块,请在 package.json 中设置 "type": "module"或使用 .mjs 扩展名。

及以后:

语法错误:无法在模块外部使用 import 语句

最佳答案

据我所知,这都是正确的。 Coffeescript 正确转换导入/导出语句,但不提供运行它们的环境。

来自documentation :

Note that the CoffeeScript compiler does not resolve modules; writing an import or export statement in CoffeeScript will produce an import or export statement in the resulting output. It is your responsibility to transpile this ES2015 syntax into code that will work in your target runtimes.

您将无法通过 coffeenode --require Coffeescript/register 运行此代码。我相信你必须转译你的代码并通过 node

运行生成的 JS

关于node.js - 在coffeescript中使用es6模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67759943/

相关文章:

angularjs - 在 Heroku 上部署 AngularJs + webpack + gulp

node.js - 使用Sequelize原始查询时如何在嵌套数组中获得一对多关联

coffeescript - Coffeescript中switch case语句内的范围

mongodb - 自动增加 meteor 简单模式成员

javascript - 使用 sinon 和 jasmine 测试提交时的表单操作

node.js - 如何使用 NodeJS 以 super 用户身份连接到另一个 MongoDB 数据库?

node.js - 查询条件缺少关键架构元素 : Validation Error

javascript - 允许远程服务器接受来自本地主机的带有参数的请求

javascript - 如何使用 coffeescript 和 ES6 创建 sails.js 项目

node.js:WAITING所有线程完成