When working with local layers in Nuxt, referencing assets like CSS files can be tricky because of how path resolution works. Let me explain the issue and provide solutions.
The Problem
When you use aliases like ~ or @ in a layer, they are resolved relative to the user's project paths, not the layer itself. This is why your CSS import isn't working as expected.
Solutions
1. Use full resolved paths in your layer's nuxt.config.ts
The recommended approach for layers is to use full resolved paths:
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
const currentDir = dirname(fileURLToPath(import.meta.url))
export default defineNuxtConfig({
css: [
join(currentDir, './assets/css/styles.css')
]
})
This approach is documented in the Nuxt Layers guide and ensures that paths are resolved correctly relative to your layer.
2. Use named layer aliases (Nuxt 3.15+)
If you're using Nuxt 3.15+, you can take advantage of named layer aliases. For auto-scanned layers (from your ~~/layers directory), Nuxt automatically creates aliases. For example, you can access your layer via #layers/base (assuming your layer is named "base").
To create named layer aliases, specify a name in the configuration of your layer:
export default defineNuxtConfig({
$meta: {
name: 'base',
},
})
Then you can reference your CSS file using:
css: ['#layers/base/assets/css/styles.css']
This feature was added in PR #30948.
3. Check experimental localLayerAliases setting