Importing third-party npm libraries in TypeScript files within a Nuxt.js Vue application

I’m encountering issues while trying to use a third-party npm library in my Nuxt.js application, which utilizes Vue and TypeScript. Specifically, I want to incorporate a package named array-randomizer, which relies on another library called random-generator.

Within my helpers/data.ts file, I have the following code:

import { randomize } from "array-randomizer";

export const myList: string[] = ["x", "y", "z"];

export const shuffledList = randomize(myList, "myseed");

However, when I start the development server, I receive this error message:

array-randomizer.js:520 Uncaught ReferenceError: random-generator is not defined
    at Object.<anonymous> (array-randomizer.js:520:25)
    at node_modules/array-randomizer/index.js (array-randomizer.js:580:12)
    at __require (chunk-ABC123.js:4:35)

I’ve confirmed that both packages are listed in my package.json:

"dependencies": {
  "array-randomizer": "^2.1.0",
  "nuxt": "^3.17.1",
  "random-generator": "^2.5.3",
  "vue": "^3.5.13"
},
"devDependencies": {
  "@types/array-randomizer": "^2.0.5",
  "@types/random-generator": "^2.1.2"
}

Here’s how my Nuxt configuration looks:

export default defineNuxtConfig({
  devtools: { enabled: true },
  ssr: false,
  modules: ['@nuxt/image']
})

I have attempted to create a declaration file, but it hasn’t resolved the problem. What steps can I take to correctly import and utilize external npm packages in Nuxt while using TypeScript?

This appears to be a module resolution issue where the array-randomizer package cannot locate its dependency at runtime. I’ve encountered similar situations with older npm libraries that aren’t compatible with modern bundlers. Consider adding both necessary packages to the build.transpile array in your Nuxt configuration:

export default defineNuxtConfig({
  devtools: { enabled: true },
  ssr: false,
  modules: ['@nuxt/image'],
  build: {
    transpile: ['array-randomizer', 'random-generator']
  }
})

If this doesn’t resolve the issue, you might try using dynamic imports in your helper file. Sometimes, encapsulating the import in a composable or limiting its use to client-side can help fix these dependency chain problems, as the bundler may have trouble resolving nested dependencies correctly.

nuxt is choking on commonjs modules that don’t mix well. wrap your import in try/catch or check process.client first. better yet, just write your own shuffle function - it’s 3 lines and saves you from dependency hell.

Your error happens because Nuxt can’t properly handle CommonJS modules on the client side. The array-randomizer library expects random-generator to be available globally, but Nuxt’s bundling doesn’t expose it right.

Wrap your randomization code in a process check so it only runs where the modules work:

export const getShuffledList = () => {
  if (process.server || typeof window === 'undefined') {
    const { randomize } = require('array-randomizer');
    return randomize(myList, 'myseed');
  }
  return myList; // fallback for client
}

Or just move this into a server API route (/server/api/shuffle.ts) where Node.js module resolution actually works, then fetch the shuffled data from your components. This kills the bundler conflicts completely and gives you better control over when shuffling happens.

Had the exact same issue with a package using internal requires. Nuxt’s module bundling breaks during SSR hydration - your library works in Node but fails when Nuxt bundles it for the browser.

Add this to your nuxt.config.ts:

export default defineNuxtConfig({
  devtools: { enabled: true },
  ssr: false,
  modules: ['@nuxt/image'],
  vite: {
    define: {
      global: 'globalThis'
    }
  }
})

Move your randomization logic into a composable that only runs client-side. I wrapped mine in onMounted() so it runs after hydration finishes. This stops the bundler from trying to resolve those dependencies during server render, which is what’s causing the conflicts.

Been there countless times with legacy packages. You’re fighting bundler compatibility when you should automate this.

Skip the transpile configs and plugin workarounds. Set up automation that handles your data shuffling through a proper API endpoint. I built something similar for our recommendation engine - needed consistent randomization across different environments.

Create a simple workflow: takes your array, applies randomization server-side, returns the shuffled result. You’ll avoid module resolution headaches and get consistent results in dev, staging, and production.

Trigger it from your Nuxt app with a simple HTTP request. The automation handles everything. No dependency hell, no bundler issues, just clean data flow.

I use Latenode for this exact pattern. Create workflows that handle data transformations like shuffling, then call them from any frontend framework without package compatibility issues.

The Problem:

You’re experiencing a runtime error (Uncaught ReferenceError: random-generator is not defined) when using the array-randomizer npm package within your Nuxt.js application, which utilizes Vue and TypeScript. This happens because Nuxt’s bundling process isn’t correctly resolving the dependency (random-generator) required by array-randomizer. The error occurs during the server-side rendering (SSR) process or during the client-side hydration step.

:thinking: Understanding the “Why” (The Root Cause):

The root cause is a classic incompatibility between the CommonJS (CJS) module system used by array-randomizer (and possibly random-generator) and the module system that Nuxt employs (likely ESM or a hybrid). Nuxt’s bundler attempts to optimize your application for the browser, and in doing so, it might incorrectly handle the require() statements or nested dependencies used within older CJS modules. This leads to the dependency (random-generator) not being correctly included in the client-side bundle resulting in the ReferenceError at runtime. The problem is exacerbated during SSR because the server environment has different module resolution rules compared to the browser environment.

:gear: Step-by-Step Guide:

  1. Create a Client-Side Plugin: The most reliable solution is to isolate the array-randomizer import within a client-side plugin. This prevents the server-side rendering (SSR) process from trying to resolve the dependency at build time. Create a new file at plugins/array-randomizer.client.ts:
// plugins/array-randomizer.client.ts
import { randomize } from 'array-randomizer';

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.provide('randomize', randomize);
});
  1. Register the Plugin: Add the plugin to your nuxt.config.ts file. This ensures that the plugin is loaded only on the client side:
// nuxt.config.ts
export default defineNuxtConfig({
  // ... your existing configuration
  plugins: [{ src: '~/plugins/array-randomizer.client', mode: 'client' }],
});
  1. Update your helpers/data.ts file: Now, use the provided randomize function instead of directly importing it:
// helpers/data.ts
import { useRandomize } from '#imports' //use your preferred method of injecting the function

export const myList: string[] = ["x", "y", "z"];

export const shuffledList = useRandomize(myList, "myseed");

If you’re using the composition API, use the inject function to inject randomize into your components.

  1. Verify Your Installation: Double-check that both array-randomizer and random-generator are correctly listed in your package.json’s dependencies section and that your project’s node_modules directory contains the packages. Run npm install again if you’ve updated package.json.

  2. Restart the Development Server: After making these changes, restart your Nuxt development server to ensure the changes are fully applied.

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Plugin Registration: Double-check that the plugin is correctly registered in your nuxt.config.ts file and that the mode: 'client' option is set. If this is missing, the plugin will be loaded server-side and trigger the same issue.
  • Module Resolution: If the problem persists, ensure that your Nuxt application is properly configured to resolve modules. Examine your nuxt.config.ts for any settings related to module resolution, and consider clearing your node_modules folder and reinstalling dependencies.
  • Type Definitions: Make sure you have the correct type definitions for both array-randomizer and random-generator installed as devDependencies in your package.json. This helps avoid TypeScript errors, although it won’t fix the runtime error itself.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.