Skip to content

Commit

Permalink
fix: eslint needs extra configs to resolve paths correctly
Browse files Browse the repository at this point in the history
Merged the release CI fixes from another branch here as that one is failing for unknow reasons

Fix over-agressive shortest imports
  • Loading branch information
SimeonC committed Oct 2, 2023
1 parent c750302 commit 26975cf
Show file tree
Hide file tree
Showing 11 changed files with 135 additions and 68 deletions.
6 changes: 3 additions & 3 deletions .github/setup/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ runs:

- name: Setup branch for NX (main)
shell: bash
if: github.ref == 'refs/head/main'
if: github.ref == 'refs/heads/main'
run: git branch -u origin/main main

- name: Setup branch for NX (!main)
shell: bash
if: github.ref != 'refs/head/main'
if: github.ref != 'refs/heads/main'
run: git branch --track main origin/main

- name: Install without scripts 🔧
Expand All @@ -43,4 +43,4 @@ runs:

- name: Build 🔨
shell: bash
run: npm run build
run: npm run build:ci
2 changes: 1 addition & 1 deletion .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
run: |
git branch --track main origin/main
npm ci --prefer-offline --silent
npm run build
npm run build:ci
- name: Deploy 🚀
uses: JamesIves/[email protected]
Expand Down
3 changes: 0 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ jobs:

- uses: ./.github/setup

- name: Build
run: npm run build

