Search code examples
sveltesapper

In sapper/svelt is there a shortcut to components


In nuxts/vue there is an alias @ and ~ to mean the root of the app. is there something similar in sapper/svelte to that in a deep route like /very/deep/page/1/2/3/4 I don't have to do something like:

import Head from '../../../../../../../../components/Thingy.svelte'

Solution

  • If you are using rollup, you can obtain it using @rollup/plugin-alias.

    For example, in your rollup.config.js:

    // ...
    import alias from '@rollup/plugin-alias';
    import path from 'path';
    // ...
    
    export default {
      input: 'src/main.js',
      // ...
      plugins: [
        // ...
        alias({
          resolve: ['.jsx', '.js', '.svelte'], // optional, by default this will just look for .js files or folders
          entries: [
            { find: '@', replacement: path.resolve(__dirname, 'src') },
          ]
        }),
        // ...
      ],
      // ...
    };
    

    Then @ will be an alias for the src directory under your toplevel.

    If you are using webpack instead, you can use the resolve.alias config property. For example, inn your webpack.config.js:

    // ...
    import path from 'path';
    // ...
    
    module.exports = {
      // ...
    
      resolve: {
        alias: {
          '@': path.resolve(__dirname, 'src')
        }
      }
    
      // ...
    };