Trying the simplest import in Node, but am not being able to get it to work.... (Added "name": "Foo", per suggestions on web.)
package.json
{
"type": "module",
"name": "Foo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC",
}
index.ts
import foo from './foo';
foo();
foo.ts
export default function foo() {
console.log("FOO");
}
result
import foo from './foo';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1072:16)
at Module._compile (internal/modules/cjs/loader.js:1122:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
CodePudding user response:
And you should insert the code in the package.json.
package.json:
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "module"
}
index.js:
import foo from "./foo.js";
foo();
CodePudding user response:
remove the line type: "module" from the package.json and see if that helps. That is because that line activates ES6 Modules for Node.js and you are trying to use commonJS modules, which don't play nicely together.
CodePudding user response:
Nice to meet you. I have solved your problem. You should change your code like the below code.
index.ts:
const foo = require('./foo')
foo.print();
foo.js:
function print() {
console.log('foo')
}
module.exports = { print }
