diff --git a/package.json b/package.json index 93f86a4..42e7103 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ }, "prettier": "tomer/prettier-config", "dependencies": { - "es-module-lexer": "^1.5.3", + "es-module-lexer": "^1.5.4", "slashes": "^3.0.12" }, "devDependencies": { diff --git a/src/index.js b/src/index.js index 77839e7..3b49fc0 100644 --- a/src/index.js +++ b/src/index.js @@ -23,8 +23,10 @@ export const parseImportsSync = (code, { resolveFrom } = {}) => { for (let { d: dynamicImportStartIndex, ss: statementStartIndex, + se: statementEndIndex, s: moduleSpecifierStartIndex, e: moduleSpecifierEndIndexExclusive, + a: metaStartIndex, } of imports) { const isImportMeta = dynamicImportStartIndex === -2 if (isImportMeta) { @@ -69,7 +71,20 @@ export const parseImportsSync = (code, { resolveFrom } = {}) => { importClause = parseImportClause(importClauseString) } - yield { + let meta + if (metaStartIndex > -1) { + let metaString = code.slice(metaStartIndex, statementEndIndex).trim() + if (isDynamicImport) { + metaString = metaString.slice(0, -1) + meta = runExpression(metaString) + } else { + const metaName = code.slice(moduleSpecifierEndIndexExclusive, metaStartIndex).trim() + if (metaName) {metaString = '{'+ metaName + ':' + metaString + '}'} + meta = runExpression(metaString) + } + } + + const result = { startIndex: statementStartIndex, // Include the closing parenthesis for dynamic import endIndex: isDynamicImport @@ -79,7 +94,17 @@ export const parseImportsSync = (code, { resolveFrom } = {}) => { moduleSpecifier, importClause, } + + if (meta) { + result.meta = meta + } + + yield result } }, } } + +function runExpression(code) { + return new Function(`return ${code}`)() +} diff --git a/test/index.test.ts b/test/index.test.ts index 3300b87..b78d987 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -17,6 +17,26 @@ test(`parseImportsSync throws before WASM load`, () => { ) }) +test(`parseImports with meta`, async () => { + let code = `import a from 'b'with {at: '12'}` + const imports: any[] = [] + for (const $import of await parseImports(code)) {imports.push($import)} + expect(imports).toHaveLength(1) + expect(imports[0].meta).toStrictEqual({with: {at: '12'}}) + + code = `import a from 'b' with {at: '12'}` + imports.length = 0 + for (const $import of await parseImports(code)) {imports.push($import)} + expect(imports).toHaveLength(1) + expect(imports[0].meta).toStrictEqual({with: {at: '12'}}) + + code = `await import("w", {with: {at: "1"}})` + imports.length = 0 + for (const $import of await parseImports(code)) {imports.push($import)} + expect(imports).toHaveLength(1) + expect(imports[0].meta).toStrictEqual({with: {at: '1'}}) +}) + test.each([ { path: `no-resolve.js`, diff --git a/tsconfig.json b/tsconfig.json index e5ff9bd..9569746 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,4 +1,7 @@ { "extends": "tomer/tsconfig", + "compilerOptions": { + "target": "es2015" + }, "include": ["**/*"] }