{"id":15364,"library":"nuxt-define","title":"Nuxt Compiler Constants Utility","description":"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.","status":"active","version":"1.0.0","language":"javascript","source_language":"en","source_url":null,"tags":["javascript","nuxt","module","typescript"],"install":[{"cmd":"npm install nuxt-define","lang":"bash","label":"npm"},{"cmd":"yarn add nuxt-define","lang":"bash","label":"yarn"},{"cmd":"pnpm add nuxt-define","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Primarily used within the `setup()` hook of a Nuxt module to define global compiler constants.","wrong":"const { addDefinePlugin } = require('nuxt-define')","symbol":"addDefinePlugin","correct":"import { addDefinePlugin } from 'nuxt-define'"},{"note":"Compiler constants are globally available during build-time compilation and should be accessed directly, not via `global` or `window`.","wrong":"console.log(global.__MY_CONSTANT__)","symbol":"__MY_CONSTANT__","correct":"console.log(__MY_CONSTANT__)"}],"quickstart":{"code":"import { defineNuxtModule } from '@nuxt/kit';\nimport { addDefinePlugin } from 'nuxt-define';\n\nexport default defineNuxtModule({\n  meta: {\n    name: 'my-feature-module',\n    configKey: 'myFeature'\n  },\n  setup(_options, _nuxt) {\n    // Define compiler constants that will be available globally in your runtime code\n    addDefinePlugin({\n      '__MY_MODULE_VERSION__': JSON.stringify('1.2.3'),\n      '__ENABLE_ANALYTICS__': JSON.stringify(true),\n      '__API_ENDPOINT__': JSON.stringify(process.env.API_ENDPOINT ?? 'https://api.example.com/default')\n    });\n\n    // Example of how these constants might be used in a runtime file (e.g., src/runtime/analytics.ts)\n    // if (__ENABLE_ANALYTICS__) {\n    //   console.log(`Analytics enabled. Module version: ${__MY_MODULE_VERSION__}`);\n    //   // initAnalytics(__API_ENDPOINT__);\n    // }\n\n    console.log('Nuxt module setup completed, constants defined.');\n  }\n});","lang":"typescript","description":"Demonstrates how to import and use `addDefinePlugin` within a Nuxt module's setup function to define global compiler constants."},"warnings":[{"fix":"Ensure all non-string values (booleans, numbers, objects) are wrapped with `JSON.stringify()`: `JSON.stringify(true)`, `JSON.stringify('my-string')`.","message":"Values passed to `addDefinePlugin` must be stringified using `JSON.stringify()` if they are not already strings. Forgetting this can lead to syntax errors in the bundled output, as the values are directly substituted into the code.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Understand that these are compile-time transformations. Do not expect to modify them at runtime. Use `process.env` for runtime environment variables.","message":"Compiler constants are replaced at build time, meaning they are not dynamic runtime variables. Changes to constants require a re-build. They are also subject to dead code elimination if used in conditional statements with a falsy value (e.g., `if (__FEATURE_FLAG__)`).","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Add a declaration file (e.g., `src/types/globals.d.ts`) with `declare const __MY_CONSTANT__: string;` for each constant.","message":"Compiler constants are not typed by default. If using TypeScript, you may need to declare them globally to avoid 'Cannot find name '__MY_CONSTANT__'' errors in your runtime code.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `addDefinePlugin` is called within your Nuxt module's `setup()` function and that the constant name exactly matches. Confirm the constant is used in code processed by the Nuxt build (e.g., `src/runtime/` files).","cause":"Attempting to access a compiler constant in runtime code without it being properly defined via `addDefinePlugin` in a Nuxt module, or trying to access it in a context where the build-time replacement has not occurred.","error":"ReferenceError: __SOME_FEATURE_FLAG__ is not defined"},{"fix":"Always use `JSON.stringify()` for the constant values, even for booleans, numbers, or strings (e.g., `'__MY_FLAG__': JSON.stringify(true)`).","cause":"A non-string value (like a boolean or number) was passed to `addDefinePlugin` without being wrapped in `JSON.stringify()`, leading to raw value substitution that breaks JavaScript syntax.","error":"SyntaxError: Invalid or unexpected token (e.g., if (true,) { ... })"},{"fix":"Create a `globals.d.ts` file in your project (e.g., `src/types/globals.d.ts`) and declare the constants: `declare const __MY_CONSTANT__: string;`.","cause":"TypeScript compiler cannot resolve the globally injected compiler constant during type checking, even if it works at runtime.","error":"TS2304: Cannot find name '__MY_CONSTANT__'."}],"ecosystem":"npm"}