Laravel项目中@tensorflow-models/toxicity库引入位置及报错问题
解决Laravel中集成@tensorflow-models/toxicity时的"toxicity is not defined"错误
我来帮你搞定这个问题!你遇到的两个报错——Uncaught ReferenceError: toxicity is not defined和Uncaught SyntaxError: Unexpected token *,本质是浏览器没法直接解析ES模块的import语法,同时库也没被正确加载到你的代码环境里。下面给你两种适配Laravel场景的解决方案:
方案一:用Laravel Vite处理(Laravel 9及以上默认推荐)
如果你的项目用的是Vite(现在Laravel新版本都是这个),按下面步骤来:
- 先装依赖
在项目根目录打开终端,运行:
npm install @tensorflow-models/toxicity @tensorflow/tfjs
- 修改你的
myjs.js文件
这次可以放心用import了,因为Vite会帮你编译:
import * as toxicity from '@tensorflow-models/toxicity'; import * as tf from '@tensorflow/tfjs'; $(document).ready(function() { const threshold = 0.9; toxicity.load(threshold).then(model => { const sentences = ['you suck']; model.classify(sentences).then(predictions => { console.log(predictions); // 顺便把结果渲染到页面的result容器里 $('#result').text(JSON.stringify(predictions, null, 2)); }); }); });
- 把
myjs.js加入Vite的编译队列
打开resources/js/app.js,添加一行引入:
import './myjs.js';
- 在视图里加载Vite编译后的资源
把原来的JS引入换成Vite的指令:
@vite(['resources/js/app.js']) <div id="result"></div>
- 启动开发服务或构建生产包
开发环境下运行:
npm run dev
上线前要构建生产版本:
npm run build
方案二:用CDN直接引入(不用构建工具的快速方案)
如果你不想折腾构建流程,直接用CDN把库加载到全局也能解决:
- 在视图里先加载CDN资源,再加载你的自定义JS
<!-- 先加载TensorFlow JS核心库 --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.10.0/dist/tf.min.js"></script> <!-- 再加载toxicity模型库 --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/toxicity@1.2.2/dist/toxicity.min.js"></script> <!-- 最后加载你的自定义JS --> <script src="{{ asset('js/myjs.js') }}"></script> <div id="result"></div>
- 修改
myjs.js去掉import语句
现在toxicity已经是全局对象了,直接用就行:
$(document).ready(function() { const threshold = 0.9; toxicity.load(threshold).then(model => { const sentences = ['you suck']; model.classify(sentences).then(predictions => { console.log(predictions); $('#result').text(JSON.stringify(predictions, null, 2)); }); }); });
注:你可以根据需要调整CDN的版本号,确保两个库版本兼容就行。
为啥之前的import没用?
- 浏览器原生不支持直接在普通JS文件里用
import语法,除非给script标签加type="module",但那样会有路径和跨域的问题,不如用Laravel自带的构建工具处理更省心。 - 你之前直接写import但没经过Vite/Mix编译,浏览器会把
import当成无效语法,自然就抛出Unexpected token *的错误了。
内容的提问来源于stack exchange,提问作者6563cc10d2
相关产品推荐
相关产品推荐

