3

In my nuxt directory structure I have a folder called modules which contains my custom modules. In this example it will contain the modules foo and bar. In nuxt.config.js foo is added like so:

// nuxt.config.js
...
modules: [
  ...
  "~/modules/foo"
],
...

Note bar is not added as a module. When I try to import bar in foo

// foo/index.ts

import { bar } from '~/modules/bar';

export default function fooModule() {
  console.log(bar)
}
// bar/index.ts

const bar = 1
export { bar };

export default function barModule() {}

I get Nuxt Fatal Error, Error: Cannot find module '~/modules/bar'. Adding "~/modules/bar" to modules in nuxt.config.js seems to make no difference.

Any Idea on how to prevent this?

1 Answer 1

2

A module is something designed with Nuxt in mind, something like the axios module is to be added this way in nuxt.config.js

export default {
  modules: ['@nuxtjs/axios']
}

You cannot dump your own code just like that into modules.


You're probably looking for plugins here?

Sign up to request clarification or add additional context in comments.

6 Comments

Im not sure I thought plugins where meant to inject functionality into the Vue context (preferably I would like to import foo and bar using an import statement at the top of the script)? I might be misunderstanding the use of plugins, Ill look into this, thanks!
Yeah, the difference between plugins and modules can be hard to understand at first. Meanwhile, you need to also know that writing it as a plugin will link it globally to the project. If it's not needed, feel free to simply import it per component/page for performance reasons. @DominiqueGarmier
If not in /plugins where would you put those .ts files? Is there a best practice? From what I understand I could put them in /assets but the documentation says it's meant for images, styles, fonts etc.
@DominiqueGarmier usually, a /utils/ is an okay directory (at the root of the project), I'm doing it this way and all the people I worked with before with are doing the same.
So I moved all my "utils" to /utils. But the problem remains. I have one module in /modules (which needs to be there), it injects a plugin into the Vue-context. And imports from /utils, which apparently doesn't exit during the build process. Giving me again Error: Cannot find module '~/utils/...'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.