Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using es6 modules in coffeescript

es6 modules are supposed to work in coffeescript (see https://coffeescript.org/#modules), but even with an extremely simple project, it doesn't work for me. I:

  1. Created a new directory

  2. Ran 'npm init -y' in it

  3. Added the key "type": "module" in my package.json

  4. Created 2 files: index.coffee and utils.coffee

    import {myprint} from 'utils.coffee'
    myprint("Hello, World!")

    export myprint = (str) ->
       console.log(str)

when I try to execute index.coffee (via 'coffee index.coffee' - I've tried both git's bash shell - on Windows and PowerShell), I get the following error message:

(node:1856) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

and later:

SyntaxError: Cannot use import statement outside a module

like image 814
John Deighan Avatar asked Sep 06 '25 22:09

John Deighan


1 Answers

This is all correct as far as I understand. Coffeescript transpiles the import/export statements correctly, but does not provide an environment to run them.

From the 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.

You won't be able to run this code via either coffee or node --require coffeescript/register. I believe you will have to transpile your code and run the resulting JS via node

like image 73
caffeinated.tech Avatar answered Sep 09 '25 14:09

caffeinated.tech