LazyCodet

a

22:27:54 15/3/2025 - 0 views -
Programming

How to Separate Build Folders for Dev and Production in Nuxt 3

When working with Nuxt 3, you might encounter a common issue: after running npm run build, the .output/ folder is overwritten, causing errors when you try to run npm run dev again. This happens because both commands share the same .output/ directory by default.

To avoid this, you can configure separate build folders for development and production environments. Here's how you can do it.

Step 1: Update nuxt.config.ts

In your Nuxt configuration file (nuxt.config.ts), add the buildDir property to define separate output folders:

export default defineNuxtConfig({
  buildDir: process.env.NODE_ENV === 'production' ? '.output-build' : '.output-dev'
})

This configuration ensures that:

  • .output-dev/ is used during development.
  • .output-build/ is used for the production build.

Step 2: Update Your package.json

Since NODE_ENV=development syntax doesn't work on Windows by default, the best approach is to use cross-env for compatibility.

Install cross-env with:

pnpm add cross-env --save-dev

Then, modify the scripts in your package.json:

{
  "scripts": {
    "dev": "cross-env NODE_ENV=development nuxt dev",
    "build": "cross-env NODE_ENV=production nuxt build",
    "start": "cross-env NODE_ENV=production nuxt start --no-clear"
  }
}

Step 3: Running the Commands

  • For Development: Run pnpm dev. This will create a .output-dev/ folder.
  • For Production: Run pnpm build. This will create a .output-build/ folder.

Why Use cross-env?

cross-env ensures environment variables work consistently across different operating systems. This is especially important for Windows users since NODE_ENV=development doesn't work natively in CMD or Git Bash.

Conclusion

By separating your build folders for development and production, you can avoid common issues and streamline your workflow in Nuxt 3. This approach ensures your development environment remains stable, even after building for production.

Happy coding! 🚀