SheetJS:错误:不支持 ES 模块 /node_modules/xlsx/dist/cpexcel.full.mjs 的 require()

SheetJS: Error: require() of ES Module /node_modules/xlsx/dist/cpexcel.full.mjs not supported

提问人:Antonio Pavicevac-Ortiz 提问时间:11/14/2023 更新时间:11/14/2023 访问量:26

问:

我正在使用 NestJS/TypeScript,我的一个服务文件具有以下导入,这些导入是从他们的 (SheetJS) 文档页面获取的。

/* load the codepage support library for extended support with older formats  */
import * as cpexcel from 'xlsx/dist/cpexcel.full.mjs';
import * as XLSX from 'xlsx/xlsx.mjs';

/* load 'fs' for readFile and writeFile support */
import { Injectable } from '@nestjs/common';
import { DSRequestContextService } from '@shared/services/context/context_service';
import { DSLogService } from '@shared/services/log/log.service';

XLSX.set_fs(fs);

XLSX.stream.set_readable(Readable);

XLSX.set_cptable(cpexcel);

但是,我收到以下错误:

[错误] 18:11:27 错误:不支持 ES 模块 /mnt/d/Repos/document-engine/node_modules/xlsx/dist/cpexcel.full.mjs 的 require()。 相反,将 /mnt/d/Repos/document-engine/node_modules/xlsx/dist/cpexcel.full.mjs 的 require 更改为所有 CommonJS 模块中都可用的动态 import()。

有人知道如何解决这个问题吗?

导入 nestjs xlsx commonjs sheetjs

评论


答:

0赞 Micael Levi 11/14/2023 #1

由于您的项目使用的是 CJS,因此您应该使用表达式来加载仅限 ESM 的模块,如 NodeJS 文档中所述:https://nodejs.org/api/esm.html#import-expressionsimport()