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

如何在Node.js中用ES6模块语法导入mathjs并使用math命名空间调用方法?

问题

我能成功运行以下代码导入mathjs的指定方法:

import { zeros } from "mathjs";
const w = zeros(5, 5);

但我希望通过math.zeros(5,5)这种命名空间的方式调用方法,这样可以借助math命名空间访问更多方法,比如math.matrix()、math.square(array)等。

当我尝试以下代码时:

import { math } from "mathjs";
const w = math.zeros(5, 5);

出现错误:

SyntaxError: The requested module 'mathjs' does not provide an export named 'math'

我的package.json配置如下:

{
  . . .
  "type": "module",
  . . .
  "dependencies": {
    "mathjs": "^11.5.1"
  }
}

解决方案

要通过math命名空间访问mathjs的所有方法,你需要导入整个模块,而不是尝试解构导入不存在的math具名导出。有两种正确的导入方式:

方式1:默认导入整个模块

import math from "mathjs";
const w = math.zeros(5, 5);
// 同时可调用其他方法
const mat = math.matrix([[1,2],[3,4]]);
const squared = math.square([2,3]);

方式2:命名空间导入所有导出

import * as math from "mathjs";
const w = math.zeros(5, 5);

原因是mathjs并未提供名为math的具名导出,而是将整个库作为默认导出,或者支持通过import * as语法把所有导出内容聚合到math命名空间下。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:50:25