eslint#ESLint TypeScript Examples
The following examples show how to use
eslint#ESLint.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: examples.spec.ts From graphql-eslint with MIT License | 6 votes |
function getESLintOutput(cwd: string): ESLint.LintResult[] {
const { stdout, stderr } = spawnSync('eslint', ['.', '--format', 'json'], { cwd });
const errorOutput = stderr.toString();
if (errorOutput) {
throw new Error(errorOutput);
}
const output = stdout.toString();
const start = output.indexOf('[{');
const end = output.lastIndexOf('}]') + 2;
return JSON.parse(output.slice(start, end));
}
Example #2
Source File: examples.spec.ts From graphql-eslint with MIT License | 6 votes |
function testSnapshot(results: ESLint.LintResult[]): void {
const normalizedResults = results
.map(result => ({
filePath: relative(ROOT_CWD, result.filePath),
messages: result.messages,
}))
.filter(result => result.messages.length > 0);
expect(normalizedResults).toMatchSnapshot();
}
Example #3
Source File: rules.spec.ts From graphql-eslint with MIT License | 6 votes |
function getESLintWithConfig(
configName: 'schema-all' | 'operations-all' | 'relay',
parserOptions?: ParserOptions
): ESLint {
return new ESLint({
useEslintrc: false,
baseConfig: {
overrides: [
{
files: '*.graphql',
extends: `plugin:@graphql-eslint/${configName}`,
parserOptions: {
schema: 'type Query { foo: Int }',
skipGraphQLConfig: true,
...parserOptions,
},
},
],
},
});
}
Example #4
Source File: testing.ts From eslint-config-kit with MIT License | 6 votes |
export async function testConfig({ config, files, extension }: Options) {
const cli = new ESLint({
baseConfig: config as Linter.Config<Linter.RulesRecord>,
useEslintrc: false,
cwd: path.resolve(process.cwd(), '../..'),
ignore: false,
})
for (const file of files) {
const filePath = path.resolve(process.cwd(), `./tests/${file}.${extension}`)
const code = fs.readFileSync(filePath).toString()
const isTS = ['ts', 'tsx'].includes(extension)
const result = await cli.lintText(code, {
filePath: isTS ? filePath : undefined,
})
expect(result).toMatchSnapshot()
}
}
Example #5
Source File: verify-code.ts From solita with Apache License 2.0 | 6 votes |
export async function verifySyntacticCorrectness(t: Test, ts: string) {
try {
const results: ESLint.LintResult[] = await eslint.lintText(ts)
for (const res of results) {
if (res.errorCount > 0) {
deepLog(
res.messages.map(
(x) => `${x.message} at ${x.line}:${x.column} (${x.nodeType})`
)
)
t.fail(`Found ${res.errorCount} errors via esbuild`)
}
}
} catch (err) {
t.error(err)
}
}
Example #6
Source File: verify-code.ts From solita with Apache License 2.0 | 6 votes |
eslint = new ESLint({
overrideConfig: {
plugins: ['@typescript-eslint'],
parser: '@typescript-eslint/parser',
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
globals: { Buffer: true },
},
})
Example #7
Source File: check-module-boundaries.ts From nx-dotnet with MIT License | 6 votes |
/**
* Loads module boundaries from eslintrc or .nx-dotnet.rc.json
* @param root Which file should be used when pulling from eslint
* @returns List of module boundaries
*/
export async function loadModuleBoundaries(
root: string,
host?: Tree,
): Promise<ModuleBoundaries> {
const configured = readConfig(host).moduleBoundaries;
if (!configured) {
const result = await new ESLint()
.calculateConfigForFile(`${root}/non-existant.ts`)
.catch(() =>
Promise.resolve({
rules: { '@nrwl/nx/enforce-module-boundaries': [] },
}),
);
const [, moduleBoundaryConfig] =
result.rules['@nrwl/nx/enforce-module-boundaries'] || [];
return moduleBoundaryConfig?.depConstraints ?? [];
} else {
return configured;
}
}
Example #8
Source File: examples.spec.ts From graphql-eslint with MIT License | 5 votes |
function countErrors(results: ESLint.LintResult[]): number {
return results.reduce<number>((acc, curr: { fatalErrorCount: number } & ESLint.LintResult) => {
if (curr.fatalErrorCount > 0) {
throw new Error('Found fatal error');
}
return acc + curr.errorCount;
}, 0);
}
Example #9
Source File: list-deprecations.ts From backstage with Apache License 2.0 | 5 votes |
export async function command(opts: OptionValues) {
const packages = await PackageGraph.listTargetPackages();
const eslint = new ESLint({
cwd: paths.targetDir,
overrideConfig: {
plugins: ['deprecation'],
rules: {
'deprecation/deprecation': 'error',
},
parserOptions: {
project: [paths.resolveTargetRoot('tsconfig.json')],
},
},
extensions: ['jsx', 'ts', 'tsx', 'mjs', 'cjs'],
});
const { stderr } = process;
if (stderr.isTTY) {
stderr.write('Initializing TypeScript...');
}
const deprecations = [];
for (const [index, pkg] of packages.entries()) {
const results = await eslint.lintFiles(joinPath(pkg.dir, 'src'));
for (const result of results) {
for (const message of result.messages) {
if (message.ruleId !== 'deprecation/deprecation') {
continue;
}
const path = relativePath(paths.targetRoot, result.filePath);
deprecations.push({
path,
message: message.message,
line: message.line,
column: message.column,
});
}
}
if (stderr.isTTY) {
stderr.clearLine(0);
stderr.cursorTo(0);
stderr.write(`Scanning packages ${index + 1}/${packages.length}`);
}
}
if (stderr.isTTY) {
stderr.clearLine(0);
stderr.cursorTo(0);
}
if (opts.json) {
console.log(JSON.stringify(deprecations, null, 2));
} else {
for (const d of deprecations) {
const location = `${d.path}:${d.line}:${d.column}`;
const wrappedMessage = d.message.replace(/\r?\n\s*/g, ' ');
console.log(`${location} - ${chalk.yellow(wrappedMessage)}`);
}
}
if (deprecations.length > 0) {
process.exit(1);
}
}
Example #10
Source File: sync.ts From g2plot-react with MIT License | 5 votes |
eslint = new ESLint({
extensions: ['.tsx'],
baseConfig: {
extends: ['@opd/eslint-config-pangu'],
},
fix: true,
})
Example #11
Source File: sync.ts From g2plot-vue with MIT License | 5 votes |
eslint = new ESLint({
extensions: ['.tsx'],
baseConfig: eslintConfig as any,
fix: true,
})
Example #12
Source File: wrap.ts From i18n-helper with MIT License | 5 votes |
eslintFormat = async (filePath: string) => {
const eslint = new ESLint({ fix: true });
const results = await eslint.lintFiles(filePath);
await ESLint.outputFixes(results);
}
Example #13
Source File: fix.ts From backstage with Apache License 2.0 | 4 votes |
export async function command() {
const pkgJsonPath = paths.resolveTarget('package.json');
const pkg = await fs.readJson(pkgJsonPath);
if (pkg.workspaces) {
throw new Error(
'Adding dependencies to the workspace root is not supported',
);
}
const packages = await PackageGraph.listTargetPackages();
const localPackageVersions = new Map(
packages.map(p => [p.packageJson.name, p.packageJson.version]),
);
const eslint = new ESLint({
cwd: paths.targetDir,
overrideConfig: {
plugins: ['monorepo'],
rules: {
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: [
`!${joinPath(paths.targetDir, 'src/**')}`,
joinPath(paths.targetDir, 'src/**/*.test.*'),
joinPath(paths.targetDir, 'src/**/*.stories.*'),
joinPath(paths.targetDir, 'src/setupTests.*'),
],
optionalDependencies: true,
peerDependencies: true,
bundledDependencies: true,
},
],
},
},
extensions: ['jsx', 'ts', 'tsx', 'mjs', 'cjs'],
});
const results = await eslint.lintFiles(['.']);
const addedDeps = new Set<string>();
const addedDevDeps = new Set<string>();
const removedDevDeps = new Set<string>();
for (const result of results) {
for (const message of result.messages) {
// Just in case
if (message.ruleId !== 'import/no-extraneous-dependencies') {
continue;
}
const match = message.message.match(/^'([^']*)' should be listed/);
if (!match) {
continue;
}
const packageName = match[1];
if (!localPackageVersions.has(packageName)) {
continue;
}
if (message.message.endsWith('not devDependencies.')) {
addedDeps.add(packageName);
removedDevDeps.add(packageName);
} else if (isTestPath(result.filePath)) {
addedDevDeps.add(packageName);
} else {
addedDeps.add(packageName);
}
}
}
if (addedDeps.size || addedDevDeps.size || removedDevDeps.size) {
for (const name of addedDeps) {
if (!pkg.dependencies) {
pkg.dependencies = {};
}
pkg.dependencies[name] = `^${localPackageVersions.get(name)}`;
}
for (const name of addedDevDeps) {
if (!pkg.devDependencies) {
pkg.devDependencies = {};
}
pkg.devDependencies[name] = `^${localPackageVersions.get(name)}`;
}
for (const name of removedDevDeps) {
delete pkg.devDependencies[name];
}
if (Object.keys(pkg.devDependencies).length === 0) {
delete pkg.devDependencies;
}
if (pkg.dependencies) {
pkg.dependencies = Object.fromEntries(
Object.entries(pkg.dependencies).sort(([a], [b]) => a.localeCompare(b)),
);
}
if (pkg.devDependencies) {
pkg.devDependencies = Object.fromEntries(
Object.entries(pkg.devDependencies).sort(([a], [b]) =>
a.localeCompare(b),
),
);
}
await fs.writeJson(pkgJsonPath, pkg, { spaces: 2 });
}
}
Example #14
Source File: main.ts From react-native-decompiler with GNU Affero General Public License v3.0 | 4 votes |
async function start() {
try {
const progressBar = ProgressBar.getInstance();
const cacheFileName = `${argValues.out}/${argValues.entry ?? 'null'}.cache`;
let startTime = performance.now();
fsExtra.ensureDirSync(argValues.out);
console.log('Reading file...');
const fileParserRouter = new FileParserRouter();
const modules = await fileParserRouter.route(argValues);
if (modules == null || modules.length === 0) {
console.error(`${chalk.red('[!]')} No modules were found!`);
console.error(`${chalk.red('[!]')} Possible reasons:`);
console.error(`${chalk.red('[!]')} - The React Native app is unbundled. If it is, export the "js-modules" folder from the app and provide it as the --js-modules argument`);
console.error(`${chalk.red('[!]')} - The bundle is a binary/encrypted file (ex. Facebook, Instagram). These files are not supported`);
console.error(`${chalk.red('[!]')} - The provided Webpack bundle input is not or does not contain the entrypoint bundle`);
console.error(`${chalk.red('[!]')} - The file provided is not a React Native or Webpack bundle.`);
process.exit(1);
}
if (argValues.entry != null && (!argValues.agressiveCache)) {
console.log('Entry module provided, filtering out unused modules');
const entryModuleDependencies = new Set<number>();
let lastDependenciesSize = 0;
entryModuleDependencies.add(argValues.entry);
while (lastDependenciesSize !== entryModuleDependencies.size) {
lastDependenciesSize = entryModuleDependencies.size;
entryModuleDependencies.forEach((moduleId) => {
const module = modules.find((mod) => mod?.moduleId === moduleId);
if (module) {
module.dependencies.forEach((dep) => entryModuleDependencies.add(dep));
}
});
}
modules.forEach((mod, i) => {
if (!entryModuleDependencies.has(mod.moduleId)) {
delete modules[i];
}
});
}
let nonIgnoredModules = modules.filter((mod) => argValues.decompileIgnored || !mod.ignored);
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Pre-parsing modules...');
progressBar.start(0, nonIgnoredModules.length);
nonIgnoredModules.forEach((module) => {
module.validate();
module.unpack();
progressBar.increment();
});
progressBar.stop();
console.log(`Took ${performance.now() - startTime}ms`);
if (!argValues.unpackOnly) {
startTime = performance.now();
console.log('Tagging...');
progressBar.start(0, nonIgnoredModules.length);
const taggerRouters = nonIgnoredModules.map((m) => new Router(taggerList, m, modules, argValues));
for (let pass = 1; pass <= taggerRouters[0].maxPass; pass += 1) {
taggerRouters.forEach((r) => r.runPass(pass));
if (pass === taggerRouters[0].maxPass) {
progressBar.increment();
}
}
progressBar.stop();
if (argValues.performance) {
console.log(`Traversal took ${Router.traverseTimeTaken}ms`);
console.log(Router.timeTaken);
Router.timeTaken = {};
Router.traverseTimeTaken = 0;
}
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Filtering out modules only depended on ignored modules...');
let modulesToIgnore: Module[] = [];
modulesToIgnore = calculateModulesToIgnore(argValues, modules);
while (modulesToIgnore.length) {
modulesToIgnore.forEach((mod) => {
mod.ignored = true;
});
modulesToIgnore = calculateModulesToIgnore(argValues, modules);
}
if (argValues.verbose) {
console.table(modules.map((mod) => {
const dependentModules = modules.filter((otherMod) => otherMod.dependencies.includes(mod.moduleId));
return {
// moduleId: mod.moduleId,
moduleName: mod.moduleName,
ignored: mod.ignored,
dependencies: mod.dependencies.filter((e) => e != null),
dependents: dependentModules.map((m) => m.moduleId),
};
}));
console.table(modules.filter((m) => !m.ignored || m.isNpmModule).map((mod) => {
const dependentModules = modules.filter((otherMod) => otherMod.dependencies.includes(mod.moduleId));
if (mod.isNpmModule && !dependentModules.filter((m) => !m.ignored).length) return null;
return {
// moduleId: mod.moduleId,
moduleName: mod.moduleName,
ignored: mod.ignored,
dependencies: mod.dependencies.filter((e) => e != null),
dependents: dependentModules.filter((m) => !m.ignored).map((m) => m.moduleId),
};
}).filter((e) => e != null));
}
nonIgnoredModules = modules.filter((mod) => argValues.decompileIgnored || !mod.ignored);
console.log(`${nonIgnoredModules.length} remain to be decompiled`);
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Decompiling...');
progressBar.start(0, nonIgnoredModules.length);
const editorRouters = nonIgnoredModules.map((m) => new Router(editorList, m, modules, argValues));
for (let pass = 1; pass <= editorRouters[0].maxPass; pass += 1) {
editorRouters.forEach((r) => r.runPass(pass));
}
const decompilerRouter = nonIgnoredModules.map((m) => new Router(decompilerList, m, modules, argValues));
for (let pass = 1; pass <= decompilerRouter[0].maxPass; pass += 1) {
decompilerRouter.forEach((r) => r.runPass(pass));
if (pass === decompilerRouter[0].maxPass) {
progressBar.increment();
}
}
progressBar.stop();
if (argValues.performance) {
console.log(`Traversal took ${Router.traverseTimeTaken}ms`);
console.log(`Recrawl took ${Router.recrawlTimeTaken}ms`);
console.log(Router.timeTaken);
}
console.log(`Took ${performance.now() - startTime}ms`);
}
startTime = performance.now();
console.log('Generating code...');
progressBar.start(0, nonIgnoredModules.length);
const eslint = new ESLint({
fix: true,
ignore: false,
useEslintrc: false,
extensions: ['.js', '.jsx'],
overrideConfig: eslintConfig,
});
const generatedFiles = await Promise.all(nonIgnoredModules.map(async (module) => {
if (module.previousRunChecksum === crypto.createHash('md5').update(JSON.stringify(module.moduleCode.body)).digest('hex')) return null;
const returnValue = {
name: module.moduleId,
extension: module.tags.includes('jsx') ? 'jsx' : 'js',
code: generator({
...module.originalFile.program,
type: 'Program',
body: module.moduleCode.body,
}).code,
};
if (!argValues.noEslint && !argValues.unpackOnly) {
try {
const lintedCode = await eslint.lintText(returnValue.code);
returnValue.code = lintedCode[0].output ?? returnValue.code;
} catch (e) {}
}
if (!argValues.noPrettier) {
try {
returnValue.code = prettier.format(returnValue.code, { parser: 'babel', singleQuote: true, printWidth: 180 });
} catch (e) {}
}
progressBar.increment();
return returnValue;
}));
progressBar.stop();
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Saving...');
progressBar.start(0, nonIgnoredModules.length);
generatedFiles.forEach((file) => {
if (file == null) return;
const filePath = `${argValues.out}/${file.name}.${file.extension}`;
if (!fsExtra.existsSync(filePath) || fsExtra.readFileSync(filePath, 'utf-8') !== file.code) {
fsExtra.writeFileSync(filePath, file.code);
}
progressBar.increment();
});
modules.forEach((m) => {
if (!m.isStatic) return;
const filePath = `${argValues.out}/${m.moduleId}.${m.tags.includes('css') ? 'css' : '?'}`;
if (!fsExtra.existsSync(filePath) || fsExtra.readFileSync(filePath, 'utf-8') !== m.staticContent) {
fsExtra.writeFileSync(filePath, m.staticContent);
}
});
progressBar.stop();
if (!fsExtra.existsSync(cacheFileName) || !argValues.agressiveCache) {
console.log('Writing to cache...');
await new CacheParse(argValues).writeCache(cacheFileName, modules);
}
console.log(`Took ${performance.now() - startTime}ms`);
console.log('Done!');
} catch (e) {
console.error(`${chalk.red('[!]')} Error occurred! You should probably report this.`);
console.error(e);
process.exit(1);
}
}
Example #15
Source File: main.ts From react-native-decompiler with GNU Affero General Public License v3.0 | 4 votes |
async function start() {
try {
const progressBar = ProgressBar.getInstance();
const cacheFileName = `${argValues.out}/${argValues.entry ?? 'null'}.cache`;
let startTime = performance.now();
fsExtra.ensureDirSync(argValues.out);
if (!fsExtra.existsSync(argValues.in)) {
console.error(`${chalk.red('[!]')} "${argValues.in}" does not exist!"`);
process.exit(1);
}
console.log('Reading file...');
const fileParserRouter = new FileParserRouter();
const modules = await fileParserRouter.route(argValues);
if (modules == null || modules.length === 0) {
console.error(`${chalk.red('[!]')} No modules were found!`);
console.error(`${chalk.red('[!]')} Possible reasons:`);
console.error(`${chalk.red('[!]')} - The React Native app is unbundled. If it is, export the "js-modules" folder from the app and provide it as the --js-modules argument`);
console.error(`${chalk.red('[!]')} - The bundle is a Hermes/binary file (ex. Facebook, Instagram). These files are not supported`);
console.error(`${chalk.red('[!]')} - The provided Webpack bundle input is not or does not contain the entrypoint bundle`);
console.error(`${chalk.red('[!]')} - The provided Webpack bundle was built from V5, which is not supported`);
console.error(`${chalk.red('[!]')} - The file provided is not a React Native or Webpack bundle.`);
process.exit(1);
}
if (argValues.entry != null && (!argValues.agressiveCache)) {
console.log('Entry module provided, filtering out unused modules');
const entryModuleDependencies = new Set<number>();
let lastDependenciesSize = 0;
entryModuleDependencies.add(argValues.entry);
while (lastDependenciesSize !== entryModuleDependencies.size) {
lastDependenciesSize = entryModuleDependencies.size;
entryModuleDependencies.forEach((moduleId) => {
const module = modules.find((mod) => mod?.moduleId === moduleId);
if (module) {
module.dependencies.forEach((dep) => entryModuleDependencies.add(dep));
}
});
}
modules.forEach((mod, i) => {
if (!entryModuleDependencies.has(mod.moduleId)) {
delete modules[i];
}
});
}
let nonIgnoredModules = modules.filter((mod) => argValues.decompileIgnored || !mod.ignored);
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Pre-parsing modules...');
progressBar.start(0, nonIgnoredModules.length);
nonIgnoredModules.forEach((module) => {
module.validate();
module.unpack();
progressBar.increment();
});
progressBar.stop();
console.log(`Took ${performance.now() - startTime}ms`);
if (!argValues.unpackOnly) {
startTime = performance.now();
console.log('Tagging...');
progressBar.start(0, nonIgnoredModules.length);
const taggerRouters = nonIgnoredModules.map((m) => new Router(taggerList, m, modules, argValues));
for (let pass = 1; pass <= taggerRouters[0].maxPass; pass += 1) {
taggerRouters.forEach((r) => r.runPass(pass));
if (pass === taggerRouters[0].maxPass) {
progressBar.increment();
}
}
progressBar.stop();
if (argValues.performance) {
console.log(`Traversal took ${Router.traverseTimeTaken}ms`);
console.log(Router.timeTaken);
Router.timeTaken = {};
Router.traverseTimeTaken = 0;
}
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Filtering out modules only depended on ignored modules...');
let modulesToIgnore: Module[] = [];
modulesToIgnore = calculateModulesToIgnore(argValues, modules);
while (modulesToIgnore.length) {
modulesToIgnore.forEach((mod) => {
mod.ignored = true;
});
modulesToIgnore = calculateModulesToIgnore(argValues, modules);
}
if (argValues.verbose) {
console.table(modules.map((mod) => {
const dependentModules = modules.filter((otherMod) => otherMod.dependencies.includes(mod.moduleId));
return {
// moduleId: mod.moduleId,
moduleName: mod.moduleName,
ignored: mod.ignored,
dependencies: mod.dependencies.filter((e) => e != null),
dependents: dependentModules.map((m) => m.moduleId),
};
}));
console.table(modules.filter((m) => !m.ignored || m.isNpmModule).map((mod) => {
const dependentModules = modules.filter((otherMod) => otherMod.dependencies.includes(mod.moduleId));
if (mod.isNpmModule && !dependentModules.filter((m) => !m.ignored).length) return null;
return {
// moduleId: mod.moduleId,
moduleName: mod.moduleName,
ignored: mod.ignored,
dependencies: mod.dependencies.filter((e) => e != null),
dependents: dependentModules.filter((m) => !m.ignored).map((m) => m.moduleId),
};
}).filter((e) => e != null));
}
nonIgnoredModules = modules.filter((mod) => argValues.decompileIgnored || !mod.ignored);
console.log(`${nonIgnoredModules.length} remain to be decompiled`);
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Decompiling...');
progressBar.start(0, nonIgnoredModules.length);
const editorRouters = nonIgnoredModules.map((m) => new Router(editorList, m, modules, argValues));
for (let pass = 1; pass <= editorRouters[0].maxPass; pass += 1) {
editorRouters.forEach((r) => r.runPass(pass));
}
const decompilerRouter = nonIgnoredModules.map((m) => new Router(decompilerList, m, modules, argValues));
for (let pass = 1; pass <= decompilerRouter[0].maxPass; pass += 1) {
decompilerRouter.forEach((r) => r.runPass(pass));
if (pass === decompilerRouter[0].maxPass) {
progressBar.increment();
}
}
progressBar.stop();
if (argValues.performance) {
console.log(`Traversal took ${Router.traverseTimeTaken}ms`);
console.log(`Recrawl took ${Router.recrawlTimeTaken}ms`);
console.log(Router.timeTaken);
}
console.log(`Took ${performance.now() - startTime}ms`);
}
startTime = performance.now();
console.log('Generating code...');
progressBar.start(0, nonIgnoredModules.length);
const eslint = new ESLint({
fix: true,
ignore: false,
useEslintrc: false,
extensions: ['.js', '.jsx'],
overrideConfig: eslintConfig,
});
const generatedFiles = await Promise.all(nonIgnoredModules.map(async (module) => {
if (module.previousRunChecksum === crypto.createHash('md5').update(JSON.stringify(module.moduleCode.body)).digest('hex')) return null;
const returnValue = {
name: module.moduleId,
extension: module.tags.includes('jsx') ? 'jsx' : 'js',
code: generator({
...module.originalFile.program,
type: 'Program',
body: module.moduleCode.body,
}).code,
};
if (!argValues.noEslint && !argValues.unpackOnly) {
try {
const lintedCode = await eslint.lintText(returnValue.code);
returnValue.code = lintedCode[0].output ?? returnValue.code;
} catch (e) {}
}
if (!argValues.noPrettier) {
try {
returnValue.code = prettier.format(returnValue.code, { parser: 'babel', singleQuote: true, printWidth: 180 });
} catch (e) {}
}
progressBar.increment();
return returnValue;
}));
progressBar.stop();
console.log(`Took ${performance.now() - startTime}ms`);
startTime = performance.now();
console.log('Saving...');
progressBar.start(0, nonIgnoredModules.length);
generatedFiles.forEach((file) => {
if (file == null) return;
const filePath = `${argValues.out}/${file.name}.${file.extension}`;
if (!fsExtra.existsSync(filePath) || fsExtra.readFileSync(filePath, 'utf-8') !== file.code) {
fsExtra.writeFileSync(filePath, file.code);
}
progressBar.increment();
});
modules.forEach((m) => {
if (!m.isStatic) return;
const filePath = `${argValues.out}/${m.moduleId}.${m.tags.includes('css') ? 'css' : '?'}`;
if (!fsExtra.existsSync(filePath) || fsExtra.readFileSync(filePath, 'utf-8') !== m.staticContent) {
fsExtra.writeFileSync(filePath, m.staticContent);
}
});
progressBar.stop();
if (!fsExtra.existsSync(cacheFileName) || !argValues.agressiveCache) {
console.log('Writing to cache...');
await new CacheParse(argValues).writeCache(cacheFileName, modules);
}
console.log(`Took ${performance.now() - startTime}ms`);
console.log('Done!');
} catch (e) {
console.error(`${chalk.red('[!]')} Error occurred! You should probably report this.`);
console.error(e);
process.exit(1);
}
}