react-markdown-preview icon indicating copy to clipboard operation
react-markdown-preview copied to clipboard

Vite doesn't support dynamically import from node_modules

Open amatiasq opened this issue 4 years ago • 2 comments

I'm trying to use this library with Vite and that produces this error:

18:39:01 [vite] warning: 
/Users/foo/vite-test/node_modules/.vite/@uiw_react-markdown-preview.js
11080|              }
11081|              return _context.abrupt("return", Promise.all(langs.map(function(key) {
11082|                return import("prismjs/components/prism-".concat(key));
   |                              ^
11083|              })));
11084|            case 5:
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.

  Plugin: vite:import-analysis
  File: /Users/foo/vite-test/node_modules/.vite/@uiw_react-markdown-preview.js?v=59696cce

It's talking about this line: https://github.com/uiwjs/react-markdown-preview/blob/cbcb4f1ee233f9627fd01195853319417468574a/src/langs.ts#L253

Vite (or Rollup, I'm not sure) has a feature where it rewrites "bare modules" (modules which path is not absolute nor relative) so it's imported from node_modules.

If we follow the link in the output we can see that there are some limitations to this feature:

  • Imports must start with ./ or ../.
  • Imports must end with a file extension

So it's not possible to use this library with Vite due to this single import.

amatiasq avatar Jul 06 '21 16:07 amatiasq

@amatiasq What is a good solution?

I can't support it, it will cause us to be unable to use it in webpack and rollup.

Vite supports importing multiple modules from the file system via the special import.meta.glob function:

const modules = import.meta.glob(`prismjs/components/prism-${key}`)

jaywcjlove avatar Aug 15 '21 08:08 jaywcjlove

Sorry I've moved away from Vite and this problem, in general I'd advocate against dynamic imports but this looks like a good fit so I don't know how can it be solved.

amatiasq avatar Aug 15 '21 18:08 amatiasq