Skip to content

Commit

Permalink
#157: Refactored creating the import code to use the advanced reflect…
Browse files Browse the repository at this point in the history
…ion library
  • Loading branch information
petermasking committed Feb 22, 2023
1 parent 045debe commit eeb422b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 39 deletions.
27 changes: 6 additions & 21 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion packages/jitar-vite-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "jitar-vite-plugin",
"version": "0.3.2",
"version": "0.3.3",
"description": "Vite plugin for Jitar.",
"author": "Masking Technology <[email protected]> (https://jitar.dev)",
"license": "MIT",
Expand All @@ -17,6 +17,9 @@
"clean": "rm -rf dist build",
"release": "npm run clean && npm run build && npm publish"
},
"dependencies": {
"jitar-reflection": "^0.1.0"
},
"peerDependencies": {
"vite": "^4.0.0"
},
Expand Down
24 changes: 7 additions & 17 deletions packages/jitar-vite-plugin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@

import path from 'path';
import { PluginOption, normalizePath, ResolvedConfig } from 'vite';
import { Reflector, ReflectionFunction } from 'jitar-reflection';

const IMPORT_PATTERN = /import(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/_-]+)["'\s].*/g;
const reflector = new Reflector();

function formatPath(path: string)
{
Expand Down Expand Up @@ -52,28 +53,17 @@ async function createImportCode(code: string, id: string, jitarFullPath: string,
.replace(jitarFullPath, '')
.replace('.ts', '.js');

// Remove all imports from the code
code = code.replace(IMPORT_PATTERN, () =>
{
return '';
});

// Later on, we need to strip the code further into an interface to make sure it can be imported
// (we can than share and reuse this code for the Jitar cache builder)

// Load the code as data url into a module
const importData = Buffer.from(code).toString('base64');
const importUrl = `data:text/javascript;base64,${importData}`;
const module = await import(importUrl);
const module = reflector.parse(code);
const exported = module.exported;

// Extract all exports from the module
const allKeys = Object.keys(module);
const functionKeys = allKeys.filter(key => key !== 'default' && typeof module[key] === 'function');
const allKeys = [...exported.keys()];
const functionKeys = allKeys.filter(key => key !== 'default' && exported.get(key) instanceof ReflectionFunction);

let importCode = '';
let exportCode = '';

if (allKeys.includes('default'))
if (exported.has('default'))
{
importCode += `const defaultExport = module.default;\n`;
exportCode += `export default defaultExport;\n`;
Expand Down

0 comments on commit eeb422b

Please sign in to comment.