6

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

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • That isn't even legal ES 6: imports and exports have to be top-level statements. You can't do it inside of a function. Why does it have to be ES 6 modules anyways? – Jared Smith Jan 28 '20 at 14:21

2 Answers2

3

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:


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

hasparus
  • 1,164
  • 8
  • 7
2

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.

Michael Warner
  • 3,879
  • 3
  • 21
  • 45