我尝试从 NPM 包导入类 main.js
import { Organization, Club } from "sqorz-client";
o = new Organization();
o.setId("id");
c = new Club();
c.setId("anotherid");
我收到此错误:
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 \
我的 NPM 包包含一些类,对于每个类我使用导出类... 在 index.js 中,我导入所有类,并使用模块导出。
类中的代码没问题,我的单元测试(玩笑)没问题,但如果我将其导入到其他项目中,它就不起作用。
我的包裹中的代码:
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(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",
[...]
}
我尝试
使用导入时,您应该确保已将项目设置为模块。
在您的消费应用程序中,确保您的 package.json 中有以下内容:
{
...
"type": "module",
...
}