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
Node doesn't accept ES6 imports in .js
files by default.
--experimental-modules
flag. If it's lower -- you'd have to upgrade..mjs
, or....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 require
s.
Node is supporting this but it is still experimental. You need to set up a few things.
--experimental-modules
and set to use it.type
to module
in your package.json
node --experimental-modules localtest.js
// package.json
{
"type": "module"
}
You can read the documentation about this here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With