Skip to content

Commit

Permalink
fix(core): swc should be an optional peer dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
AgentEnder committed May 24, 2022
1 parent 85485cc commit 467621b
Show file tree
Hide file tree
Showing 12 changed files with 147 additions and 63 deletions.
7 changes: 4 additions & 3 deletions packages/devkit/src/utils/package-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ export function addDependenciesToPackageJson(

return json;
});
return (): void => {
installPackagesTask(tree);
};
}
return (): void => {
installPackagesTask(tree);
};
return () => {};
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/js/src/utils/swc/add-swc-dependencies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { addDependenciesToPackageJson, Tree } from '@nrwl/devkit';
import { swcCliVersion, swcCoreVersion, swcHelpersVersion } from '../versions';

export function addSwcDependencies(tree: Tree) {
addDependenciesToPackageJson(
return addDependenciesToPackageJson(
tree,
{
'@swc/helpers': swcHelpersVersion,
Expand Down
3 changes: 2 additions & 1 deletion packages/js/src/utils/versions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { swcCoreVersion } from 'nx/src/utils/versions';

export const nxVersion = require('../../package.json').version;

export const swcCoreVersion = '~1.2.143';
export const swcCliVersion = '~0.1.55';
export const swcHelpersVersion = '~0.3.3';
1 change: 1 addition & 0 deletions packages/linter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@nrwl/devkit": "file:../devkit",
"@nrwl/jest": "file:../jest",
"@phenomnomnominal/tsquery": "4.1.1",
"nx": "file:../nx",
"tmp": "~0.2.1",
"tslib": "^2.3.0"
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
addDependenciesToPackageJson,
addProjectConfiguration,
convertNxGenerator,
formatFiles,
Expand All @@ -14,6 +15,7 @@ import { addPropertyToJestConfig, jestProjectGenerator } from '@nrwl/jest';
import { getRelativePathToRootTsConfig } from '@nrwl/workspace/src/utilities/typescript';
import { join } from 'path';
import { workspaceLintPluginDir } from '../../utils/workspace-lint-rules';
import { swcCoreVersion, swcNodeVersion } from 'nx/src/utils/versions';

export const WORKSPACE_RULES_PROJECT_NAME = 'eslint-rules';

Expand Down Expand Up @@ -54,14 +56,21 @@ export async function lintWorkspaceRulesProjectGenerator(tree: Tree) {
});

// Add jest to the project and return installation task
const jestInstallationTask = await jestProjectGenerator(tree, {
const installTask = await jestProjectGenerator(tree, {
project: WORKSPACE_RULES_PROJECT_NAME,
supportTsx: false,
skipSerializers: true,
setupFile: 'none',
compiler: 'tsc',
});

// Add swc dependencies
addDependenciesToPackageJson(
tree,
{},
{ '@swc-node/register': swcNodeVersion, '@swc/core': swcCoreVersion }
);

// Add extra config to the jest.config.ts file to allow ESLint 8 exports mapping to work with jest
addPropertyToJestConfig(
tree,
Expand All @@ -74,7 +83,7 @@ export async function lintWorkspaceRulesProjectGenerator(tree: Tree) {

await formatFiles(tree);

return jestInstallationTask;
return installTask;
}

export const lintWorkspaceRulesProjectSchematic = convertNxGenerator(
Expand Down
25 changes: 16 additions & 9 deletions packages/nx-plugin/src/generators/plugin/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
import type { Tree } from '@nrwl/devkit';
import {
addDependenciesToPackageJson,
convertNxGenerator,
formatFiles,
generateFiles,
GeneratorCallback,
getWorkspaceLayout,
installPackagesTask,
joinPathFragments,
names,
normalizePath,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
} from '@nrwl/devkit';
import type { Schema } from './schema';
import { nxVersion } from '../../utils/versions';
import * as path from 'path';
import { libraryGenerator } from '@nrwl/js';
import { addSwcDependencies } from '@nrwl/js/src/utils/swc/add-swc-dependencies';
import { swcNodeVersion } from 'nx/src/utils/versions';
import * as path from 'path';

import { nxVersion } from '../../utils/versions';
import { e2eProjectGenerator } from '../e2e-project/e2e';
import { generatorGenerator } from '../generator/generator';
import { executorGenerator } from '../executor/executor';
import { runTasksInSerial } from '@nrwl/workspace/src/utilities/run-tasks-in-serial';
import { generatorGenerator } from '../generator/generator';

import type { Schema } from './schema';
interface NormalizedSchema extends Schema {
name: string;
fileName: string;
Expand Down Expand Up @@ -135,17 +138,21 @@ export async function pluginGenerator(host: Tree, schema: Schema) {

tasks.push(libraryTask);

const installTask = addDependenciesToPackageJson(
addDependenciesToPackageJson(
host,
{},
{
'@nrwl/devkit': nxVersion,
'@nrwl/jest': nxVersion,
'@nrwl/js': nxVersion,
'@swc-node/register': swcNodeVersion,
tslib: '^2.0.0',
}
);
tasks.push(installTask);

// Ensures Swc Deps are installed to handle running
// local plugin generators and executors
addSwcDependencies(host);

await addFiles(host, options);
updateWorkspaceJson(host, options);
Expand All @@ -160,7 +167,7 @@ export async function pluginGenerator(host: Tree, schema: Schema) {

await formatFiles(host);

return runTasksInSerial(...tasks);
return () => installPackagesTask(host);
}

export default pluginGenerator;
Expand Down
14 changes: 12 additions & 2 deletions packages/nx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@
"homepage": "https://nx.dev",
"dependencies": {
"@parcel/watcher": "2.0.4",
"@swc-node/register": "^1.4.2",
"@swc/core": "^1.2.173",
"chalk": "4.1.0",
"chokidar": "^3.5.1",
"cli-cursor": "3.1.0",
Expand Down Expand Up @@ -61,6 +59,18 @@
"yargs": "^17.4.0",
"yargs-parser": "21.0.1"
},
"peerDependencies": {
"@swc-node/register": "^1.4.2",
"@swc/core": "^1.2.173"
},
"peerDependenciesMeta": {
"@swc-node/register": {
"optional": true
},
"@swc/core": {
"optional": true
}
},
"nx-migrations": {
"migrations": "./migrations.json",
"packageGroup": [
Expand Down
105 changes: 94 additions & 11 deletions packages/nx/src/utils/register.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { join } from 'path';
import { logger, NX_PREFIX, stripIndent } from './logger';

/**
* Optionally, if swc-node and tsconfig-paths are available in the current workspace, apply the require
Expand All @@ -7,22 +8,72 @@ import { join } from 'path';
* If ts-node and tsconfig-paths are not available, the user can still provide an index.js file in
* the root of their project and the fundamentals will still work (but
* workspace path mapping will not, for example).
*
* @returns cleanup function
*/
export const registerTsProject = (
path: string,
configFilename = 'tsconfig.json'
) => {
// These are requires to prevent it from registering when it shouldn't
const { register } = require('@swc-node/register/register');
const {
readDefaultTsConfig,
} = require('@swc-node/register/read-default-tsconfig');
): (() => void) => {
const cleanupFunctions: (() => void)[] = [];

// Function to register transpiler that returns cleanup function
let registerTranspiler: () => () => void;

const tsConfigPath = join(path, configFilename);
cleanupFunctions.push(registerTsConfigPaths(tsConfigPath));

const swcNodeInstalled = packageIsInstalled('@swc-node/register');
if (swcNodeInstalled) {
// These are requires to prevent it from registering when it shouldn't
const { register } =
require('@swc-node/register/register') as typeof import('@swc-node/register/register');
const {
readDefaultTsConfig,
} = require('@swc-node/register/read-default-tsconfig');

try {
const tsConfigPath = join(path, configFilename);
const tsConfig = readDefaultTsConfig(tsConfigPath);
register(tsConfig);
registerTranspiler = () => register(tsConfig);
} else {
// We can fall back on ts-node if its available
const tsNodeInstalled = packageIsInstalled('ts-node/register');
if (tsNodeInstalled) {
warnTsNodeUsage();
const { register } =
require('ts-node/register') as typeof import('ts-node');

// ts-node doesn't provide a cleanup method
registerTranspiler = () => {
register({
project: tsConfigPath,
transpileOnly: true,
});
return () => {};
};
}
}

if (registerTranspiler) {
cleanupFunctions.push(registerTranspiler());
} else {
warnNoTranspiler();
}

// Overall cleanup method cleans up tsconfig path resolution
// as well as ts transpiler
return () => {
for (const f of cleanupFunctions) {
f();
}
};
};

/**
* @param tsConfigPath Adds the paths from a tsconfig file into node resolutions
* @returns cleanup function
*/
export function registerTsConfigPaths(tsConfigPath): () => void {
try {
/**
* Load the ts config from the source project
*/
Expand All @@ -38,6 +89,38 @@ export const registerTsProject = (
paths: tsConfigResult.paths,
});
}
} catch (err) {}
} catch (err) {
warnNoTsconfigPaths();
}
return () => {};
};
}

function warnTsNodeUsage() {
logger.warn(
stripIndent(`${NX_PREFIX} Falling back to ts-node for local typescript execution. This may be a little slower.
- To fix this, ensure @swc-node/register and @swc/core have been installed`)
);
}

function warnNoTsconfigPaths() {
logger.warn(
stripIndent(`${NX_PREFIX} Unable to load tsconfig-paths, workspace libraries may be inaccessible.
- To fix this, install tsconfig-paths with npm/yarn/pnpm`)
);
}

function warnNoTranspiler() {
logger.warn(
stripIndent(`${NX_PREFIX} Unable to locate swc-node or ts-node. Nx will be unable to run local ts files without transpiling.
- To fix this, ensure @swc-node/register and @swc/core have been installed`)
);
}

function packageIsInstalled(m: string) {
try {
const p = require.resolve(m);
return true;
} catch {
return false;
}
}
2 changes: 2 additions & 0 deletions packages/nx/src/utils/versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,5 @@ export const tslintVersion = '~6.1.0';
export const typescriptESLintVersion = '~5.18.0';
export const eslintVersion = '~8.12.0';
export const eslintConfigPrettierVersion = '8.1.0';
export const swcNodeVersion = '^1.4.2';
export const swcCoreVersion = '^1.2.173';
32 changes: 1 addition & 31 deletions packages/workspace/src/utilities/plugins/models.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1 @@
export interface PluginGenerator {
factory: string;
schema: string;
description: string;
aliases: string;
hidden: boolean;
}

export interface PluginExecutor {
implementation: string;
schema: string;
description: string;
}

export interface PluginCapabilities {
name: string;
executors: { [name: string]: PluginExecutor };
generators: { [name: string]: PluginGenerator };
}

export interface CorePlugin {
name: string;
capabilities: 'executors' | 'generators' | 'executors,generators';
link?: string;
}

export interface CommunityPlugin {
name: string;
url: string;
description: string;
}
export * from 'nx/src/utils/plugins/models';
4 changes: 2 additions & 2 deletions scripts/depcheck/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ const argv = require('yargs')
.map((name) => ({ name }))
.map(async (project) => {
const projectPath = join(packagesDirectory, project.name);
const { dependencies } = JSON.parse(
const { dependencies, peerDependencies } = JSON.parse(
readFileSync(`${projectPath}/package.json`).toString()
);

const missing = argv.missing
? await getMissingDependencies(
project.name,
projectPath,
dependencies,
{ ...dependencies, ...(peerDependencies || {}) },
argv.verbose
)
: [];
Expand Down
2 changes: 1 addition & 1 deletion scripts/depcheck/missing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ const IGNORE_MATCHES = {
'@angular-devkit/core',
'@angular-devkit/architect',
'@angular/cli',
'ts-node', // We *may* fall back on ts-node, but we want to encourage the use of @swc-node instead so we don't explicitly list ts-node as an optional dep
],
web: [
// we don't want to bloat the install of @nrwl/web by including @swc/core and swc-loader as a dependency.
Expand All @@ -121,7 +122,6 @@ const IGNORE_MATCHES = {
'@nrwl/jest',
'@nrwl/linter',
'tsconfig-paths',
'@swc-node/register',
],
nest: ['semver'],
'make-angular-cli-faster': ['@angular/core'],
Expand Down

0 comments on commit 467621b

Please sign in to comment.