Typescript is recommanded for this module usage
You can also check nuxt-typed-router for route names autocomplete
yarn add -D nuxt-assets-paths
#or
npm install -D nuxt-assets-paths
First, register the module in the nuxt.config.[js|ts]
const config = {
...,
modules: [
'nuxt-assets-paths',
]
}
In your nuxt.config
import 'nuxt-assets-paths';
export default {
assetsPaths: {
// Options
},
};
Options:
export interface NuxtAssetsPathsOptions {
//
/**
* Path to where you cant the file to be saved (ex: "./src/models/assets.ts")
* @default "<srcDir>/__assetsPaths.ts"
*/
filePath?: string;
/** Name of the routesNames object in the generated file (ex: "routesTree")
* @default "assetsPaths"
* */
pathsObjectName?: string;
/**
* Enables static files paths generation
* @default true */
staticPaths?: boolean;
}
Exemple:
import 'nuxt-assets-paths';
export default {
assetsPaths: {
filePath: 'src/models/__assetsPaths.ts',
},
};
At build , the module will create a file with the global object of the assets paths inside.
Given this structure
βββ assets
βββ icons
βββ actions
βββ done.png
βββ done.svg
βββ home.svg
βββ images
βββ background.svg
βββ flower.webp
βββ ...
The generated file will look like this
export const assetsPaths = {
icons: {
actions: {
done_png: '~assets/icons/actions/done.png',
done_svg: '~assets/icons/actions/done.svg',
},
home: '~assets/icons/home.svg',
},
images: {
background: '~assets/images/background.svg',
flower: '~assets/images/flower.webp',
},
};
export type AssetsPaths =
| '~assets/icons/actions/done.png'
| '~assets/icons/actions/done.svg'
| '~assets/icons/home.svg'
| '~assets/images/background.svg'
| '~assets/images/flower.webp';
You can now just import it
<template>
<img :src="assetsPaths.actions.done_svg" />
</template>
import { assetsPaths } from '~/models/assetsPaths.ts';
export default {
data: () => ({
assetsPaths,
}),
};
And type your component props (Volar recommanded in VSCode)
import { Proptype } from 'vue';
import { AssetsPaths } from '...yourPath/__assetsPaths';
export default defineComponent({
name: 'Image',
props: {
src: { type: String as PropType<AssetsPaths> },
},
});
Create a plugin nuxt-assets-paths.ts
, and register it in your nuxt.config.js
import { assetsPaths } from '...your file path';
export default (ctx, inject) => {
inject('assets', assetsPaths);
};
Then create shims a file in ~/shims/nuxt.d.ts
import { assetsPaths } from '...your file path';
declare module 'vue/types/vue' {
interface Vue {
$assets: typeof assetsPaths;
}
}
You will now have $assets
exposed in all your component without importing it and it will be typed automaticaly!
<template>
<img :src="$assets.actions.done_svg" />
</template>
- Clone this repository
- Install dependencies using
yarn
ornpm install