I am attempting to initialize a database using TypeScript.
Here is my TypeScript code:
import { User, UserRole } from '../entity/User';
import crypto from 'crypto';
import {dbManager, pwhash } from '..';
async function inituser()
{
const user = new User();
user.email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe8d969b9099d0928bbe938fd09b9a8bd09f8b">[email protected]</a>';
user.own_organization = []
user.salt = crypto.randomBytes(16).toString('hex');
user.password = pwhash("password", user.salt);
user.role = UserRole.admin;
await dbManager.save(user);
const duser = await dbManager.findOne(User);
return duser;
}
const duser = inituser();
console.log("Loaded users: ", duser);
When I try to run the script using ts-node like:
npx ts-node db/initializers/inituser.ts
An error occurs:
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1167:16)
at Module._compile (internal/modules/cjs/loader.js:1215:27)
at Module.m._compile (/usr/lib/node_modules/ts-node/src/index.ts:858:23)
...
To resolve this error, I added "type": "module" in the package.json file.
{
"name": "typescript-test",
"version": "1.0.0",
"type": "module",
...
}
This change was made to address the warning message regarding loading an ES module.
(node:3854) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)