Vue3集成OpenAI Node库遇Unexpected token编译错误求助
Vue3项目集成OpenAI API Node库编译失败问题排查与解决
问题背景
执行以下操作后项目编译报错:
- 运行
npm install openai安装依赖 - 在
<script setup>中添加import OpenAI from "openai" - 执行
npm run serve启动项目,出现编译错误
编译错误信息
ERROR Failed to compile with 1 error 20:47:19 error in ./node_modules/openai/index.js Module parse failed: Unexpected token (50:148) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. | */ > constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, ...opts } = {}) { | if (apiKey === undefined) { | throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); @ ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/ToolsViews/LLMModelDetails.vue?vue&type=script&setup=true&lang=js 20:0-28 131:15-21 @ ./src/ToolsViews/LLMModelDetails.vue?vue&type=script&setup=true&lang=js @ ./src/ToolsViews/LLMModelDetails.vue @ ./src/router/index.js @ ./src/main.js @ multi (webpack)-dev-server/client?http://192.168.1.7:8090&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
项目配置文件
package.json
{ "name": "vue-argon-dashboard-2", "version": "3.0.0", "private": true, "author": "Creative Tim", "license": "SEE LICENSE IN <https://www.creative-tim.com/license>", "description": "VueJS version of Argon Dashboard 2 by Creative Tim", "homepage": "https://demos.creative-tim.com/vue-argon-dashboard/", "bugs": { "url": "https://github.com/creativetimofficial/vue-argon-dashboard/issues" }, "repository": { "type": "git", "url": "git+https://github.com/creativetimofficial/vue-argon-dashboard.git" }, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "@babel/core": "^7.23.9", "@formkit/auto-animate": "^0.8.1", "@popperjs/core": "2.11.8", "axios": "^1.6.5", "bootstrap": "^5.3.2", "core-js": "3.35.1", "dropzone": "6.0.0-beta.2", "echarts": "^4.9.0", "element-plus": "^2.5.2", "jquery": "^3.7.1", "next": "^14.1.0", "openai": "^4.28.0", "pinia": "^2.1.7", "quill": "1.3.7", "vue": "3.4.15", "vue-flatpickr-component": "11.0.3", "vue-router": "4.2.5", "vuex": "^4.1.0" }, "devDependencies": { "@babel/plugin-proposal-nullish-coalescing-operator": "^7.18.6", "@babel/preset-env": "^7.23.9", "@vue/cli-plugin-babel": "4.5.0", "@vue/cli-plugin-eslint": "4.5.0", "@vue/cli-plugin-router": "4.5.0", "@vue/cli-service": "4.5.0", "@vue/compiler-sfc": "3.2.0", "@vue/eslint-config-prettier": "6.0.0", "babel-eslint": "^10.1.0", "eslint": "6.7.2", "eslint-plugin-prettier": "3.3.1", "eslint-plugin-vue": "7.0.0", "prettier": "2.2.1", "sass": "1.43.3", "sass-loader": "10.1.1" } }
vue.config.js
module.exports = { lintOnSave: false,//关闭eslint语法检查 devServer: { port: 8090, proxy: { '/api': { // target: 'http://localhost:9088', target: 'http://localhost:9172', changeOrigin: true, ws: true, pathRewrite: { // '^/api'是一个正则表达式,表示要匹配请求的url中,全部'http://localhost:8000/api' 转接为 http://localhost:8000/ '^/api': '', } } } }, configureWebpack: { module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: "javascript/auto" } ] } } };
babel.config.js
module.exports = { presets: ["@vue/cli-plugin-babel/preset","@babel/preset-env"], };
已尝试操作
- 升级Node至最新版本,问题未解决
- 新建仅集成OpenAI API Node库的项目可正常运行
- 当前项目卸载openai并移除导入代码后恢复正常
解决方案
1. 让Babel处理OpenAI模块
修改vue.config.js,添加规则让babel-loader编译node_modules/openai中的代码,支持空值合并运算符:
module.exports = { lintOnSave: false, devServer: { port: 8090, proxy: { '/api': { target: 'http://localhost:9172', changeOrigin: true, ws: true, pathRewrite: { '^/api': '', } } } }, configureWebpack: { module: { rules: [ { test: /\.mjs$/, include: /node_modules/, type: "javascript/auto" }, // 添加以下规则 { test: /\.js$/, include: /node_modules\/openai/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: ['@babel/plugin-proposal-nullish-coalescing-operator'] } } } ] } } };
2. 使用OpenAI浏览器兼容入口
OpenAI官方提供了浏览器端兼容的导入路径,修改导入语句:
import OpenAI from "openai/browser";
实例化时需开启dangerouslyAllowBrowser选项(仅测试环境使用,生产环境不建议直接暴露API密钥):
const openai = new OpenAI({ apiKey: "你的API密钥", dangerouslyAllowBrowser: true });
3. 升级Vue CLI版本
当前项目使用的@vue/cli-service 4.5.0对Vue3的支持有限,建议升级到Vue CLI 5+:
npm update @vue/cli-service @vue/cli-plugin-babel @vue/cli-plugin-eslint @vue/cli-plugin-router --save-dev
升级后执行npm install重新安装依赖,再启动项目。
4. 后端代理调用(生产环境推荐)
直接在浏览器端使用API密钥存在安全风险,建议通过后端代理调用OpenAI API:
- 后端示例(Node.js):
const express = require('express'); const OpenAI = require('openai'); const app = express(); app.use(express.json()); const openai = new OpenAI({ apiKey: "你的API密钥" }); app.post('/api/openai/chat', async (req, res) => { try { const { messages } = req.body; const completion = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages: messages }); res.json(completion); } catch (err) { res.status(500).json({ error: err.message }); } }); app.listen(9172, () => console.log('后端服务启动在9172端口')); - 前端调用示例:
import axios from 'axios'; async function callOpenAI() { const response = await axios.post('/api/openai/chat', { messages: [{ role: "user", content: "Hello!" }] }); console.log(response.data); }
内容的提问来源于stack exchange,提问作者JimTheVueGuy
相关产品推荐
相关产品推荐

