How to create an alias to import components in Svelte without using relative paths

We will create the $svelte variable that will dynamically point to the /resources/svelte folder that contains the Svelte files compiled by Inertiajs

in 07/21/2024

If you are using a Laravel 8 project with Webpack.mix and Svelte, you must be used to importing components using relative paths. This can be a problem if you want to reorganize your project directories.

In this article we will learn how to create an alias to dynamically define the path of your component imports.

Who is this tutorial applicable to?

  1. If you are using a Laravel project with or without Inertiajs for Svelte
  2. If you are using Laravel Mix (used in Laravel versions 8 and earlier).

What will change?

This procedure allows instead of importing the components like this:

 import Component from "../../../../components/Component.svelte"

...you can import it like this:

 import Component from "$svelte/components/Component.svelte"

To do this we will create the alias $svelte. The alias is a global variable, which can be called in any file in your project. It will always point from the defined root. This way, your imports will be more organized. This alias is similar to Sveltekit's $lib.

In webpack.mix.js

Configure webpack to resolve the alias that will be created.

 .mix.webpackConfig({
resolve: {
indeed: {
$svelte: path.resolve(__dirname, 'resources/svelte'),
}
}}

In tsconfig.js

Configure typescript (even if you use js) to interpret the alias.

 {
"compilerOptions": {
"target": "es6",
"module": "esnext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"$svelte/*": [
"resources/svelte/*"
]
}
},
"exclude": [
"node_modules",
"public"
]
}

In jsconfig.json

Configure javascript to interpret your alias.

 {
"compilerOptions": {
"baseUrl": ".",
"paths": {
"$svelte/*": ["resources/svelte/*"]
}
},
"exclude": [
"node_modules",
"public"
]
}

Conclusion

Note that, in both jsconfig and tsconfig, it is necessary to exclude the "node_modules" and "public" directories so that it does not index the files in these folders.

Once done, restart your VS Code and wait for the indexing to finish. It is now possible to navigate using the alias.

To go back

Free project tool, flows, calendar, chat, mini site and much more
Nós utilizamos cookies
Utilizamos seus dados para analisar e personalizar nossos conteúdos e anúncios para você. Ao continuar usando este site você nos dá seu consentimento para coletar tais informações e utilizá-las para estas finalidades. Em caso de dúvidas, acesse nossa Privacy Policy