The alias property

Nuxt allows you to use aliases to access custom directories within your JavaScript and CSS


  • Type: Object
  • Default:

    1. {
    2. '~~': `<rootDir>`,
    3. '@@': `<rootDir>`,
    4. '~': `<srcDir>`,
    5. '@': `<srcDir>`,
    6. 'assets': `<srcDir>/assets`, // (unless you have set a custom `dir.assets`)
    7. 'static': `<srcDir>/static`, // (unless you have set a custom `dir.static`)
    8. }

This option lets you define aliases to directories within your project (in addition to the ones above). These aliases can be used within your JavaScript and CSS.

nuxt.config.js

  1. import { resolve } from 'path'
  2. export default {
  3. alias: {
  4. 'images': resolve(__dirname, './assets/images'),
  5. 'style': resolve(__dirname, './assets/style'),
  6. 'data': resolve(__dirname, './assets/other/data')
  7. }
  8. }

components/example.vue

  1. <template>
  2. <img src="~images/main-bg.jpg">
  3. </template>
  4. <script>
  5. import data from 'data/test.json'
  6. // etc.
  7. </script>
  8. <style>
  9. @import '~style/variables.scss';
  10. @import '~style/utils.scss';
  11. @import '~style/base.scss';
  12. body {
  13. background-image: url('~images/main-bg.jpg');
  14. }
  15. </style>

The alias Property - 图1

Within a Webpack context (image sources, CSS - but not JavaScript) you must prefix your alias with ~ (as in the example above).

The alias Property - 图2

If you are using TypeScript and want to use the alias you define within your TypeScript files, you will need to add the aliases to your paths object within tsconfig.json.