a dynamic import() which is available in all CommonJS modules?

在Nodejs的文件中:
此代码执行完全正常:


import { Client } from '@notionhq/client'
import { NotionCompatAPI } from 'notion-compat'


(async() => {
  const token = 'your-token'

  const notion = new NotionCompatAPI(
      new Client({ auth: token })
  )
  
  const pageId = 'your-page-id'
  
  const recordMap = await notion.getPage(pageId)
  
  console.log(recordMap)

})()

但是我使用express作为nodejs后端框架在使用的时候会报错:

[ERROR] 14:41:09 Error: require() of ES Module path/node_modules/.pnpm/notion-compat@7.1.6_@notionhq+client@2.2.15/node_modules/notion-compat/build/index.js from path/src/notion/index.ts not supported.
Instead change the require of index.js in path/src/notion/index.ts to a dynamic import() which is available in all CommonJS modules.

具体代码文件: https://codesandbox.io/s/j67h8w

关键代码:

import { Client } from '@notionhq/client'
import { NotionCompatAPI } from 'notion-compat'


export const getBlocks = async(blockId?: string) => {
  const token = 'your-token'

  const notion = new NotionCompatAPI(
      new Client({ auth: token })
  )
  
  const pageId = 'your-page-id'
  
  const recordMap = await notion.getPage(pageId)
  
  return recordMap
}
阅读 1k
avatarAI BotBETA
### 回答

在 Node.js 中,当你遇到使用 `require()` 加载 ES 模块(ESM)时的错误,并且错误提示你改为使用 `dynamic import()`,这通常意味着你正在尝试在一个 CommonJS 模块系统中加载一个设计为 ES 模块的包。

在 Express 或任何基于 CommonJS 的 Node.js 应用中,如果你需要加载一个 ES 模块,你可以使用 `import()` 函数(动态导入),而不是静态的 `import` 语句或 `require()` 函数。这是因为静态 `import` 语句和 `require()` 函数在处理模块类型(ESM vs CommonJS)时有不同的行为和要求。

对于你的情况,你可以修改你的代码,将静态的 `import` 语句替换为动态 `import()`,如下所示:

// 从静态导入改为动态导入
// import { Client } from '@notionhq/client';
// import { NotionCompatAPI } from 'notion-compat';

export const getBlocks = async (blockId?: string) => {
const token = 'your-token';

// 使用动态导入
const [Client, { NotionCompatAPI }] = await Promise.all([

import('@notionhq/client'),
import('notion-compat')

]);

const notion = new NotionCompatAPI(new Client({ auth: token }));

const pageId = 'your-page-id';

const recordMap = await notion.getPage(pageId);

return recordMap;
}


这里,我们使用 `Promise.all()` 来并行加载 `@notionhq/client` 和 `notion-compat` 两个模块,然后解构赋值给 `Client` 和 `NotionCompatAPI`。这种方法允许你在 CommonJS 环境中动态地加载 ES 模块。

注意,动态导入返回的是一个 Promise,因此你需要在 `await` 之后使用它。这种方法解决了在 CommonJS 环境中直接 `require()` ES 模块时遇到的问题。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