Skip to content

Commit

Permalink
fix function that removes/change import, export and export default st…
Browse files Browse the repository at this point in the history
…atement
  • Loading branch information
wpdas committed Apr 27, 2024
1 parent 0d5e81a commit 9e57ca5
Show file tree
Hide file tree
Showing 8 changed files with 123 additions and 22 deletions.
2 changes: 1 addition & 1 deletion lib/actions/handleNames.js
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ const checkIfItemExistInContent = (content, itemName) => {
* @param {{filePath: string, toImport: string[], content: string}[]} fileSchemas
*/
const handleNames = (fileSchemas) => {
reset_name_counter();
// reset_name_counter();
let tempBundle = "";

/**
Expand Down
49 changes: 32 additions & 17 deletions lib/actions/transformSchemaToWidget.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,6 @@ const processSchema = (fileSchema) => {
}
});
isModule = !foundIgnoredFile;

console.log("FINAL:", isModule);
}

// INFO: Ficou mais pesado porque tem arquivos com conteúdo pequeno, e o codigo adicionado para pegar a referencia deixa maior
Expand Down Expand Up @@ -759,13 +757,13 @@ const injectModules = (fileSchemas, fileSchema) => {
// TODO: Parei aqui, parece que ta tudo certo
// console.log("FOOO", fileSchema.filePath);
// Atualiza o modulo deste arquivo para usar o finalBundle com as importacoes injetadas
console.log("Exported Keys:", fileSchema.moduleProps.values);
const sofrer = wrapCodeInGetFunction(
fileSchema.finalFileBundle,
fileSchema.filePath,
);
console.log("Module:", sofrer);
console.log("Final:", filterReturn(sofrer, fileSchema.moduleProps.values));
// console.log("Exported Keys:", fileSchema.moduleProps.values);
// const sofrer = wrapCodeInGetFunction(
// fileSchema.finalFileBundle,
// fileSchema.filePath,
// );
// console.log("Module:", sofrer);
// console.log("Final:", filterReturn(sofrer, fileSchema.moduleProps.values));

fileSchema.moduleProps = {
...fileSchema.moduleProps,
Expand Down Expand Up @@ -805,9 +803,9 @@ const injectDependencies = (fileSchemas, fileSchema) => {
if (!fileItemSchema.isModule) {
// Injeta o conteúdo literalmente
fileBundle = `
${fileItemSchema.jsContent}
${fileBundle}
`;
${fileItemSchema.jsContent}
${fileBundle}
`;

injectedFiles.push(fileItemPath);
}
Expand All @@ -833,6 +831,14 @@ const injectFilesDependencies = (fileSchemas, fileSchema) => {
return fileSchema;
};

const injectModulesDependencies = (fileSchemas, fileSchema) => {
// Faz a injeção das dependencias dos módulos, dependencias de stateless files, nao de outros módulos.
// INFO: A injeção de referencia de módulos é feito pelo "injectModules"
// fileSchema = injectDependencies(fileSchemas, fileSchema, true);

return fileSchema;
};

/**
* Caso tenha dependencias do Alem (inportable items), prepara eles para serem injetados.
*
Expand Down Expand Up @@ -970,15 +976,24 @@ const transformSchemaToWidget = (fileSchemas, additionalFileSchemas) => {
);
});

// Faz transformação de async/await para o formato promisify
// Injeta as dependencias dos arquivos módulos dentro deles
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
// Transform async/await (experimental)
fileSchema.finalFileBundle = transformAsyncAwait(
fileSchema.finalFileBundle,
fileSchemas[fileSchemaIndex] = injectModulesDependencies(
fileSchemas,
fileSchema,
);
fileSchemas[fileSchemaIndex] = fileSchema;
});

// Faz transformação de async/await para o formato promisify
// fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
// // Transform async/await (experimental)
// fileSchema.finalFileBundle = transformAsyncAwait(
// fileSchema.finalFileBundle,
// );
// fileSchemas[fileSchemaIndex] = fileSchema;
// });
// TODO: remover transformAsyncAwait.js

// ATENÇÃO: muda tanto o "finalFileBundle" quanto o "jsContent"
// Injeta os módulos caso sejam requeridos
fileSchemas.forEach((fileSchema, fileSchemaIndex) => {
Expand Down
4 changes: 4 additions & 0 deletions lib/alem-vm/importable/modules/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Modules

Thes files inside this folder are going to be injected to the global state and components using them will get only their references, so, saving
size for the final bundle file.
5 changes: 5 additions & 0 deletions lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,10 @@ function escapeHtmlEntities(str) {
.replace(/'/g, "'");
}

// Transforma "export default function" para "function"
const exportDefaultFunctionToFunction = (code) =>
code.replaceAll(/\bexport default function\b/g, "function");

module.exports = {
getFileImportsElements,
getImportStatements,
Expand Down Expand Up @@ -645,4 +649,5 @@ module.exports = {
hasHtmlElements,
cleanErrorMessage,
escapeHtmlEntities,
exportDefaultFunctionToFunction,
};
8 changes: 8 additions & 0 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ const removeExports = (code) => {
return newCode;
};

/**
* Remove Imports
*
* ATENÇÃO: Prefira usar "removeImportsAndExports" que é feito com Babel, é 100% seguro e mais robusto!
*
* @param {*} c
* @returns
*/
const removeImports = (c) => {
// Remove line breaks
const importItems = c.match(/(import)(.*?)(from)/gs);
Expand Down
68 changes: 68 additions & 0 deletions lib/parsers/removeImportsAndExports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
const t = require("@babel/types");

/**
* Remove linhas que tenham "import" do javascript
* Troca "export" e "export default" por nada
*
* INFO: Essa é a forma mais segura
*
* @param {*} code
* @returns
*/
function removeImportsAndExports(code) {
const ast = parser.parse(code, {
sourceType: "module", // necessário para suportar módulos ES6
plugins: ["jsx", "typescript"], // adicione plugins se estiver usando JSX ou TypeScript
});

traverse(ast, {
ImportDeclaration(path) {
path.remove(); // Remove a declaração de importação completamente
},
ExportDeclaration(path) {
if (path.node.declaration) {
// Se a declaração de exportação possui um nó de declaração (ou seja, não é apenas 'export { something }')
const { declaration } = path.node;
path.replaceWith(declaration); // Substitui a exportação pela declaração contida
} else {
// Para exportações que são apenas exportações de variáveis, remover a palavra 'export'
path.replaceWithMultiple(
path.node.specifiers.map((specifier) =>
t.variableDeclaration("let", [
t.variableDeclarator(specifier.local),
]),
),
);
}
},
ExportDefaultDeclaration(path) {
if (path.node.declaration) {
// Remove apenas a palavra 'default' e mantém a declaração
const { declaration } = path.node;
if (
t.isFunctionDeclaration(declaration) ||
t.isClassDeclaration(declaration)
) {
// Para funções e classes, elas precisam ser convertidas para expressões antes da remoção do 'export default'
const expression = t.functionExpression(
null,
declaration.params,
declaration.body,
declaration.generator,
declaration.async,
);
path.replaceWith(expression);
} else {
path.replaceWith(declaration);
}
}
},
});

return generate(ast, { false: true }).code;
}

module.exports = removeImportsAndExports;
3 changes: 2 additions & 1 deletion lib/parsers/transformAndGetFunctionExportDeclarations.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const convertFunctionsToArrow = require("./convertFunctionsToArrow");
const { exportDefaultFunctionToFunction } = require("../helpers");
const generate = require("@babel/generator").default;

function convertExportDefault(code) {
Expand Down Expand Up @@ -36,7 +37,7 @@ function convertExportDefault(code) {
*/
function transformAndGetFunctionExportDeclarations(code, filePath) {
// Transforma "export default function" para "function"
code = code.replaceAll(/\bexport default function\b/g, "function");
code = exportDefaultFunctionToFunction(code);

// Converte functions para arrow functions
try {
Expand Down
6 changes: 3 additions & 3 deletions lib/parsers/wrapCodeInGetFunction.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const t = require("@babel/types");
const babel = require("@babel/core");
// const babelPreset = require("@babel/preset-env");
// const reactPreset = require("@babel/preset-react");
const typescriptPreset = require("@babel/preset-typescript");
const convertFunctionsToArrow = require("./convertFunctionsToArrow");
const removeGetNameAndLastComma = require("./removeGetNameAndLastComma");
const removeImportsAndExports = require("./removeImportsAndExports");

/**
* Esta função vai cobrir o arquivo/code com uma função Get e todas as declarações sendo exportadas
Expand Down Expand Up @@ -41,7 +40,8 @@ const removeGetNameAndLastComma = require("./removeGetNameAndLastComma");
*/
function wrapCodeInGetFunction(code, filePath) {
// Remover importações e exports
code = code.replace(/import.*;|export\s+default|export\s+/g, "");
// code = code.replace(/import.*;|export\s+default|export\s+/g, "");
code = removeImportsAndExports(code);

// Parsear o código para AST removendo TypeScript
const ast = parser.parse(code, {
Expand Down

0 comments on commit 9e57ca5

Please sign in to comment.