- name: Run Tests
run: npm test

Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
"test:watch": "nx run-many --target=test:watch",
"start": "start-storybook -p 6006",
"build": "nx affected --target=build",
"build:ci": "nx run-many --target=build",
"build:docs": "build-storybook",
"prepare": "husky install && npm run build",
"prepare": "husky install && npm run build:ci",
"all-upgrade": "npm-upgrade && lerna exec --concurrency 1 -- npm-upgrade"
},
"workspaces": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ export function buildBaseTypescript(
},
},
],
'@tablecheck/prefer-shortest-import': 'error',
...forcedRules,
},
};
Expand Down
8 changes: 8 additions & 0 deletions packages/eslint-plugin/__tests__/shortestImport.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,14 @@ ruleTester.run('shortestImport', rule, {
path: '~/feature1/slice2/second',
filename: './test_src/feature1/slice1/inner1/index.ts',
},
{
path: '@node/module',
filename: './test_src/feature1/slice1/inner1/index.ts',
},
{
path: 'react',
filename: './test_src/feature1/slice1/inner1/index.ts',
},
]),
invalid: convertPathCaseToCodeCase([
{
Expand Down
12 changes: 11 additions & 1 deletion packages/eslint-plugin/src/shortestImport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,20 @@ export const shortestImport: TSESLint.RuleModule<
return relativeLength <= aliasLength;
}

function isImportNodeModule(importPath: string) {
if (importPath.startsWith('@')) return true;
const isPathMapping = Object.keys(pathMappings).some((key) =>
importPath.startsWith(key),
);
if (isPathMapping) return false;
return !importPath.startsWith('.') && !importPath.startsWith('/');
}

function checkAndFixImport(node: ImportExpression | ImportDeclaration) {
if (node.source.type !== AST_NODE_TYPES.Literal) return;
const importPath = node.source.value;
if (typeof importPath !== 'string') return;
if (typeof importPath !== 'string' || isImportNodeModule(importPath))
return;
const resolvedImport = resolveImport(importPath);
const relativePath = getRelativeImport(importPath, resolvedImport);
const aliasPath = getPathAliasImport(resolvedImport);
Expand Down
43 changes: 43 additions & 0 deletions packages/nx/src/generators/quality/eslintConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import * as path from 'path';

import { Tree } from '@nx/devkit';
import { getNxProjectRoot, outputPrettyFile } from '@tablecheck/frontend-utils';
import * as fs from 'fs-extra';

function getConfigs(projectRoot: string) {
const mapToPath = (filename: string) => path.join(projectRoot, filename);
const nxAppConfigs = ['tsconfig.app.json', 'tsconfig.spec.json'].map(
mapToPath,
);
const defaultConfigs = ['tsconfig.base.json', 'tsconfig.json'].map(mapToPath);
if (nxAppConfigs.every((config) => fs.existsSync(config))) {
return nxAppConfigs;
}
return defaultConfigs.filter((config) => fs.existsSync(config));
}

export function generateEslintConfig(tree: Tree, projectName: string) {
const { projectRoot } = getNxProjectRoot(tree, projectName);
const projectTsConfigs =
getConfigs(projectRoot)
.map((tsConfig) => path.relative(tree.root, tsConfig))
.join(',') ||
'/* could not detect tsconfig.json files, manually set them here */';
const fileContent = `
module.exports = {
extends: ['@tablecheck/eslint-config'],
parserOptions: {
project: [${projectTsConfigs}],
},
settings: {
'import/resolver': {
typescript: {
project: [${projectTsConfigs}],
},
},
},
rules: {},
};
`;
outputPrettyFile(path.join(projectRoot, '.eslintrc.cjs'), fileContent);
}
7 changes: 0 additions & 7 deletions packages/nx/src/generators/quality/files/.eslintrc.cjs

This file was deleted.

57 changes: 5 additions & 52 deletions packages/nx/src/generators/quality/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ import {
addDependenciesToPackageJson,
Tree,
updateJson,
addProjectConfiguration,
readProjectConfiguration,
updateProjectConfiguration,
} from '@nx/devkit';
import { getNxProjectRoot } from '@tablecheck/frontend-utils';
import merge from 'lodash/merge';
import { PackageJson } from 'type-fest';

import { getLatestVersions } from '../../utils/dependencies';
Expand All @@ -21,53 +16,8 @@ import generateFileTypes from '../ts-file-types/generator';
import { FileTypesGeneratorSchema } from '../ts-file-types/schema';
import generateConfig from '../ts-node-config/generator';

function updateProjectConfig(tree: Tree, projectName: string) {
const { projectSourceRoot, projectRoot } = getNxProjectRoot(
tree,
projectName,
);
const lintTarget = {
executor: '@tablecheck/nx:quality',
outputs: ['{options.outputFile}'],
options: {
lintFilePatterns: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'].map(
(pattern) =>
path.relative(projectRoot, path.join(projectSourceRoot, pattern)),
),
},
};
const lintFormatTarget = merge({}, lintTarget, {
options: {
fix: true,
},
});
try {
const projectConfig = readProjectConfiguration(tree, projectName);
updateProjectConfiguration(
tree,
projectName,
merge(projectConfig, {
targets: {
quality: lintTarget,
'quality:format': lintFormatTarget,
},
}),
);
} catch (e) {
console.error(
'Failed to detect existing project config, generating new project.json to run executors',
e,
);
addProjectConfiguration(tree, projectName, {
root: '.',
sourceRoot: 'src',
targets: {
quality: lintTarget,
'quality:format': lintFormatTarget,
},
});
}
}
import { generateEslintConfig } from './eslintConfig';
import { updateProjectConfig } from './projectConfig';

export async function qualityGenerator(
tree: Tree,
Expand All @@ -85,6 +35,8 @@ export async function qualityGenerator(
'@tablecheck/commitlint-config',
'@tablecheck/eslint-config',
'@tablecheck/prettier-config',
'@typescript-eslint/eslint-plugin',
'@typescript-eslint/parser',
]),
)();
updateJson(tree, 'package.json', (json: PackageJson) => {
Expand All @@ -105,6 +57,7 @@ export async function qualityGenerator(
path.relative(process.cwd(), tree.root),
{},
);
generateEslintConfig(tree, schema.project);
execSync('npx husky install', {
cwd: process.cwd(),
stdio: 'inherit',
Expand Down
61 changes: 61 additions & 0 deletions packages/nx/src/generators/quality/projectConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import * as path from 'path';

import {
Tree,
addProjectConfiguration,
readProjectConfiguration,
updateProjectConfiguration,
} from '@nx/devkit';
import { getNxProjectRoot } from '@tablecheck/frontend-utils';
import merge from 'lodash/merge';

export function updateProjectConfig(tree: Tree, projectName: string) {
const { projectSourceRoot, projectRoot } = getNxProjectRoot(
tree,
projectName,
);
const lintTarget = {
executor: '@tablecheck/nx:quality',
outputs: ['{options.outputFile}'],
options: {
lintFilePatterns: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'].map(
(pattern) =>
path.join(
'{projectRoot}',
path.relative(projectRoot, path.join(projectSourceRoot, pattern)),
),
),
},
};
const lintFormatTarget = merge({}, lintTarget, {
options: {
fix: true,
},
});
try {
const projectConfig = readProjectConfiguration(tree, projectName);
updateProjectConfiguration(
tree,
projectName,
merge(projectConfig, {
targets: {
quality: lintTarget,
'quality:format': lintFormatTarget,
},
}),
);
} catch (e) {
console.error(
'Failed to detect existing project config, generating new project.json to run executors',
e,
);
addProjectConfiguration(tree, projectName, {
root: '.',
sourceRoot: 'src',
targets: {
quality: lintTarget,
'quality:format': lintFormatTarget,
},
});
}
}

0 comments on commit 26975cf

Please sign in to comment.