You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何在一个JS文件创建并导出两个类?

在Node.js中创建并导出多个类

没问题,我来给你梳理下Node.js里怎么在单个.js文件创建两个类并正确导出,同时聊聊常见的报错坑点~

Node.js主要支持两种模块系统:CommonJS(传统默认方式)和ES模块(现代标准),两种方式的导出导入语法不一样,我分别给你示例:

方式1:CommonJS 模块(默认)

这是Node.js早期就支持的模块系统,不需要额外配置,直接写.js文件就行:

// user-product.js
// 定义第一个类
class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hey, ${this.name}!`);
  }
}

// 定义第二个类
class Product {
  constructor(id, price) {
    this.id = id;
    this.price = price;
  }

  showPrice() {
    return `价格:¥${this.price.toFixed(2)}`;
  }
}

// 导出两个类:把它们放在一个对象里导出
module.exports = { User, Product };

导入使用:

在另一个文件里用require导入,解构出需要的类:

const { User, Product } = require('./user-product.js');

// 实例化使用
const myUser = new User('张三');
myUser.greet(); // 输出 Hey, 张三!

const myProduct = new Product(1001, 99.9);
console.log(myProduct.showPrice()); // 输出 价格:¥99.90

方式2:ES 模块(现代标准)

如果想用ES6的export/import语法,需要做一点配置:

  • 要么把文件后缀改成.mjs
  • 要么在项目根目录的package.json里添加 "type": "module"

示例代码:

// user-product.mjs 或者 package.json设了"type": "module"的.js文件
// 定义类
class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hey, ${this.name}!`);
  }
}

class Product {
  constructor(id, price) {
    this.id = id;
    this.price = price;
  }

  showPrice() {
    return `价格:¥${this.price.toFixed(2)}`;
  }
}

// 导出方式1:批量导出
export { User, Product };

// 导出方式2:定义时直接导出(更简洁)
// export class User { ... }
// export class Product { ... }

导入使用:

用import语法解构导入:

import { User, Product } from './user-product.mjs';

const myUser = new User('李四');
myUser.greet();

const myProduct = new Product(1002, 59.5);
console.log(myProduct.showPrice());

常见报错及解决

1. SyntaxError: Unexpected token 'export'

  • 原因:没启用ES模块,比如用了export但文件是普通.js且没在package.json设置"type": "module"
  • 解决:要么改后缀为.mjs,要么在package.json加"type": "module",要么换成CommonJS的module.exports

2. ReferenceError: User is not defined

  • 原因:导入时类名写错(大小写敏感!),或者导出时没把User放进导出对象里
  • 解决:检查导出的对象是否包含目标类,导入时的名称要和导出完全一致

3. TypeError: require(...) is not a function

  • 原因:混用了模块系统,比如在ES模块里用require,或者在CommonJS里用import
  • 解决:统一模块系统,要么全用CommonJS,要么全用ES模块

如果你有具体的报错信息,可以贴出来,我再帮你精准排查~

内容的提问来源于stack exchange,提问作者salihgungor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:12:30