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

Angular 15中使用lunr索引文章报错:lunr is not a function求助

Angular 15 中使用 lunr 出现「Error: lunr is not a function」的解决方案

问题原因

Angular 15 对 ES 模块的解析规则更严格,原有的命名导入方式(import * as lunr from 'lunr')无法正确识别 lunr 的函数导出结构,导致调用时报错。

解决方案

方案1:启用合成默认导入

  1. 打开项目根目录的 tsconfig.json,在 compilerOptions 中添加或修改配置:
{
  "compilerOptions": {
    // 保留原有其他配置
    "allowSyntheticDefaultImports": true
  }
}
  1. 使用默认导入方式引入 lunr:
import lunr from 'lunr';

方案2:直接调用模块的默认导出

如果不想修改 TypeScript 配置,可通过命名导入后提取默认导出:

import * as lunrModule from 'lunr';
const lunr = lunrModule.default;

验证示例

修改导入后,确保索引创建逻辑正常执行:

const searchIndex = lunr(function () {
  this.field('title');
  this.field('body');
  
  this.add({
    id: '1',
    title: 'Angular 15 升级指南',
    body: 'Angular 15 带来了诸多性能优化...'
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:55:05