Nuxt Compiler Constants Utility

1.0.0 · active · verified Tue Apr 21

nuxt-define is a utility package designed for Nuxt module authors to uniformly define compiler constants across all supported Nuxt builders, including Vite, Webpack, and Rspack. It abstracts away the builder-specific mechanisms for constant definition, providing a single `addDefinePlugin` function. This allows module developers to avoid adding builder-specific dev dependencies, reducing dependency noise and ensuring consistent behavior regardless of the underlying bundler chosen by the Nuxt project. The current stable version is 1.0.0, suggesting a mature initial release. As a utility, its release cadence is likely tied to Nuxt ecosystem updates or bug fixes, rather than a strict schedule. Its key differentiator is simplifying cross-builder constant definition and enabling effective dead code elimination for feature flags during the build process, leading to optimized bundles.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import and use `addDefinePlugin` within a Nuxt module's setup function to define global compiler constants.

import { defineNuxtModule } from '@nuxt/kit';
import { addDefinePlugin } from 'nuxt-define';

export default defineNuxtModule({
  meta: {
    name: 'my-feature-module',
    configKey: 'myFeature'
  },
  setup(_options, _nuxt) {
    // Define compiler constants that will be available globally in your runtime code
    addDefinePlugin({
      '__MY_MODULE_VERSION__': JSON.stringify('1.2.3'),
      '__ENABLE_ANALYTICS__': JSON.stringify(true),
      '__API_ENDPOINT__': JSON.stringify(process.env.API_ENDPOINT ?? 'https://api.example.com/default')
    });

    // Example of how these constants might be used in a runtime file (e.g., src/runtime/analytics.ts)
    // if (__ENABLE_ANALYTICS__) {
    //   console.log(`Analytics enabled. Module version: ${__MY_MODULE_VERSION__}`);
    //   // initAnalytics(__API_ENDPOINT__);
    // }

    console.log('Nuxt module setup completed, constants defined.');
  }
});

view raw JSON →