Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(js): refactor ensurePackage #15074

Merged
merged 1 commit into from
Feb 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 69 additions & 36 deletions docs/generated/devkit/nrwl_devkit.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ It only uses language primitives and immutable objects
- [output](../../devkit/documents/nrwl_devkit#output)
- [workspaceRoot](../../devkit/documents/nrwl_devkit#workspaceroot)

### Functions
### Other Functions

- [addDependenciesToPackageJson](../../devkit/documents/nrwl_devkit#adddependenciestopackagejson)
- [addProjectConfiguration](../../devkit/documents/nrwl_devkit#addprojectconfiguration)
Expand All @@ -149,7 +149,6 @@ It only uses language primitives and immutable objects
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
- [detectWorkspaceScope](../../devkit/documents/nrwl_devkit#detectworkspacescope)
- [ensurePackage](../../devkit/documents/nrwl_devkit#ensurepackage)
- [extractLayoutDirectory](../../devkit/documents/nrwl_devkit#extractlayoutdirectory)
- [formatFiles](../../devkit/documents/nrwl_devkit#formatfiles)
- [generateFiles](../../devkit/documents/nrwl_devkit#generatefiles)
Expand Down Expand Up @@ -203,6 +202,10 @@ It only uses language primitives and immutable objects
- [writeJson](../../devkit/documents/nrwl_devkit#writejson)
- [writeJsonFile](../../devkit/documents/nrwl_devkit#writejsonfile)

### Utils Functions

- [ensurePackage](../../devkit/documents/nrwl_devkit#ensurepackage)

## Project Graph Enumerations

### DependencyType
Expand Down Expand Up @@ -823,7 +826,7 @@ Implementation of a target of a project that handles multiple projects to be bat

• **workspaceRoot**: `string`

## Functions
## Other Functions

### addDependenciesToPackageJson

Expand Down Expand Up @@ -1182,39 +1185,6 @@ Detect workspace scope from the package.json name

---

### ensurePackage

▸ **ensurePackage**(`tree`, `pkg`, `requiredVersion`, `options?`): `void`

Ensure that dependencies and devDependencies from package.json are installed at the required versions.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

This will check that @nrwl/jest@<nxVersion> exists in devDependencies.
If it exists then function returns, otherwise it will install the package before continuing.
When running with --dryRun, the function will throw when dependencies are missing.

#### Parameters

| Name | Type | Description |
| :------------------------ | :------------------------------------------------ | :----------------------------------------------------------------- |
| `tree` | [`Tree`](../../devkit/documents/nrwl_devkit#tree) | the file system tree |
| `pkg` | `string` | the package to check (e.g. @nrwl/jest) |
| `requiredVersion` | `string` | the version or semver range to check (e.g. ~1.0.0, >=1.0.0 <2.0.0) |
| `options` | `Object` | |
| `options.dev?` | `boolean` | - |
| `options.throwOnMissing?` | `boolean` | - |

#### Returns

`void`

---

### extractLayoutDirectory

▸ **extractLayoutDirectory**(`directory`): `Object`
Expand Down Expand Up @@ -2431,3 +2401,66 @@ Serializes the given data to JSON and writes it to a file.
#### Returns

`void`

---

## Utils Functions

### ensurePackage

▸ **ensurePackage**(`tree`, `pkg`, `requiredVersion`, `options?`): `void`

**`deprecated`** Use the other function signature without a Tree

Use a package that has not been installed as a dependency.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

This install the @nrwl/jest@<nxVersion> and return the module
When running with --dryRun, the function will throw when dependencies are missing.

#### Parameters

| Name | Type | Description |
| :------------------------ | :------------------------------------------------ | :----------------------------------------------------------------- |
| `tree` | [`Tree`](../../devkit/documents/nrwl_devkit#tree) | the file system tree |
| `pkg` | `string` | the package to check (e.g. @nrwl/jest) |
| `requiredVersion` | `string` | the version or semver range to check (e.g. ~1.0.0, >=1.0.0 <2.0.0) |
| `options?` | `Object` | - |
| `options.dev?` | `boolean` | - |
| `options.throwOnMissing?` | `boolean` | - |

#### Returns

`void`

▸ **ensurePackage**<`T`\>(`pkg`, `version`): `T`

Ensure that dependencies and devDependencies from package.json are installed at the required versions.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

#### Type parameters

| Name | Type |
| :--- | :------------------------ |
| `T` | extends `unknown` = `any` |

#### Parameters

| Name | Type | Description |
| :-------- | :------- | :---------------------------------------------------------- |
| `pkg` | `string` | the package to install and require |
| `version` | `string` | the version to install if the package doesn't exist already |

#### Returns

`T`
105 changes: 69 additions & 36 deletions docs/generated/packages/devkit/documents/nrwl_devkit.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ It only uses language primitives and immutable objects
- [output](../../devkit/documents/nrwl_devkit#output)
- [workspaceRoot](../../devkit/documents/nrwl_devkit#workspaceroot)

### Functions
### Other Functions

- [addDependenciesToPackageJson](../../devkit/documents/nrwl_devkit#adddependenciestopackagejson)
- [addProjectConfiguration](../../devkit/documents/nrwl_devkit#addprojectconfiguration)
Expand All @@ -149,7 +149,6 @@ It only uses language primitives and immutable objects
- [defaultTasksRunner](../../devkit/documents/nrwl_devkit#defaulttasksrunner)
- [detectPackageManager](../../devkit/documents/nrwl_devkit#detectpackagemanager)
- [detectWorkspaceScope](../../devkit/documents/nrwl_devkit#detectworkspacescope)
- [ensurePackage](../../devkit/documents/nrwl_devkit#ensurepackage)
- [extractLayoutDirectory](../../devkit/documents/nrwl_devkit#extractlayoutdirectory)
- [formatFiles](../../devkit/documents/nrwl_devkit#formatfiles)
- [generateFiles](../../devkit/documents/nrwl_devkit#generatefiles)
Expand Down Expand Up @@ -203,6 +202,10 @@ It only uses language primitives and immutable objects
- [writeJson](../../devkit/documents/nrwl_devkit#writejson)
- [writeJsonFile](../../devkit/documents/nrwl_devkit#writejsonfile)

### Utils Functions

- [ensurePackage](../../devkit/documents/nrwl_devkit#ensurepackage)

## Project Graph Enumerations

### DependencyType
Expand Down Expand Up @@ -823,7 +826,7 @@ Implementation of a target of a project that handles multiple projects to be bat

• **workspaceRoot**: `string`

## Functions
## Other Functions

### addDependenciesToPackageJson

Expand Down Expand Up @@ -1182,39 +1185,6 @@ Detect workspace scope from the package.json name

---

### ensurePackage

▸ **ensurePackage**(`tree`, `pkg`, `requiredVersion`, `options?`): `void`

Ensure that dependencies and devDependencies from package.json are installed at the required versions.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

This will check that @nrwl/jest@<nxVersion> exists in devDependencies.
If it exists then function returns, otherwise it will install the package before continuing.
When running with --dryRun, the function will throw when dependencies are missing.

#### Parameters

| Name | Type | Description |
| :------------------------ | :------------------------------------------------ | :----------------------------------------------------------------- |
| `tree` | [`Tree`](../../devkit/documents/nrwl_devkit#tree) | the file system tree |
| `pkg` | `string` | the package to check (e.g. @nrwl/jest) |
| `requiredVersion` | `string` | the version or semver range to check (e.g. ~1.0.0, >=1.0.0 <2.0.0) |
| `options` | `Object` | |
| `options.dev?` | `boolean` | - |
| `options.throwOnMissing?` | `boolean` | - |

#### Returns

`void`

---

### extractLayoutDirectory

▸ **extractLayoutDirectory**(`directory`): `Object`
Expand Down Expand Up @@ -2431,3 +2401,66 @@ Serializes the given data to JSON and writes it to a file.
#### Returns

`void`

---

## Utils Functions

### ensurePackage

▸ **ensurePackage**(`tree`, `pkg`, `requiredVersion`, `options?`): `void`

**`deprecated`** Use the other function signature without a Tree

Use a package that has not been installed as a dependency.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

This install the @nrwl/jest@<nxVersion> and return the module
When running with --dryRun, the function will throw when dependencies are missing.

#### Parameters

| Name | Type | Description |
| :------------------------ | :------------------------------------------------ | :----------------------------------------------------------------- |
| `tree` | [`Tree`](../../devkit/documents/nrwl_devkit#tree) | the file system tree |
| `pkg` | `string` | the package to check (e.g. @nrwl/jest) |
| `requiredVersion` | `string` | the version or semver range to check (e.g. ~1.0.0, >=1.0.0 <2.0.0) |
| `options?` | `Object` | - |
| `options.dev?` | `boolean` | - |
| `options.throwOnMissing?` | `boolean` | - |

#### Returns

`void`

▸ **ensurePackage**<`T`\>(`pkg`, `version`): `T`

Ensure that dependencies and devDependencies from package.json are installed at the required versions.

For example:

```typescript
ensurePackage(tree, '@nrwl/jest', nxVersion);
```

#### Type parameters

| Name | Type |
| :--- | :------------------------ |
| `T` | extends `unknown` = `any` |

#### Parameters

| Name | Type | Description |
| :-------- | :------- | :---------------------------------------------------------- |
| `pkg` | `string` | the package to install and require |
| `version` | `string` | the version to install if the package doesn't exist already |

#### Returns

`T`
6 changes: 5 additions & 1 deletion docs/generated/packages/js/generators/init.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@
"type": "boolean",
"aliases": ["skip-format"],
"description": "Skip formatting files.",
"default": true,
"x-priority": "internal"
},
"skipPackageJson": {
"type": "boolean",
"description": "Skip adding package.json dependencies",
"x-priority": "internal"
},
"tsConfigName": {
Expand Down
9 changes: 9 additions & 0 deletions e2e/cra-to-nx/src/cra-to-nx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ describe('nx init (for CRA)', () => {
});

it('should convert to an integrated workspace with Vite', () => {
// TODO investigate why this is broken
const originalPM = process.env.SELECTED_PM;
process.env.SELECTED_PM = originalPM === 'pnpm' ? 'yarn' : originalPM;

const appName = 'my-app';
createReactApp(appName);

Expand All @@ -53,9 +57,13 @@ describe('nx init (for CRA)', () => {

const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
process.env.SELECTED_PM = originalPM;
});

it('should convert to an integrated workspace with Vite with custom port', () => {
// TODO investigate why this is broken
const originalPM = process.env.SELECTED_PM;
process.env.SELECTED_PM = originalPM === 'pnpm' ? 'yarn' : originalPM;
const appName = 'my-app';
createReactApp(appName);
updateFile(`.env`, `NOT_THE_PORT=8000\nPORT=3000\nSOMETHING_ELSE=whatever`);
Expand All @@ -71,6 +79,7 @@ describe('nx init (for CRA)', () => {

const unitTestsOutput = runCLI(`test ${appName}`);
expect(unitTestsOutput).toContain('Successfully ran target test');
process.env.SELECTED_PM = originalPM;
});

it('should convert to a standalone workspace with craco (webpack)', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Tree } from '@nrwl/devkit';
import { joinPathFragments } from '@nrwl/devkit';
import type { NormalizedSchema } from './normalized-schema';
import { ensureTypescript } from '@nrwl/js/src/utils/typescript/ensure-typescript';

export function convertToStandaloneApp(tree: Tree, options: NormalizedSchema) {
const pathToAppModule = joinPathFragments(
Expand All @@ -23,6 +24,7 @@ function updateMainEntrypoint(
) {
let routerModuleSetup: string;
if (options.routing) {
ensureTypescript();
const { tsquery } = require('@phenomnomnominal/tsquery');
const appModuleContents = tree.read(pathToAppModule, 'utf-8');
const ast = tsquery.ast(appModuleContents);
Expand Down Expand Up @@ -73,6 +75,7 @@ function updateAppComponent(tree: Tree, options: NormalizedSchema) {
);
const appComponentContents = tree.read(pathToAppComponent, 'utf-8');

ensureTypescript();
const { tsquery } = require('@phenomnomnominal/tsquery');
const ast = tsquery.ast(appComponentContents);
const COMPONENT_DECORATOR_SELECTOR =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Tree } from '@nrwl/devkit';
import { joinPathFragments } from '@nrwl/devkit';
import type { NormalizedSchema } from './normalized-schema';
import { ensureTypescript } from '@nrwl/js/src/utils/typescript/ensure-typescript';

export function convertToStandaloneApp(tree: Tree, options: NormalizedSchema) {
const pathToAppModule = joinPathFragments(
Expand All @@ -21,6 +22,7 @@ function updateMainEntrypoint(
tree: Tree,
pathToAppModule: string
) {
ensureTypescript();
const { tsquery } = require('@phenomnomnominal/tsquery');
let routerModuleSetup: string;
if (options.routing) {
Expand Down Expand Up @@ -63,6 +65,7 @@ bootstrapApplication(AppComponent${
}).catch((err) => console.error(err));`;

function updateAppComponent(tree: Tree, options: NormalizedSchema) {
ensureTypescript();
const { tsquery } = require('@phenomnomnominal/tsquery');
const pathToAppComponent = joinPathFragments(
options.appProjectRoot,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { NormalizedSchema } from './normalized-schema';

import { insertImport } from '@nrwl/workspace/src/utilities/ast-utils';
import { addImportToModule } from '../../../utils/nx-devkit/ast-utils';
import { ensureTypescript } from '@nrwl/js/src/utils/typescript/ensure-typescript';

let tsModule: typeof import('typescript');

Expand All @@ -14,7 +15,7 @@ export function addRouterRootConfiguration(
const moduleSource = host.read(modulePath, 'utf-8');

if (!tsModule) {
tsModule = require('typescript');
tsModule = ensureTypescript();
}
let sourceFile = tsModule.createSourceFile(
modulePath,
Expand Down
Loading