Imports in Nuxt Layers — Transcript

Transcript of the free Vue.js lesson Imports in Nuxt Layerswatch the video lesson.

Before Nuxt's three point sixteen, import statements in Nuxt layers were a little bit tricky. In this lesson, let me show you why and how you can avoid the gotchas using the latest features. So if I were to import a component, traditionally I would use the at symbol as an alias to the root directory. The problem with this is that the Hello World component doesn't exist in the root of my playground or my actual application.

It exists in the components directory of the layer. Therefore, TypeScript does correctly complain here that the module can't be found. Over in the browser, this does actually work, though, as the layer is merged in with the app. So what's the workaround?

Well, if I just remove the import statement altogether, the auto imports do work as expected. So you really don't have to import anything if you don't want to. However, I know some people don't like auto imports. And if you have some code in a directory that isn't already being auto imported, then you would have to provide a manual import.

If I provide a relative path inside of my end application to the layer, this does work. Notice that the error disappears. And in the browser, everything is just the same. However, this makes a tight coupling between the location of my end application and the layer code.

I definitely don't want to have a relative path in my end application to the layer code. That way, when I end up distributing it, I can distribute it in many different ways. vue from the playground and paste it into the layer and then provide a relative path there. This would be OK, because you can provide relative paths inside of your layer to other files within your layer.

But there is a better way, because it works for both scenarios. Inside NuxtApps that are three point sixteen and above, we can provide a name to our layer inside of the layer's Nuxt config. That's defined under the meta property, and then the name property. Let's call our layer my layer.

Now, in both files that exist inside of our layer and files that exist inside of the end user project, instead of using the at alias or relative paths, we can use the hashtag layers alias slash the name of our layer. So in the end user app and inside of the layer code, both work exactly the same. My recommendation, therefore, is to always import code inside of your layers and inside of your end user apps that are extending a layer with this syntax right here. it points to the root of your layer, and you can get everything you need out of that layer, whether it's in a directory that supports auto imports or even if it's not.

If you do get an error, failed to resolve import, when you do this for the first time, don't worry, that's totally normal. Sometimes Nuxt just doesn't like to pick up on that name change for the layer. Just restart your dev server and everything should work great.