FredKSchott / snowpack

ESM-powered frontend build tool. Instant, lightweight, unbundled development. ✌️
https://www.snowpack.dev
MIT License
19.48k stars 922 forks source link

[FEATURE] Transform complex dynamic imports #2861

Open FredKSchott opened 3 years ago

FredKSchott commented 3 years ago

The problem that you want to solve.

Issue reported here: https://github.com/snowpackjs/snowpack/discussions/2840 We should be able to transform:

import(`../locales/${langCode}.json`);

to:

import(`../locales/${langCode}.json.proxy.js`);

Your take on the correct solution to problem.

We could add some advanced handling to our internal transform utility to parse the expression inside of a dynamic import into an AST (with something like acorn) or even something simpler like Regex. Then, we could transform the template string based on its raw parts.

Are you willing to submit a pull request to implement this change?

This is a little tricky, but fairly self contained / a good place to start if you're looking to contribute to Snowpack!

natemoo-re commented 3 years ago

I wonder if we could combine #2900 and #2881, expand the import.meta.glob lexer to collect all import statements, then handle import.meta.glob and proxy import transforms all in one go? That sounds like it would be the most performant solution.

We could also speed up the lexer by only scanning forward from import tokens rather than the whole file.

natemoo-re commented 3 years ago

Also this particular use case might be solved by our upcoming import.meta.glob feature? I'll have to test this one!

// writing the following
const langs = import.meta.glob(`../locales/*.json`);

// should produce
const langs = {
  '../locales/en.json': () => import('../locales/es.json.proxy.js'),
  '../locales/es.json': () => import('../locales/es.json.proxy.js')
}
FredKSchott commented 3 years ago

Oh interesting! What if we just added a warning when we saw a complex dynamic import, telling you to use glob instead?

Airkro commented 3 years ago

import.meta.glob can't be found in the document.