Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run esnext file from terminal

I am kinda new typescript and I wrote an SDK, My .tsconfig looks kinda like this

{
  "compilerOptions": {
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "module": "esnext",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "sourceMap": true,
    "strict": true,
    "target": "es2015",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noImplicitAny": false,
    "outDir": "./lib",
  },
  "compileOnSave": true,
  "include": [
    "src"
  ],
  "exclude": ["node_modules"]
}

I build this using tsc command. Now I created localtest.js file where I am importing this

import getWorkspace from './lib/index'

const randomFunc = async () => {
   // some code 
}
randomFunc()

and then running it with following command in my terminal node localtest.js which is throwing following error

function (exports, require, module, __filename, __dirname) { import getWorkspace from './lib/index'
                                                                     ^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)
    at Object.runInThisContext (vm.js:326:10)
    at Module._compile (internal/modules/cjs/loader.js:664:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
    at startup (internal/bootstrap/node.js:283:19)

Any idea on how I can fix it and why I am getting the above error

like image 831
anny123 Avatar asked Jan 23 '20 12:01

anny123


2 Answers

Node doesn't accept ES6 imports in .js files by default.

  • On Node 12, add --experimental-modules flag. If it's lower -- you'd have to upgrade.
  • Either change the extension to .mjs, or...
  • to use ESModules in .js files (like the ones emitted by TS), add "type": "module" to the nearest package.json.

More info:

  • https://nodejs.org/dist/latest-v12.x/docs/api/esm.html#esm_enabling
  • https://stackoverflow.com/a/45854500/6003547

Alternatively, you can change "module" compiler option to "commonjs" to emit requires.

like image 150
hasparus Avatar answered Oct 16 '22 12:10

hasparus


Node is supporting this but it is still experimental. You need to set up a few things.

  1. You need Node.js version 12+
  2. You need a flag --experimental-modules and set to use it.
  3. Change type to module in your package.json
node --experimental-modules localtest.js
// package.json
{
  "type": "module"
}

You can read the documentation about this here.

like image 35
Michael Warner Avatar answered Oct 16 '22 12:10

Michael Warner