Skip to content

Commit

Permalink
feat(compiler): compile ts files
Browse files Browse the repository at this point in the history
  • Loading branch information
nivekcode committed Mar 4, 2020
1 parent fe13a4c commit a911b7c
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 31 deletions.
27 changes: 18 additions & 9 deletions package-lock.json

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

35 changes: 35 additions & 0 deletions src/lib/compiler/typescript-compiler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import * as ts from 'typescript';

const compile = (filePaths: string[], compilerOptions: ts.CompilerOptions): void => {
let program = ts.createProgram(filePaths, compilerOptions);
let emitResult = program.emit();

reportDiagnostics(ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics));

let exitCode = emitResult.emitSkipped ? 1 : 0;
process.exit(exitCode);
};

function reportDiagnostics(diagnostics: ts.Diagnostic[]): void {
diagnostics.forEach(diagnostic => {
let message = 'Error';
if (diagnostic.file) {
let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
message += ` ${diagnostic.file.fileName} (${line + 1},${character + 1})`;
}
message += ': ' + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
console.log(message);
});
}

export const compileSources = (filePaths: string[]): void => {
const tsOptions = {
noEmitOnError: true,
noImplicitAny: true,
declaration: true,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.ESNext
};
compile(filePaths, tsOptions);
};
38 changes: 19 additions & 19 deletions src/lib/converters/multiple-files.converter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,22 @@ import {
generateSvgConstant,
generateTypeDefinition,
generateTypeName,
generateUntypedSvgConstant,
generateVariableName
} from '../generators/generators';
import { getFilePathsFromRegex } from '../regex-helpers';
import { extractSvgContent, writeIconsFile } from '../file-helpers';
import { getFilePathsFromRegex } from '../helpers/regex-helpers';
import { deleteFolder, extractSvgContent, writeIconsFile } from '../helpers/file-helpers';
import { ConvertionOptions } from '../../bin/svg-to-ts';
import { compileSources } from '../compiler/typescript-compiler';

const typesDelimitor = ' | ';

export const convertToMultipleFiles = async (convertionOptions: ConvertionOptions): Promise<void> => {
const { typeName, prefix, delimiter, interfaceName, outputDirectory, srcFiles, fileName } = convertionOptions;
let svgConstants = '';
let types = generateTypeDefinition(typeName);

try {
const filePaths = await getFilePathsFromRegex(srcFiles);
await deleteFolder(`${outputDirectory}/icons`);
for (let i = 0; i < filePaths.length; i++) {
const fileNameWithEnding = path.basename(filePaths[i]);
const [filenameWithoutEnding, extension] = fileNameWithEnding.split('.');
Expand All @@ -31,26 +32,25 @@ export const convertToMultipleFiles = async (convertionOptions: ConvertionOption
const optimizedSvg = await svgo.optimize(rawSvg);
const variableName = generateVariableName(prefix, filenameWithoutEnding);
const typeName = generateTypeName(filenameWithoutEnding, delimiter);
const svgConstant = generateSvgConstant(variableName, interfaceName, typeName, optimizedSvg.data);
const svgConstant = generateUntypedSvgConstant(variableName, typeName, optimizedSvg.data);

await writeIconsFile(outputDirectory, `${prefix}-${filenameWithoutEnding}.icon`, svgConstant);

svgConstants += svgConstant;
types += i === filePaths.length - 1 ? `'${typeName}';` : `'${typeName}'${typesDelimitor}`;
await writeIconsFile(`${outputDirectory}/icons`, `${prefix}-${filenameWithoutEnding}.icon`, svgConstant);
}
}
const outputFiles = await getFilePathsFromRegex([`${outputDirectory}/icons/*.ts`]);
compileSources(outputFiles);

/*
if (svgConstants !== '') {
const fileContent = (svgConstants += types += generateInterfaceDefinition(interfaceName, typeName));
await writeIconsFile(outputDirectory, fileName, fileContent);
console.log(
chalk.blue.bold('svg-to-ts:'),
chalk.green('Icons file successfully generated under'),
chalk.green.underline(outputDirectory)
);
}
*/
if (svgConstants !== '') {
const fileContent = (svgConstants += types += generateInterfaceDefinition(interfaceName, typeName));
await writeIconsFile(outputDirectory, fileName, fileContent);
console.log(
chalk.blue.bold('svg-to-ts:'),
chalk.green('Icons file successfully generated under'),
chalk.green.underline(outputDirectory)
);
}
*/
} catch (error) {
console.log(chalk.blue.bold('svg-to-ts:'), chalk.red('Something went wrong', error));
}
Expand Down
23 changes: 23 additions & 0 deletions src/lib/generators/generators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,29 @@ export const generateSvgConstant = (
};`;
};

export const generateUntypedSvgConstant = (
variableName: string,
filenameWithoutEnding: string,
data: string
): string => {
return `export const ${variableName} = {
name: '${filenameWithoutEnding}',
data: '${data}'
};`;
};

export const generateSvgStandaloneFile = (
variableName: string,
interfaceName: string,
filenameWithoutEnding: string,
data: string
): string => {
return `export const ${variableName}: ${interfaceName} = {
name: '${filenameWithoutEnding}',
data: '${data}'
};`;
};

export const generateTypeName = (filenameWithoutEnding, delimiter: Delimiter): string => {
if (delimiter === Delimiter.CAMEL) {
return `${camelCase(filenameWithoutEnding)}`;
Expand Down
18 changes: 15 additions & 3 deletions src/lib/file-helpers.ts → src/lib/helpers/file-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import * as path from 'path';
import * as prettier from 'prettier/standalone';
import typescriptParser from 'prettier/parser-typescript';

import { ConvertionOptions } from '../bin/svg-to-ts';

const readfile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);

Expand All @@ -17,11 +15,25 @@ export const extractSvgContent = async (filePath: string): Promise<string> => {
export const writeIconsFile = async (outputDirectory: string, fileName: string, fileContent: string): Promise<void> => {
const formatedFileContent = formatContent(fileContent);
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory);
fs.mkdirSync(outputDirectory, { recursive: true });
}
await writeFile(path.join(outputDirectory, `${fileName}.ts`), formatedFileContent);
};

export const deleteFolder = async (directoryPath: string) => {
if (fs.existsSync(directoryPath)) {
fs.readdirSync(directoryPath).forEach((filePath: string) => {
const curPath = directoryPath + '/' + filePath;
if (fs.lstatSync(curPath).isDirectory()) {
deleteFolder(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(directoryPath);
}
};

const formatContent = (fileContent: string) =>
prettier.format(fileContent, {
parser: 'typescript',
Expand Down
File renamed without changes.

0 comments on commit a911b7c

Please sign in to comment.