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

无法导入@langchain/community的Ollama模块,求技术解决方案

解决浏览器无法解析@langchain/community模块导入的问题

你的问题核心是浏览器原生ES模块不支持直接导入npm包的"裸模块标识符"(比如@langchain/community/llms/ollama),浏览器只能识别以/、./或../开头的相对/绝对路径模块。以下是几种可行的解决方案:

方案一:使用打包工具(推荐)

用Vite、Webpack这类工具将npm模块打包成浏览器可识别的代码,是前端项目的标准做法:

  1. 初始化Vite项目(注意备份现有文件后覆盖):
    npm create vite@latest . -- --template vanilla
    
  2. 重新安装依赖:
    npm install @langchain/community
    
  3. 将原public/app.js的代码移到src/main.js,并修改index.html中的脚本引用:
    <script type="module" src="/src/main.js"></script>
    
  4. 启动开发服务器:
    npm run dev
    
    打包工具会自动处理模块导入,浏览器能正常识别。

方案二:通过CDN直接引入模块

无需打包,直接用CDN提供的ES模块版本:
在index.html中添加模块导入并挂载到全局:

<script type="module">
  // 可根据需要替换为对应版本号
  import { Ollama } from 'https://cdn.jsdelivr.net/npm/@langchain/community@0.2.10/llms/ollama.js';
  window.Ollama = Ollama;
</script>

然后修改app.js,移除原import语句,直接使用全局变量:

const chatButton = document.getElementById('chat-button');

chatButton.addEventListener('click', async () => {
  try {
    console.log('Initializing Ollama client...');
    const ollama = new window.Ollama({
      baseUrl: "http://localhost:11434",
      model: "llama2",
    });
    // 后续逻辑保持不变
  } catch (error) {
    // 错误处理保持不变
  }
});

方案三:手动复制模块文件(不推荐)

从node_modules/@langchain/community/dist/llms/ollama.js找到编译后的模块文件,复制到public目录下,然后修改app.js的导入路径:

import { Ollama } from './ollama.js';

这种方式需要手动维护模块文件,版本更新时需重复操作,仅适合临时测试。

额外注意事项

  • 确保Ollama服务已在http://localhost:11434正常运行
  • 如果调用时出现跨域错误,需在server.js中添加CORS支持:
    1. 安装CORS中间件:npm install cors
    2. 在服务端代码中配置:
      const express = require('express');
      const cors = require('cors');
      const app = express();
      app.use(cors());
      // 其他服务端逻辑
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 22:10:18