Skip to content
Advertisement

Next.js – best way to serve static JS from a node module’s “dist” folder

I’m working with an application that uses Tesseract (OCR) to read text from images.

I would like to take some JS files from node_modules/tesseract.js/dist and make them downloadable in the browser.

I know I can just copy the files to ./public and next.js will serve it statically from there, but then if I update my version of Tesseract, I may need to update those files as well. So maintenance becomes a problem.

My 1st thought is to customize my webpack config to copy the files from node_modules/tesseract.js/dist to ./public/tesseract (or something like that). That would make sure the files get re-copied if I update Tesseract. But I’m not particularly savvy with webpack and haven’t figured out how to do that yet.

My 2nd thought was to “proxy” the retrieval of the JS file’s content and just make the content available as a “page” in next.js (but this seems super hacktastic).

I feel like this is something that shouldn’t be so complicated … but I’ve not been able to figure it out myself yet.

Thanks in advance!

Advertisement

Answer

Yup agreed, updating your server to serve a node_modules path sounds a bit dangerous.

I personally would just copy over these files with webpack like you mentioned.

Here are the docs on Next.js on how to set up a custom webpack config.

next.config.js

const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  webpack: (config) => {
    // append the CopyPlugin to copy the file to your public dir
    config.plugins.push(
      new CopyPlugin({
        patterns: [
          { from: "node_modules/tesseract.js/dist", to: "public/" },
        ],
      }),
    )

    // Important: return the modified config
    return config
  }
};

I purposefully didn’t include the public/tesseract path, I’m not sure if the CopyPlugin will automatically generate missing directories if they don’t exist at build time.

Advertisement