vite-plugin-dynamic-import icon indicating copy to clipboard operation
vite-plugin-dynamic-import copied to clipboard

Cannot get it to work in SvelteKit...

Open rchrdnsh opened this issue 2 years ago • 9 comments

I added the plugin to the config, like so:

plugins: [
  autoImport({
    components: ['./src/library'],
  }),
  sveltekit(),
  dynamicImport(),
  // etc....

...then tried to use it in a svelte component, like so:

let Component;
onMount(async () => {
  // Component = (await import(`../library/${component}.svelte`)).default <-- this works, btw, but not ideal...
  Component = (await import(`@library/${component}.svelte`)).default
})

..and got the following error in the console:

10:38:54 AM [vite] warning: 
/Users/rchrdnsh/Code/Svelte/RYKR-kit/src/library/ContentCard.svelte
1375|   onMount(async () => {
1376|           // Component = (await import(`../library/${component}.svelte`)).default
1377|           $$invalidate(11, Component = (await import(`@library/${component}.svelte`)).default);
   |                                               ^
1378|   });
1379|  
The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

...but it also does not work in the app either...

...so, dunno what to do to make it work (shrug emoji)

rchrdnsh avatar Dec 09 '22 18:12 rchrdnsh

Is @library an alias in your vite.config.js?

caoxiemeihao avatar Dec 10 '22 09:12 caoxiemeihao

in sveltekit the aliases are defined in the svelte.config.js like so:

import adapter from '@sveltejs/adapter-auto';
import { mdsvex } from 'mdsvex';
import mdsvexConfig from './mdsvex.config.js';
import sveltePreprocess from 'svelte-preprocess';

/** @type {import('@sveltejs/kit').Config} */

const config = {
  extensions: [
    '.svelte',
    ...mdsvexConfig.extensions
  ],
  preprocess: [
    mdsvex(mdsvexConfig),
    sveltePreprocess()
  ],
  kit: {
    adapter: adapter({ edge: true }),
    alias: {
      $library: 'src/library',
      $content: 'src/content',
      $images: 'src/images',
      $music: 'src/music',
      $themes: 'src/themes'
    }
  }
};

export default config;

...and sveltekit itself is a vite plugin, like so:

import { sveltekit } from '@sveltejs/kit/vite';
import autoImport from 'sveltekit-autoimport';
import dynamicImport from 'vite-plugin-dynamic-import';
import { imagetools } from 'vite-imagetools';
import mkcert from 'vite-plugin-mkcert';

/** @type {import('vite').UserConfig} */

const supportedExtensions = ['webp', 'jpg', 'jpeg', 'png'];

const config = {
  ssr: {
    noExternal: [
      'svelte-stripe-js',
      'style-value-types',
      'popmotion',
      'framesync'
    ]
  },
  plugins: [
    autoImport({
      components: ['./src/library'],
    }),
    sveltekit(),
    dynamicImport(),
    imagetools(
      {
        defaultDirectives: (url) => {
          const extension = url.pathname.substring(
            url.pathname.lastIndexOf('.') + 1
          );
          if (supportedExtensions.includes(extension)) {
            return new URLSearchParams({
              format: `webp;jpg`,
              width: `200;300;400;500;800;1000;2000`,
              picture: true
            });
          }
          return new URLSearchParams();
        }
      },
    ),
    mkcert({hosts: ['localhost', 'app.local']})
  ]
};

export default config;

...and those aliases defined in the `svelte.config.js file are used in the generated tsconfig.json, like so:

{
  "compilerOptions": {
    "baseUrl": "..",
    "paths": {
      "$library": [
        "src/library"
      ],
      "$library/*": [
        "src/library/*"
      ],
      "$content": [
        "src/content"
      ],
      "$content/*": [
        "src/content/*"
      ],
      "$images": [
        "src/images"
      ],
      "$images/*": [
        "src/images/*"
      ],
      "$music": [
        "src/music"
      ],
      "$music/*": [
        "src/music/*"
      ],
      "$themes": [
        "src/themes"
      ],
      "$themes/*": [
        "src/themes/*"
      ]
    },
    "rootDirs": [
      "..",
      "./types"
    ],
    "importsNotUsedAsValues": "error",
    "isolatedModules": true,
    "preserveValueImports": true,
    "lib": [
      "esnext",
      "DOM",
      "DOM.Iterable"
    ],
    "moduleResolution": "node",
    "module": "esnext",
    "target": "esnext"
  },
  "include": [
    "ambient.d.ts",
    "./types/**/$types.d.ts",
    "../vite.config.ts",
    "../src/**/*.js",
    "../src/**/*.ts",
    "../src/**/*.svelte",
    "../src/**/*.js",
    "../src/**/*.ts",
    "../src/**/*.svelte",
    "../tests/**/*.js",
    "../tests/**/*.ts",
    "../tests/**/*.svelte"
  ],
  "exclude": [
    "../node_modules/**",
    "./[!ambient.d.ts]**"
  ]
}

...but beyond these files i don't know what's going on between Vite and Svelte Kit.

rchrdnsh avatar Dec 10 '22 17:12 rchrdnsh

You may need to define the corresponding alias in vite.config.js.

Not sure how work Vite and Svelte Kit. Can you provide a minimal reproduction Demo?

caoxiemeihao avatar Dec 11 '22 00:12 caoxiemeihao

oh geeez…totally forgot to make a minrep, apologies…does it work now?

rchrdnsh avatar Jan 12 '23 07:01 rchrdnsh

Still need to reproduce the Demo 😅

caoxiemeihao avatar Jan 12 '23 08:01 caoxiemeihao

@idleberg is talking in this post: https://stackoverflow.com/questions/69295473/svelte-sveltekit-dynamic-import-of-components-with-variable

about how he did get a similar plugin => The Rollup plugin @rollup/plugin-dynamic-import-vars to work with Svelte and Vite. So while the concept of this vite plugin seems to work, this does not yet work with sveltekit and vite.

Still Error Output from svelte:

Error while preprocessing /home/user/projects/exampleapp/src/routes/example/switchmepage/+page.svelte - Transform failed with 1 error: /home/user/projects/exampleapp/src/routes/example/switchmepage/+page.svelte:29:28: ERROR: Expected string but found "`./src/${"

Any chance you get this done @caoxiemeihao ? Otherwise maybe a hint: This is known to not work with xyz would be nice. How did you solve your issue until now @rchrdnsh ?

raphael-devel avatar Jan 25 '23 14:01 raphael-devel

Anyone provide a minimal reproduction of the repo? Because I haven't used SvelteKit yet. :(

caoxiemeihao avatar Jan 26 '23 10:01 caoxiemeihao

@caoxiemeihao Here you will find the minimal repo: https://github.com/raphael-devel/raphael-devel-demo-sveltekit-repo-4-vite-plugin-dynamic-import

But it is really just a matter of:

npm create svelte@latest my-app
cd my-app
npm install
npm run dev

details about the SETUP you will find in README.md

Hope that helps..

For me this issue now is not crucial... but maybe it will help others...

raphael-devel avatar Jan 29 '23 11:01 raphael-devel

vite.config.js

 export default {
   resolve: {
+    extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json', '.svelte'],
   },
 }

https://github.com/vite-plugin/vite-plugin-dynamic-import/blob/v1.2.7/src/index.ts#L77

caoxiemeihao avatar Jan 30 '23 03:01 caoxiemeihao