When attempting to import classes from my NPM package in main.js, I encountered an issue.
import { Organization, Club } from "sqorz-client";
o = new Organization();
o.setId("id");
c = new Club();
c.setId("anotherid");
The error message it returned was :
import { Organization } from "sqorz-client";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1175:20)
at Module.\_compile (node:internal/modules/cjs/loader:1219:27)
at Module.\_extensions..js (node:internal/modules/cjs/loader:1309:10)
at Module.load (node:internal/modules/cjs/loader:1113:32)
at Module.\_load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint \[as runMain\] (node:internal/modules/run_main:83:12)
at node:internal/main/run_main_module:23:47 \
My NPM package contains various classes which are exported using export class syntax...
This code within the classes is correct, as confirmed by successful unit tests with Jest. However, when attempting to import these classes into another project, it does not function as expected.
Sample code from my package :
index.js
import { Organization } from "./src/types/organization";
import { Club } from "./src/types/club";
import { SqorzClient } from "./src/SqorzClient";
import { Event } from "./src/types/event";
import { Pilot } from "./src/types/pilot";
import { Race } from "./src/types/race";
import { SqorzRequest } from "./src/services/sqorzRequest";
module.exports = { Organization, Club, SqorzClient, Event, Pilot, Race, SqorzRequest };
src/types/organization.js ( compiled by tsc )
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Organization = void 0;
class Organization {
getId() {
return this._id;
}
setId(id) {
this._id = id;
return this;
}
getName() {
return this._name;
}
setName(name) {
this._name = name;
return this;
}
getCode() {
return this._code;
}
setCode(code) {
this._code = code;
return this;
}
}
exports.Organization = Organization;
package.json
{
"name": "sqorz-client",
[...]
"files": [
"src"
],
"main": "index.js",
[...]
}
I have tried various solutions like:
- using module.exports = class in Organization.js,
- changing the main file,
- adjusting the source file list,
- and more...