'Dependency not found in Nuxt when defining alias in nuxt.config.js

I'm getting this error when trying to import a file using a custom alias:

import api from 'api'

api in ./node_modules/babel-loader/lib??ref--2-0!./node_modules/vue-loader/lib??vue-loader-options!./pages/exercises.vue?vue&type=script&lang=js&

This is my nuxt.config.js:

import { resolve } from 'path'
const _api = process.env.API_MOCK === '1' ? 'apimock': 'api'

export default {
  buildModules: [
    '@nuxtjs/vuetify',
    '@nuxtjs/router'
  ],
  alias: {
    'api': resolve(__dirname,  './helpers/' + _api)
  },
}

My file structure looks like this:

.
├── components
│   ├── drawer.vue
│   ├── popup-criar-treino.vue
│   ├── popup-treino.vue
│   └── toolbar.vue
├── helpers
│   ├── api
│   │   └── urls.js
│   └── apimock
│       ├── db_mock
│       │   └── db_mock.js
│       ├── mockadapter.js
│       └── urls.js
├── jsconfig.json
├── layouts
│   └── default.vue
├── nuxt.config.js
├── package.json
├── package-lock.json
├── pages
│   ├── exercises.vue
│   ├── index.vue
│   ├── plans.vue
│   └── treinos.vue
└── router.js

I dont get what i'm missing here, i'm following the example in Nuxt docs: https://nuxtjs.org/docs/configuration-glossary/configuration-alias/



Solution 1:[1]

You should inject axios to api.js file

export default function ({ $axios, app }, inject) {
  const api = $axios.create({
    headers: {
      common: {
        Accept: 'application/json',
        Authorization
      }
    }
  });
  inject('api', api)
}

Then add api to plugins then you can call it as alias in anywhere in app

  plugins: [    
    { src: '~/plugins/api.js' },
  ]

this.$api.get/post...

With your directory, you also can inject to NuxtApp like the way I suggest above;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hai Tien