Skip to content

Commit

Permalink
feat(cli): support replace ext in dynamic imports (#12046)
Browse files Browse the repository at this point in the history
* feat(get-deps): import('../foo.vue') => import('../foo.mjs') 的替换

* feat(get-deps): import('../foo.vue') => import('../foo.mjs') 的替换

* feat(get-deps): 对应正则的优化

* feat(get-deps): 对应正则的优化

* feat(get-deps): 对应正则的优化之前的太宽泛了

* feat(get-deps): 对应正则的优化之前的太宽泛了

* feat(get-deps): 对应正则的优化之前的太宽泛了

---------

Co-authored-by: sunguohui <[email protected]>
  • Loading branch information
suncohey and sunguohui authored Jul 29, 2023
1 parent 49e1e9f commit 3acee8b
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/vant-cli/src/compiler/get-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ let existsCache: Record<string, boolean> = {};
// https://regexr.com/47jlq
const IMPORT_RE =
/import\s+?(?:(?:(?:[\w*\s{},]*)\s+from(\s+)?)|)(?:(?:".*?")|(?:'.*?'))[\s]*?(?:;|$|)/g;

const IMPORT_NOF_RE = /import\s*\(\s*?['"].+?['"]\)/g;

const EXPORT_FROM_RE =
/@?export\s+?(?:(?:(?:[\w*\s{},]*)\s+from(\s+)?)|)(?:(?:".*?")|(?:'.*?'))[\s]*?(?:;|$|)/g;

Expand All @@ -16,6 +19,11 @@ function matchImports(code: string): string[] {
return imports.filter((line) => !line.includes('import type'));
}

function matchImportsNof(code: string): string[] {
const imports = code.match(IMPORT_NOF_RE) || [];
return imports.filter((line) => !line.includes('import type'));
}

function matchExportFroms(code: string): string[] {
const exportFroms = code.match(EXPORT_FROM_RE) || [];
return exportFroms.filter((line) => !line.includes('export type'));
Expand Down Expand Up @@ -97,17 +105,23 @@ export function getDeps(filePath: string) {
/**
* 1. Replace .vue extension
* @example "import App from 'App.vue';" => "import App from 'App.xxx';"
* @example "defineAsyncComponent(() => import('../xxx.vue'))" => "defineAsyncComponent(() => import('../xxx.xxx'));"
*
* 2. if using .mjs or .cjs, complete the import path
* @example import './foo' -> import './foo.mjs'
* @example import './foo' -> import './foo/index.mjs'
* @example "defineAsyncComponent(() => import('../foo.vue'))" => "defineAsyncComponent(() => import('../foo.mjs'));"
*/
export function replaceScriptImportExt(
code: string,
filePath: string,
ext: string,
) {
const imports = [...matchImports(code), ...matchExportFroms(code)];
const imports = [
...matchImports(code),
...matchImportsNof(code),
...matchExportFroms(code),
];

const updateImport = (index: number, newImport: string) => {
code = code.replace(imports[index], newImport);
Expand Down

0 comments on commit 3acee8b

Please sign in to comment.