Easily use transformers.js with react in browser.
npm install use-transformers
import { useState } from "react";
import { useTransformers } from "use-transformers";
export default function Home() {
const [input, setInput] = useState("I love transformers!");
const { data, isLoading, mutate } = useTransformers({
task: "sentiment-analysis",
options: {
dtype: "q8",
},
});
const handleClick = () => {
if (!input) return;
mutate(input);
};
return (
<main className="flex h-full flex-col items-center justify-center gap-y-4">
<div className="flex w-60 flex-col items-center gap-y-4">
<input
disabled={isLoading}
value={input}
onChange={(e) => setInput(e.target.value)}
/>
<div>{JSON.stringify(data)}</div>
<Button onClick={handleClick}>
ready: {JSON.stringify(isLoading)}
</Button>
</div>
</main>
);
}
- react hooks
- use web worker
For current load worker file in browser, you need to add the following to your next.config.ts
, see this issue for more information.
next.config.ts
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { NextConfig } from "next";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const nextConfig: NextConfig = {
webpack: (config) => {
// https://github.com/huggingface/transformers.js/issues/1026#issuecomment-2490410996
config.resolve.alias = {
...config.resolve.alias,
"sharp$": false,
"onnxruntime-node$": false,
"@huggingface/transformers": path.resolve(
__dirname,
"node_modules/@huggingface/transformers",
),
};
return config;
},
};
export default nextConfig;
- transformers.js
- bripc
- API design swr