face-api: Unable to use faceapi in a nexjs - react application "Module not found: Can't resolve 'fs'"

Issue Description Getting the following error:

error - ./node_modules/@vladmandic/face-api/dist/face-api.esm.js:8:25031 Module not found: Can’t resolve ‘fs’

Steps to Reproduce create a nextjs application as given here:

https://nextjs.org/learn/basics/create-nextjs-app/setup

added face api packages (npm install). Including tensorflow Invoked the api to load the models: await faceapi.nets.ssdMobilenetv1.loadFromUri(‘/models’)

And got the error:

Expected Behavior It should have loaded the models.

**Environment Windows 10. Nodejs. React application. Using VS code editor. Browser is chrome/Edge.

  • Module version?
  • Built-in demo or custom code? - custom
  • Type of module used (e.g. js, esm, esm-nobundle)? js
  • Browser or NodeJS and version (e.g. NodeJS 14.15 or Chrome 89)? - Node v14.13.1, Chrome Version 89.0.4389.90 (Official Build) (64-bit)
  • OS and Hardware platform (e.g. Windows 10, Ubuntu Linux on x64, Android 10)? Windows 10
  • Packager (if any) (e.g, webpack, rollup, parcel, esbuild, etc.)? standard webpack

Additional

  • For installation or startup issues include your package.json
  • For usage issues, it is recommended to post your code as gist

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 26 (13 by maintainers)

Most upvoted comments

i’ll try to create a detailed wiki article in the next few day, so i’m reopening this issue as a reminder.

just add file next.config.js to your project root with content:

module.exports = {
  future: {
    webpack5: true,
  },
  webpack: (config) => {
    if (config.target === 'web') config.externals = [ 'fs', 'os' ];
    return config;
  },
}

then loading a component works fine in emotion.js:

const Faceapi = dynamic(() => import('../components/loadFaceapi'), { ssr: false });

where loadFaceapi.js contains:

import * as faceapi from '@vladmandic/face-api/dist/face-api.esm.js';

however, since FaceAPI is now loaded inside the component, all faceapi processing should be inside that component as well - there is no global object faceapi registered in emotion.js (and you can’t re-export an import from a component).

so you have to move all calls to FaceAPI inside loadFaceapi.js
(e.g. faceapi.nets.ssdMobilenetv1.loadFromUri(), faceapi.detectAllFaces, etc.)

I’ll share the entire project without the node modules. Please do an npm install and npm run dev to run the project.

thanks