guybedford / es-module-lexer

Low-overhead lexer dedicated to ES module parsing for fast analysis
MIT License
917 stars 48 forks source link

parse not correct #97

Closed WarrenJones closed 2 years ago

WarrenJones commented 2 years ago

const [{ default: lang }, { default: langWidgets }] = await Promise.all([ // eslint-disable-next-line no-unsanitized/method import(@test/i18n/locales/${config.locale}) // eslint-disable-next-line no-unsanitized/method .then(p => p, () => import(@test/es/i18n/locales/${defaultLocale})), // eslint-disable-next-line no-unsanitized/method import(@aaa/i18n/locales/${config.locale}) // eslint-disable-next-line no-unsanitized/method .then(p => p, () => import(@aaa/es/i18n/locales/${defaultLocale})), ]);

What this snippet returns is out of expected.

console.log(index + 'exp', source.substring(expStart, expEnd)) console.log(index + 'ee', source.substring(start, end))

guybedford commented 2 years ago

@WarrenJones the properties to use here are the s and e values, which will be the full string including the template literal. The reason for this is that the range of a dynamic import is its full dynamic expression, not the internal string.

With your example code:

const source = `
const [{ default: lang }, { default: langWidgets }] = await Promise.all([
  // eslint-disable-next-line no-unsanitized/method
  import(\`@test/i18n/locales/\${config.locale}\`)
    // eslint-disable-next-line no-unsanitized/method
    .then(p => p, () => import(\`@test/es/i18n/locales/7\${defaultLocale}\`)),
  // eslint-disable-next-line no-unsanitized/method
  import(\`@aaa/i18n/locales/\${config.locale}\`)
    // eslint-disable-next-line no-unsanitized/method
    .then(p => p, () => import(\`@aaa/es/i18n/locales/\${defaultLocale}\`)),
]);
`;

const [imports, exports] = parse(source);

for (const impt of imports) {
  console.log(source.slice(impt.s, impt.e));
}

gives me the output:

`@test/i18n/locales/${config.locale}`
`@test/es/i18n/locales/7${defaultLocale}`
`@aaa/i18n/locales/${config.locale}`
`@aaa/es/i18n/locales/${defaultLocale}`

Closing as resolved, but feel free to discuss further.