chore(repo): update prettier to v2 (#2934)

this is just for the repo, and not the workspace

Co-authored-by: Rares Matei <matei.rar@gmail.com>
This commit is contained in:
Jason Jean 2020-04-29 01:09:37 -04:00 committed by GitHub
parent 9b585cb3b8
commit e06822da7e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
545 changed files with 6485 additions and 6410 deletions

View File

@ -6,12 +6,12 @@ module.exports = {
{ {
value: 'cleanup', value: 'cleanup',
name: name:
'cleanup: A code change that neither fixes a bug nor adds a feature' 'cleanup: A code change that neither fixes a bug nor adds a feature',
}, },
{ {
value: 'chore', value: 'chore',
name: "chore: Other changes that don't modify src or test files" name: "chore: Other changes that don't modify src or test files",
} },
], ],
scopes: [ scopes: [
@ -28,13 +28,13 @@ module.exports = {
{ name: 'storybook', description: 'anything Storybook specific' }, { name: 'storybook', description: 'anything Storybook specific' },
{ {
name: 'testing', name: 'testing',
description: 'anything testing specific (e.g., jest or cypress)' description: 'anything testing specific (e.g., jest or cypress)',
}, },
{ {
name: 'repo', name: 'repo',
description: 'anything related to managing the repo itself' description: 'anything related to managing the repo itself',
}, },
{ name: 'misc', description: 'misc stuff' } { name: 'misc', description: 'misc stuff' },
], ],
allowTicketNumber: true, allowTicketNumber: true,
@ -66,7 +66,7 @@ module.exports = {
breaking: 'List any BREAKING CHANGES (optional):\n', breaking: 'List any BREAKING CHANGES (optional):\n',
footer: footer:
'List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:\n', 'List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:\n',
confirmCommit: 'Are you sure you want to proceed with the commit above?' confirmCommit: 'Are you sure you want to proceed with the commit above?',
}, },
allowCustomScopes: false, allowCustomScopes: false,
@ -75,7 +75,7 @@ module.exports = {
skipQuestions: ['ticketNumber'], skipQuestions: ['ticketNumber'],
// limit subject length // limit subject length
subjectLimit: 100 subjectLimit: 100,
// breaklineChar: '|', // It is supported for fields body and footer. // breaklineChar: '|', // It is supported for fields body and footer.
// footerPrefix : 'ISSUES CLOSED:' // footerPrefix : 'ISSUES CLOSED:'
// askForBreakingChangeFirst : true, // default is false // askForBreakingChangeFirst : true, // default is false

View File

@ -27,9 +27,9 @@ class TodoEffects {
// dispatch an undo action to undo the changes in the client state // dispatch an undo action to undo the changes in the client state
return { return {
type: 'UNDO_TODO_UPDATE', type: 'UNDO_TODO_UPDATE',
todo: action.todo todo: action.todo,
}; };
} },
}) })
) )
); );
@ -57,9 +57,9 @@ class TodoEffects {
// update the backend first, and then dispatch an action that will // update the backend first, and then dispatch an action that will
// update the client side // update the client side
return this.backend.updateTodo(action.todo.id, action.todo).pipe( return this.backend.updateTodo(action.todo.id, action.todo).pipe(
map(updated => ({ map((updated) => ({
type: 'UPDATE_TODO_SUCCESS', type: 'UPDATE_TODO_SUCCESS',
todo: updated todo: updated,
})) }))
); );
}, },
@ -67,7 +67,7 @@ class TodoEffects {
// we don't need to undo the changes on the client side. // we don't need to undo the changes on the client side.
// we can dispatch an error, or simply log the error here and return `null` // we can dispatch an error, or simply log the error here and return `null`
return null; return null;
} },
}) })
) )
); );
@ -93,9 +93,9 @@ class TodoEffects {
// provides an action // provides an action
run: (a: GetTodos) => { run: (a: GetTodos) => {
return this.backend.getAll().pipe( return this.backend.getAll().pipe(
map(response => ({ map((response) => ({
type: 'TODOS', type: 'TODOS',
todos: response.todos todos: response.todos,
})) }))
); );
}, },
@ -103,7 +103,7 @@ class TodoEffects {
onError: (action: GetTodos, error: any) => { onError: (action: GetTodos, error: any) => {
// dispatch an undo action to undo the changes in the client state // dispatch an undo action to undo the changes in the client state
return null; return null;
} },
}) })
) )
); );
@ -130,16 +130,16 @@ class TodoEffects {
// provides an action // provides an action
run: (todo: GetTodo) => { run: (todo: GetTodo) => {
return this.backend.getTodo(todo.id).map(response => ({ return this.backend.getTodo(todo.id).map((response) => ({
type: 'LOAD_TODO_SUCCESS', type: 'LOAD_TODO_SUCCESS',
todo: response.todo todo: response.todo,
})); }));
}, },
onError: (action: GetTodo, error: any) => { onError: (action: GetTodo, error: any) => {
// dispatch an undo action to undo the changes in the client state // dispatch an undo action to undo the changes in the client state
return null; return null;
} },
}) })
) )
); );
@ -170,9 +170,9 @@ class TodoEffects {
return this.backend return this.backend
.fetchTodo(activatedRouteSnapshot.params['id']) .fetchTodo(activatedRouteSnapshot.params['id'])
.pipe( .pipe(
map(todo => ({ map((todo) => ({
type: 'LOAD_TODO_SUCCESS', type: 'LOAD_TODO_SUCCESS',
todo: todo todo: todo,
})) }))
); );
}, },
@ -184,7 +184,7 @@ class TodoEffects {
// we can log and error here and return null // we can log and error here and return null
// we can also navigate back // we can also navigate back
return null; return null;
} },
}) })
) )
); );

View File

@ -78,7 +78,7 @@ If you have an Angular component that has an AngularJS child component you may n
@Component({ @Component({
selector: 'app-ticket-list', selector: 'app-ticket-list',
templateUrl: './ticket-list.component.html', templateUrl: './ticket-list.component.html',
styleUrls: ['./ticket-list.component.css'] styleUrls: ['./ticket-list.component.css'],
}) })
export class TicketListComponent implements OnInit { export class TicketListComponent implements OnInit {
@Input() tuskTickets; @Input() tuskTickets;

View File

@ -93,7 +93,7 @@ if (environment.production) {
platformBrowserDynamic() platformBrowserDynamic()
.bootstrapModule(AppModule) .bootstrapModule(AppModule)
.catch(err => console.error(err)); .catch((err) => console.error(err));
``` ```
And the template of the generated component will look as follows: And the template of the generated component will look as follows:
@ -313,7 +313,7 @@ if (environment.production) {
platformBrowserDynamic() platformBrowserDynamic()
.bootstrapModule(AppModule) .bootstrapModule(AppModule)
.catch(err => console.error(err)); .catch((err) => console.error(err));
``` ```
### Registering CUSTOM_ELEMENTS_SCHEMA ### Registering CUSTOM_ELEMENTS_SCHEMA
@ -326,7 +326,7 @@ Next, let's register the `CUSTOM_ELEMENTS_SCHEMA` schema, which will tell the An
imports: [BrowserModule], imports: [BrowserModule],
providers: [], providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA], schemas: [CUSTOM_ELEMENTS_SCHEMA],
bootstrap: [AppComponent] bootstrap: [AppComponent],
}) })
export class AppModule {} export class AppModule {}
``` ```

View File

@ -98,19 +98,19 @@ import { text, number, boolean } from '@storybook/addon-knobs';
import { ButtonComponent } from './button.component'; import { ButtonComponent } from './button.component';
export default { export default {
title: 'ButtonComponent' title: 'ButtonComponent',
}; };
export const primary = () => ({ export const primary = () => ({
moduleMetadata: { moduleMetadata: {
imports: [] imports: [],
}, },
component: ButtonComponent, component: ButtonComponent,
props: { props: {
text: text('text', 'Click me!'), text: text('text', 'Click me!'),
padding: number('padding', 0), padding: number('padding', 0),
style: text('style', 'default') style: text('style', 'default'),
} },
}); });
``` ```

View File

@ -20,9 +20,9 @@ describe('TodoApps', () => {
beforeEach(() => cy.visit('/')); beforeEach(() => cy.visit('/'));
it('should display todos', () => { it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2)); getTodos().should((t) => expect(t.length).equal(2));
getAddTodoButton().click(); getAddTodoButton().click();
getTodos().should(t => expect(t.length).equal(3)); getTodos().should((t) => expect(t.length).equal(3));
}); });
}); });
``` ```

View File

@ -20,7 +20,7 @@ interface Todo {
@Component({ @Component({
selector: 'myorg-root', selector: 'myorg-root',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] styleUrls: ['./app.component.css'],
}) })
export class AppComponent { export class AppComponent {
todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }]; todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];
@ -53,14 +53,14 @@ interface Todo {
@Component({ @Component({
selector: 'myorg-root', selector: 'myorg-root',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] styleUrls: ['./app.component.css'],
}) })
export class AppComponent { export class AppComponent {
todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }]; todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];
addTodo() { addTodo() {
this.todos.push({ this.todos.push({
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
}); });
} }
} }

View File

@ -15,7 +15,7 @@ import { HttpClientModule } from '@angular/common/http';
declarations: [AppComponent], declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule], imports: [BrowserModule, HttpClientModule],
providers: [], providers: [],
bootstrap: [AppComponent] bootstrap: [AppComponent],
}) })
export class AppModule {} export class AppModule {}
``` ```
@ -33,7 +33,7 @@ interface Todo {
@Component({ @Component({
selector: 'myorg-root', selector: 'myorg-root',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] styleUrls: ['./app.component.css'],
}) })
export class AppComponent { export class AppComponent {
todos: Todo[] = []; todos: Todo[] = [];
@ -43,7 +43,7 @@ export class AppComponent {
} }
fetch() { fetch() {
this.http.get<Todo[]>('/api/todos').subscribe(t => (this.todos = t)); this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
} }
addTodo() { addTodo() {

View File

@ -122,7 +122,7 @@ import { AppService } from './app.service';
@Module({ @Module({
imports: [], imports: [],
controllers: [AppController], controllers: [AppController],
providers: [AppService] providers: [AppService],
}) })
export class AppModule {} export class AppModule {}
``` ```
@ -150,7 +150,7 @@ export class AppService {
addTodo() { addTodo() {
this.todos.push({ this.todos.push({
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
}); });
} }
} }

View File

@ -65,7 +65,7 @@ export class AppService {
addTodo() { addTodo() {
this.todos.push({ this.todos.push({
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
}); });
} }
} }
@ -83,7 +83,7 @@ import { Todo } from '@myorg/data';
@Component({ @Component({
selector: 'myorg-root', selector: 'myorg-root',
templateUrl: './app.component.html', templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] styleUrls: ['./app.component.css'],
}) })
export class AppComponent { export class AppComponent {
todos: Todo[] = []; todos: Todo[] = [];
@ -93,7 +93,7 @@ export class AppComponent {
} }
fetch() { fetch() {
this.http.get<Todo[]>('/api/todos').subscribe(t => (this.todos = t)); this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
} }
addTodo() { addTodo() {

View File

@ -47,7 +47,7 @@ import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
@NgModule({ @NgModule({
imports: [CommonModule] imports: [CommonModule],
}) })
export class UiModule {} export class UiModule {}
``` ```
@ -100,7 +100,7 @@ import { Todo } from '@myorg/data';
@Component({ @Component({
selector: 'myorg-todos', selector: 'myorg-todos',
templateUrl: './todos.component.html', templateUrl: './todos.component.html',
styleUrls: ['./todos.component.css'] styleUrls: ['./todos.component.css'],
}) })
export class TodosComponent implements OnInit { export class TodosComponent implements OnInit {
@Input() todos: Todo[]; @Input() todos: Todo[];
@ -135,7 +135,7 @@ import { UiModule } from '@myorg/ui';
declarations: [AppComponent], declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule, UiModule], imports: [BrowserModule, HttpClientModule, UiModule],
providers: [], providers: [],
bootstrap: [AppComponent] bootstrap: [AppComponent],
}) })
export class AppModule {} export class AppModule {}
``` ```

View File

@ -20,9 +20,9 @@ describe('TodoApps', () => {
beforeEach(() => cy.visit('/')); beforeEach(() => cy.visit('/'));
it('should display todos', () => { it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2)); getTodos().should((t) => expect(t.length).equal(2));
getAddTodoButton().click(); getAddTodoButton().click();
getTodos().should(t => expect(t.length).equal(3)); getTodos().should((t) => expect(t.length).equal(3));
}); });
}); });
``` ```

View File

@ -20,14 +20,14 @@ interface Todo {
export const App = () => { export const App = () => {
const [todos, setTodos] = useState<Todo[]>([ const [todos, setTodos] = useState<Todo[]>([
{ title: 'Todo 1' }, { title: 'Todo 1' },
{ title: 'Todo 2' } { title: 'Todo 2' },
]); ]);
return ( return (
<> <>
<h1>Todos</h1> <h1>Todos</h1>
<ul> <ul>
{todos.map(t => ( {todos.map((t) => (
<li className={'todo'}>{t.title}</li> <li className={'todo'}>{t.title}</li>
))} ))}
</ul> </ul>
@ -54,15 +54,15 @@ interface Todo {
export const App = () => { export const App = () => {
const [todos, setTodos] = useState<Todo[]>([ const [todos, setTodos] = useState<Todo[]>([
{ title: 'Todo 1' }, { title: 'Todo 1' },
{ title: 'Todo 2' } { title: 'Todo 2' },
]); ]);
function addTodo() { function addTodo() {
setTodos([ setTodos([
...todos, ...todos,
{ {
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
} },
]); ]);
} }
@ -70,7 +70,7 @@ export const App = () => {
<> <>
<h1>Todos</h1> <h1>Todos</h1>
<ul> <ul>
{todos.map(t => ( {todos.map((t) => (
<li className={'todo'}>{t.title}</li> <li className={'todo'}>{t.title}</li>
))} ))}
</ul> </ul>

View File

@ -16,17 +16,17 @@ const App = () => {
useEffect(() => { useEffect(() => {
fetch('/api/todos') fetch('/api/todos')
.then(_ => _.json()) .then((_) => _.json())
.then(setTodos); .then(setTodos);
}, []); }, []);
function addTodo() { function addTodo() {
fetch('/api/addTodo', { fetch('/api/addTodo', {
method: 'POST', method: 'POST',
body: '' body: '',
}) })
.then(_ => _.json()) .then((_) => _.json())
.then(newTodo => { .then((newTodo) => {
setTodos([...todos, newTodo]); setTodos([...todos, newTodo]);
}); });
} }
@ -35,7 +35,7 @@ const App = () => {
<> <>
<h1>Todos</h1> <h1>Todos</h1>
<ul> <ul>
{todos.map(t => ( {todos.map((t) => (
<li className={'todo'}>{t.title}</li> <li className={'todo'}>{t.title}</li>
))} ))}
</ul> </ul>

View File

@ -117,7 +117,7 @@ export function addTodoRoutes(app: Express) {
app.get('/api/todos', (req, resp) => resp.send(todos)); app.get('/api/todos', (req, resp) => resp.send(todos));
app.post('/api/addTodo', (req, resp) => { app.post('/api/addTodo', (req, resp) => {
const newTodo = { const newTodo = {
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
}; };
todos.push(newTodo); todos.push(newTodo);
resp.send(newTodo); resp.send(newTodo);

View File

@ -58,7 +58,7 @@ export function addTodoRoutes(app: Express) {
app.get('/api/todos', (req, resp) => resp.send(todos)); app.get('/api/todos', (req, resp) => resp.send(todos));
app.post('/api/addTodo', (req, resp) => { app.post('/api/addTodo', (req, resp) => {
const newTodo = { const newTodo = {
title: `New todo ${Math.floor(Math.random() * 1000)}` title: `New todo ${Math.floor(Math.random() * 1000)}`,
}; };
todos.push(newTodo); todos.push(newTodo);
resp.send(newTodo); resp.send(newTodo);

View File

@ -114,7 +114,7 @@ import { Todo } from '@myorg/data';
export const Todos = (props: { todos: Todo[] }) => { export const Todos = (props: { todos: Todo[] }) => {
return ( return (
<ul> <ul>
{props.todos.map(t => ( {props.todos.map((t) => (
<li className={'todo'}>{t.title}</li> <li className={'todo'}>{t.title}</li>
))} ))}
</ul> </ul>
@ -138,17 +138,17 @@ const App = () => {
useEffect(() => { useEffect(() => {
fetch('/api/todos') fetch('/api/todos')
.then(_ => _.json()) .then((_) => _.json())
.then(setTodos); .then(setTodos);
}, []); }, []);
function addTodo() { function addTodo() {
fetch('/api/addTodo', { fetch('/api/addTodo', {
method: 'POST', method: 'POST',
body: '' body: '',
}) })
.then(_ => _.json()) .then((_) => _.json())
.then(newTodo => { .then((newTodo) => {
setTodos([...todos, newTodo]); setTodos([...todos, newTodo]);
}); });
} }

View File

@ -19,7 +19,7 @@ import { Todo } from '@myorg/data';
export const Todos = (props: { todos: Todo[] }) => { export const Todos = (props: { todos: Todo[] }) => {
return ( return (
<ul> <ul>
{props.todos.map(t => ( {props.todos.map((t) => (
<li className={'todo'}>{t.title}!!</li> <li className={'todo'}>{t.title}!!</li>
))} ))}
</ul> </ul>

View File

@ -139,7 +139,7 @@ console.log(
JSON.stringify({ JSON.stringify({
...commands('lint'), ...commands('lint'),
...commands('test'), ...commands('test'),
...commands('build') ...commands('build'),
}) })
); );
@ -148,7 +148,7 @@ function commands(target) {
execSync(`npx nx print-affected --base=${baseSha} --target=${target}`) execSync(`npx nx print-affected --base=${baseSha} --target=${target}`)
.toString() .toString()
.trim() .trim()
).tasks.map(t => t.target.project); ).tasks.map((t) => t.target.project);
array.sort(() => 0.5 - Math.random()); array.sort(() => 0.5 - Math.random());
const third = Math.floor(array.length / 3); const third = Math.floor(array.length / 3);
@ -158,7 +158,7 @@ function commands(target) {
return { return {
[target + '1']: a1, [target + '1']: a1,
[target + '2']: a2, [target + '2']: a2,
[target + '3']: a3 [target + '3']: a3,
}; };
} }
``` ```
@ -221,7 +221,7 @@ execSync(
',' ','
)} --parallel`, )} --parallel`,
{ {
stdio: [0, 1, 2] stdio: [0, 1, 2],
} }
); );
``` ```

View File

@ -186,7 +186,7 @@ When the plugin is generated, a test file is created in the `my-plugin-e2e` app.
We'll go over a few parts of a test file below: We'll go over a few parts of a test file below:
```typescript ```typescript
it('should create my-plugin', async done => { it('should create my-plugin', async (done) => {
const plugin = uniq('my-plugin'); const plugin = uniq('my-plugin');
ensureNxProject('@my-org/my-plugin', 'dist/libs/my-plugin'); ensureNxProject('@my-org/my-plugin', 'dist/libs/my-plugin');
await runNxCommandAsync(`generate @my-org/my-plugin:myPlugin ${plugin}`); await runNxCommandAsync(`generate @my-org/my-plugin:myPlugin ${plugin}`);

View File

@ -37,8 +37,8 @@ import { chain, externalSchematic, Rule } from '@angular-devkit/schematics';
export default function (schema: any): Rule { export default function (schema: any): Rule {
return chain([ return chain([
externalSchematic('@nrwl/workspace', 'lib', { externalSchematic('@nrwl/workspace', 'lib', {
name: schema.name name: schema.name,
}) }),
]); ]);
} }
``` ```
@ -112,13 +112,13 @@ import {
SchematicContext, SchematicContext,
Tree, Tree,
url, url,
externalSchematic externalSchematic,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { getProjectConfig } from '@nrwl/workspace'; import { getProjectConfig } from '@nrwl/workspace';
function generateLibrary(schema: any): Rule { function generateLibrary(schema: any): Rule {
return externalSchematic('@nrwl/workspace', 'lib', { return externalSchematic('@nrwl/workspace', 'lib', {
name: schema.name name: schema.name,
}); });
} }
@ -127,7 +127,7 @@ function generateFiles(schema: any): Rule {
context.logger.info('adding NOTES.md to lib'); context.logger.info('adding NOTES.md to lib');
const templateSource = apply(url('./files'), [ const templateSource = apply(url('./files'), [
move(getProjectConfig(tree, schema.name).root) move(getProjectConfig(tree, schema.name).root),
]); ]);
return chain([mergeWith(templateSource)])(tree, context); return chain([mergeWith(templateSource)])(tree, context);
@ -197,8 +197,8 @@ export default function(schema: SchematicOptions): Rule {
return chain([ return chain([
externalSchematic('@nrwl/workspace', 'lib', { externalSchematic('@nrwl/workspace', 'lib', {
name: `${schema.name}-${schema.type || ''}`, name: `${schema.name}-${schema.type || ''}`,
unitTestRunner: 'none' unitTestRunner: 'none',
}) }),
]); ]);
} }
``` ```

View File

@ -5,10 +5,10 @@ import {
readJson, readJson,
runCLI, runCLI,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli('angular', cli => { forEachCli('angular', (cli) => {
describe('Build Angular library', () => { describe('Build Angular library', () => {
/** /**
* Graph: * Graph:
@ -51,7 +51,7 @@ forEachCli('angular', cli => {
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
${children ${children
.map( .map(
entry => (entry) =>
`import { ${toClassName( `import { ${toClassName(
entry entry
)}Module } from '@proj/${entry}';` )}Module } from '@proj/${entry}';`
@ -60,7 +60,7 @@ forEachCli('angular', cli => {
@NgModule({ @NgModule({
imports: [CommonModule, ${children imports: [CommonModule, ${children
.map(entry => `${toClassName(entry)}Module`) .map((entry) => `${toClassName(entry)}Module`)
.join(',')}] .join(',')}]
}) })
export class ${toClassName(parent)}Module {} export class ${toClassName(parent)}Module {}
@ -101,7 +101,7 @@ forEachCli('angular', cli => {
const jsonFile = readJson(`dist/libs/${parentLib}/package.json`); const jsonFile = readJson(`dist/libs/${parentLib}/package.json`);
expect(jsonFile.dependencies).toEqual({ expect(jsonFile.dependencies).toEqual({
[`@proj/${childLib}`]: '0.0.1', [`@proj/${childLib}`]: '0.0.1',
[`@proj/${childLib2}`]: '0.0.1' [`@proj/${childLib2}`]: '0.0.1',
}); });
}); });
}); });

View File

@ -10,7 +10,7 @@ import {
forEachCli, forEachCli,
checkFilesExist, checkFilesExist,
tmpProjPath, tmpProjPath,
supportUi supportUi,
} from './utils'; } from './utils';
import { toClassName } from '@nrwl/workspace'; import { toClassName } from '@nrwl/workspace';

View File

@ -6,10 +6,10 @@ import {
runCLI, runCLI,
runCommand, runCommand,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
describe('Bazel', () => { describe('Bazel', () => {
const ngapp = uniq('ngapp'); const ngapp = uniq('ngapp');
const reactapp = uniq('reactapp'); const reactapp = uniq('reactapp');

View File

@ -10,7 +10,7 @@ import {
runCommand, runCommand,
tmpProjPath, tmpProjPath,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli('nx', () => { forEachCli('nx', () => {
@ -84,7 +84,7 @@ forEachCli(() => {
const reportOutput = runCommand('npm run nx report'); const reportOutput = runCommand('npm run nx report');
packagesWeCareAbout.forEach(p => { packagesWeCareAbout.forEach((p) => {
expect(reportOutput).toContain(p); expect(reportOutput).toContain(p);
}); });
}, 120000); }, 120000);
@ -157,7 +157,7 @@ forEachCli(() => {
`./node_modules/migrate-parent-package/package.json`, `./node_modules/migrate-parent-package/package.json`,
JSON.stringify({ JSON.stringify({
version: '1.0.0', version: '1.0.0',
'nx-migrations': './migrations.json' 'nx-migrations': './migrations.json',
}) })
); );
@ -168,14 +168,14 @@ forEachCli(() => {
run11: { run11: {
version: '1.1.0', version: '1.1.0',
description: '1.1.0', description: '1.1.0',
factory: './run11' factory: './run11',
}, },
run20: { run20: {
version: '2.0.0', version: '2.0.0',
description: '2.0.0', description: '2.0.0',
factory: './run20' factory: './run20',
} },
} },
}) })
); );
@ -204,13 +204,13 @@ forEachCli(() => {
updateFile( updateFile(
`./node_modules/migrate-child-package/package.json`, `./node_modules/migrate-child-package/package.json`,
JSON.stringify({ JSON.stringify({
version: '1.0.0' version: '1.0.0',
}) })
); );
updateFile( updateFile(
'./node_modules/@nrwl/tao/src/commands/migrate.js', './node_modules/@nrwl/tao/src/commands/migrate.js',
content => { (content) => {
const start = content.indexOf('// testing-fetch-start'); const start = content.indexOf('// testing-fetch-start');
const end = content.indexOf('// testing-fetch-end'); const end = content.indexOf('// testing-fetch-end');
@ -262,14 +262,14 @@ forEachCli(() => {
{ {
package: 'migrate-parent-package', package: 'migrate-parent-package',
version: '1.1.0', version: '1.1.0',
name: 'run11' name: 'run11',
}, },
{ {
package: 'migrate-parent-package', package: 'migrate-parent-package',
version: '2.0.0', version: '2.0.0',
name: 'run20' name: 'run20',
} },
] ],
}); });
// runs migrations // runs migrations

View File

@ -8,7 +8,7 @@ describe('create-nx-workspace', () => {
execSync(`yarn local-registry disable`); execSync(`yarn local-registry disable`);
}); });
it('creates a new project', async done => { it('creates a new project', async (done) => {
if (!process.env.PUBLISHED_VERSION) { if (!process.env.PUBLISHED_VERSION) {
console.error(`Please provision the version you are publishing`); console.error(`Please provision the version you are publishing`);
process.exit(1); process.exit(1);
@ -54,7 +54,7 @@ describe('create-nx-workspace', () => {
expect( expect(
execSync(`npm_config_registry=http://localhost:4873/ && npm audit`, { execSync(`npm_config_registry=http://localhost:4873/ && npm audit`, {
cwd: workspaceDir cwd: workspaceDir,
}).toString() }).toString()
).toContain(`0 vulnerabilities`); ).toContain(`0 vulnerabilities`);
@ -66,7 +66,7 @@ describe('create-nx-workspace', () => {
// filtering out rxjs in the listr package. // filtering out rxjs in the listr package.
const rxjs = allVersionsOf(workspaceDir, 'rxjs').filter( const rxjs = allVersionsOf(workspaceDir, 'rxjs').filter(
value => value !== '5.5.12' (value) => value !== '5.5.12'
); );
if (rxjs.length > 1) { if (rxjs.length > 1) {
console.log(`more than one version of rxjs: ${rxjs.join(', ')}`); console.log(`more than one version of rxjs: ${rxjs.join(', ')}`);
@ -83,7 +83,7 @@ describe('create-nx-workspace', () => {
}); });
function wait(value = 500) { function wait(value = 500) {
return new Promise(r => { return new Promise((r) => {
setTimeout(() => r(), value); setTimeout(() => r(), value);
}); });
} }
@ -91,13 +91,13 @@ function wait(value = 500) {
function startRegistry() { function startRegistry() {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const server = exec('yarn local-registry start'); const server = exec('yarn local-registry start');
server.stdout.on('data', d => { server.stdout.on('data', (d) => {
if (d.toString().indexOf('http address') > -1) { if (d.toString().indexOf('http address') > -1) {
res(); res();
} }
}); });
server.on('exit', s => { server.on('exit', (s) => {
if (s !== 0) { if (s !== 0) {
rej(`Cannot start local registry`); rej(`Cannot start local registry`);
} }
@ -107,7 +107,7 @@ function startRegistry() {
function allVersionsOf(dir: string, packageToCheck: string) { function allVersionsOf(dir: string, packageToCheck: string) {
const r = packageJsonFilesInNodeModules(`${dir}/node_modules`) const r = packageJsonFilesInNodeModules(`${dir}/node_modules`)
.map(p => { .map((p) => {
try { try {
const parsed = JSON.parse(readFileSync(p).toString()); const parsed = JSON.parse(readFileSync(p).toString());
if (parsed.name == packageToCheck) { if (parsed.name == packageToCheck) {
@ -118,7 +118,7 @@ function allVersionsOf(dir: string, packageToCheck: string) {
return null; return null;
} }
}) })
.filter(p => !!p); .filter((p) => !!p);
return r.filter((value, index, self) => self.indexOf(value) === index); return r.filter((value, index, self) => self.indexOf(value) === index);
} }
@ -133,7 +133,7 @@ function addReact(workspaceDir: string) {
); );
execSync(`npm install --registry=http://localhost:4873/`, { execSync(`npm install --registry=http://localhost:4873/`, {
stdio: [0, 1, 2], stdio: [0, 1, 2],
cwd: workspaceDir cwd: workspaceDir,
}); });
} }
@ -141,7 +141,7 @@ async function execCommand(description: string, cmd: string, cwd?: string) {
console.log(description); console.log(description);
execSync(`npm_config_registry=http://localhost:4873/ && ${cmd}`, { execSync(`npm_config_registry=http://localhost:4873/ && ${cmd}`, {
stdio: [0, 1, 2], stdio: [0, 1, 2],
cwd cwd,
}); });
await wait(); await wait();
} }
@ -149,7 +149,7 @@ async function execCommand(description: string, cmd: string, cwd?: string) {
function packageJsonFilesInNodeModules(dirName: string): string[] { function packageJsonFilesInNodeModules(dirName: string): string[] {
let res = []; let res = [];
try { try {
readdirSync(dirName).forEach(c => { readdirSync(dirName).forEach((c) => {
try { try {
const child = path.join(dirName, c); const child = path.join(dirName, c);
const s = statSync(child); const s = statSync(child);

View File

@ -8,10 +8,10 @@ import {
runCLI, runCLI,
supportUi, supportUi,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint';
const nrwlPackageName = currentCLIName === 'angular' ? 'angular' : 'react'; const nrwlPackageName = currentCLIName === 'angular' ? 'angular' : 'react';

View File

@ -5,7 +5,7 @@ import {
updateFile, updateFile,
forEachCli, forEachCli,
supportUi, supportUi,
patchKarmaToWorkOnWSL patchKarmaToWorkOnWSL,
} from './utils'; } from './utils';
forEachCli('angular', () => { forEachCli('angular', () => {

View File

@ -4,13 +4,13 @@ import {
uniq, uniq,
runCLI, runCLI,
forEachCli, forEachCli,
updateFile updateFile,
} from './utils'; } from './utils';
import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { stripIndents } from '@angular-devkit/core/src/utils/literals';
forEachCli(() => { forEachCli(() => {
describe('Jest', () => { describe('Jest', () => {
it('should be able test projects using jest', async done => { it('should be able test projects using jest', async (done) => {
ensureProject(); ensureProject();
const mylib = uniq('mylib'); const mylib = uniq('mylib');
const myapp = uniq('myapp'); const myapp = uniq('myapp');
@ -21,7 +21,7 @@ forEachCli(() => {
runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`), runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`),
runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`), runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`),
runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`), runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`),
runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`) runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`),
]); ]);
const appResult = await runCLIAsync(`test ${myapp} --no-watch`); const appResult = await runCLIAsync(`test ${myapp} --no-watch`);
expect(appResult.stderr).toContain('Test Suites: 3 passed, 3 total'); expect(appResult.stderr).toContain('Test Suites: 3 passed, 3 total');
@ -30,7 +30,7 @@ forEachCli(() => {
done(); done();
}, 45000); }, 45000);
it('should merge with jest config globals', async done => { it('should merge with jest config globals', async (done) => {
ensureProject(); ensureProject();
const testGlobal = `'My Test Global'`; const testGlobal = `'My Test Global'`;
const mylib = uniq('mylib'); const mylib = uniq('mylib');
@ -68,7 +68,7 @@ forEachCli(() => {
done(); done();
}, 45000); }, 45000);
it('should set the NODE_ENV to `test`', async done => { it('should set the NODE_ENV to `test`', async (done) => {
ensureProject(); ensureProject();
const mylib = uniq('mylib'); const mylib = uniq('mylib');
runCLI(`generate @nrwl/workspace:lib ${mylib} --unit-test-runner jest`); runCLI(`generate @nrwl/workspace:lib ${mylib} --unit-test-runner jest`);

View File

@ -5,12 +5,12 @@ import {
uniq, uniq,
forEachCli, forEachCli,
supportUi, supportUi,
patchKarmaToWorkOnWSL patchKarmaToWorkOnWSL,
} from './utils'; } from './utils';
forEachCli(() => { forEachCli(() => {
describe('Karma', () => { describe('Karma', () => {
it('should be able to generate a testable library using karma', async done => { it('should be able to generate a testable library using karma', async (done) => {
ensureProject(); ensureProject();
const mylib = uniq('mylib'); const mylib = uniq('mylib');
@ -19,7 +19,7 @@ forEachCli(() => {
await Promise.all([ await Promise.all([
runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`), runCLIAsync(`generate @nrwl/angular:service test --project ${mylib}`),
runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`) runCLIAsync(`generate @nrwl/angular:component test --project ${mylib}`),
]); ]);
const karmaResult = await runCLIAsync(`test ${mylib}`); const karmaResult = await runCLIAsync(`test ${mylib}`);
@ -27,7 +27,7 @@ forEachCli(() => {
done(); done();
}, 30000); }, 30000);
it('should be able to generate a testable application using karma', async done => { it('should be able to generate a testable application using karma', async (done) => {
ensureProject(); ensureProject();
const myapp = uniq('myapp'); const myapp = uniq('myapp');
runCLI(`generate @nrwl/angular:app ${myapp} --unit-test-runner karma`); runCLI(`generate @nrwl/angular:app ${myapp} --unit-test-runner karma`);
@ -35,7 +35,7 @@ forEachCli(() => {
await Promise.all([ await Promise.all([
runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`), runCLIAsync(`generate @nrwl/angular:service test --project ${myapp}`),
runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`) runCLIAsync(`generate @nrwl/angular:component test --project ${myapp}`),
]); ]);
const karmaResult = await runCLIAsync(`test ${myapp}`); const karmaResult = await runCLIAsync(`test ${myapp}`);
expect(karmaResult.stdout).toContain('5 SUCCESS'); expect(karmaResult.stdout).toContain('5 SUCCESS');

View File

@ -7,7 +7,7 @@ import {
updateFile, updateFile,
ensureProject, ensureProject,
uniq, uniq,
forEachCli forEachCli,
} from './utils'; } from './utils';
forEachCli('nx', () => { forEachCli('nx', () => {
@ -100,7 +100,7 @@ forEachCli('nx', () => {
expect(() => checkFilesExist(`my-cache`)).toThrow(); expect(() => checkFilesExist(`my-cache`)).toThrow();
runCLI(`lint ${myapp} --cache --cache-location="my-cache"`, { runCLI(`lint ${myapp} --cache --cache-location="my-cache"`, {
silenceError: true silenceError: true,
}); });
expect(() => checkFilesExist(`my-cache`)).not.toThrow(); expect(() => checkFilesExist(`my-cache`)).not.toThrow();
const cacheInfo = readFile('my-cache'); const cacheInfo = readFile('my-cache');
@ -125,14 +125,16 @@ forEachCli('nx', () => {
const stdout = runCLI( const stdout = runCLI(
`lint ${myapp} --output-file="${outputFile}" --format=json`, `lint ${myapp} --output-file="${outputFile}" --format=json`,
{ {
silenceError: true silenceError: true,
} }
); );
expect(stdout).toContain('Unexpected console statement'); expect(stdout).toContain('Unexpected console statement');
expect(() => checkFilesExist(outputFile)).not.toThrow(); expect(() => checkFilesExist(outputFile)).not.toThrow();
const outputContents = JSON.parse(readFile(outputFile)); const outputContents = JSON.parse(readFile(outputFile));
const outputForApp: any = Object.values(outputContents).filter( const outputForApp: any = Object.values(
(result: any) => result.filePath.includes(`${myapp}/src/main.ts`) outputContents
).filter((result: any) =>
result.filePath.includes(`${myapp}/src/main.ts`)
)[0]; )[0];
expect(outputForApp.errorCount).toBe(1); expect(outputForApp.errorCount).toBe(1);
expect(outputForApp.messages[0].ruleId).toBe('no-console'); expect(outputForApp.messages[0].ruleId).toBe('no-console');

View File

@ -9,7 +9,7 @@ import {
runCLIAsync, runCLIAsync,
supportUi, supportUi,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli('nx', () => { forEachCli('nx', () => {
@ -24,9 +24,9 @@ forEachCli('nx', () => {
'/external-api': { '/external-api': {
target: 'http://localhost:4200', target: 'http://localhost:4200',
pathRewrite: { pathRewrite: {
'^/external-api/hello': '/api/hello' '^/external-api/hello': '/api/hello',
} },
} },
}; };
updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf)); updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf));

View File

@ -9,7 +9,7 @@ import {
runNew, runNew,
updateFile, updateFile,
forEachCli, forEachCli,
runNgAdd runNgAdd,
} from './utils'; } from './utils';
forEachCli('angular', () => { forEachCli('angular', () => {
@ -43,10 +43,10 @@ forEachCli('angular', () => {
// update angular-cli.json // update angular-cli.json
const angularCLIJson = readJson('angular.json'); const angularCLIJson = readJson('angular.json');
angularCLIJson.projects.proj.architect.build.options.scripts = angularCLIJson.projects.proj.architect.test.options.scripts = [ angularCLIJson.projects.proj.architect.build.options.scripts = angularCLIJson.projects.proj.architect.test.options.scripts = [
'src/scripts.ts' 'src/scripts.ts',
]; ];
angularCLIJson.projects.proj.architect.test.options.styles = [ angularCLIJson.projects.proj.architect.test.options.styles = [
'src/styles.css' 'src/styles.css',
]; ];
updateFile('angular.json', JSON.stringify(angularCLIJson, null, 2)); updateFile('angular.json', JSON.stringify(angularCLIJson, null, 2));
@ -66,7 +66,7 @@ forEachCli('angular', () => {
'nrwl.angular-console', 'nrwl.angular-console',
'angular.ng-template', 'angular.ng-template',
'ms-vscode.vscode-typescript-tslint-plugin', 'ms-vscode.vscode-typescript-tslint-plugin',
'esbenp.prettier-vscode' 'esbenp.prettier-vscode',
]); ]);
// check that package.json got merged // check that package.json got merged
@ -95,7 +95,7 @@ forEachCli('angular', () => {
'update:check': 'ng update', 'update:check': 'ng update',
'dep-graph': 'nx dep-graph', 'dep-graph': 'nx dep-graph',
'workspace-schematic': 'nx workspace-schematic', 'workspace-schematic': 'nx workspace-schematic',
help: 'nx help' help: 'nx help',
}); });
expect( expect(
updatedPackageJson.devDependencies['@nrwl/workspace'] updatedPackageJson.devDependencies['@nrwl/workspace']
@ -110,16 +110,16 @@ forEachCli('angular', () => {
'package.json': '*', 'package.json': '*',
'tslint.json': '*', 'tslint.json': '*',
'tsconfig.json': '*', 'tsconfig.json': '*',
'nx.json': '*' 'nx.json': '*',
}, },
projects: { projects: {
proj: { proj: {
tags: [] tags: [],
}, },
'proj-e2e': { 'proj-e2e': {
tags: [] tags: [],
} },
} },
}); });
// check if angular-cli.json get merged // check if angular-cli.json get merged
@ -140,27 +140,27 @@ forEachCli('angular', () => {
tsConfig: 'apps/proj/tsconfig.app.json', tsConfig: 'apps/proj/tsconfig.app.json',
assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'], assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'],
styles: ['apps/proj/src/styles.css'], styles: ['apps/proj/src/styles.css'],
scripts: ['apps/proj/src/scripts.ts'] scripts: ['apps/proj/src/scripts.ts'],
}, },
configurations: { configurations: {
production: { production: {
fileReplacements: [ fileReplacements: [
{ {
replace: 'apps/proj/src/environments/environment.ts', replace: 'apps/proj/src/environments/environment.ts',
with: 'apps/proj/src/environments/environment.prod.ts' with: 'apps/proj/src/environments/environment.prod.ts',
} },
], ],
budgets: [ budgets: [
{ {
maximumError: '5mb', maximumError: '5mb',
maximumWarning: '2mb', maximumWarning: '2mb',
type: 'initial' type: 'initial',
}, },
{ {
maximumError: '10kb', maximumError: '10kb',
maximumWarning: '6kb', maximumWarning: '6kb',
type: 'anyComponentStyle' type: 'anyComponentStyle',
} },
], ],
optimization: true, optimization: true,
outputHashing: 'all', outputHashing: 'all',
@ -169,20 +169,20 @@ forEachCli('angular', () => {
namedChunks: false, namedChunks: false,
extractLicenses: true, extractLicenses: true,
vendorChunk: false, vendorChunk: false,
buildOptimizer: true buildOptimizer: true,
} },
} },
}); });
expect(updatedAngularCLIJson.projects.proj.architect.serve).toEqual({ expect(updatedAngularCLIJson.projects.proj.architect.serve).toEqual({
builder: '@angular-devkit/build-angular:dev-server', builder: '@angular-devkit/build-angular:dev-server',
options: { options: {
browserTarget: 'proj:build' browserTarget: 'proj:build',
}, },
configurations: { configurations: {
production: { production: {
browserTarget: 'proj:build:production' browserTarget: 'proj:build:production',
} },
} },
}); });
expect(updatedAngularCLIJson.projects.proj.architect.test).toEqual({ expect(updatedAngularCLIJson.projects.proj.architect.test).toEqual({
@ -194,8 +194,8 @@ forEachCli('angular', () => {
karmaConfig: 'apps/proj/karma.conf.js', karmaConfig: 'apps/proj/karma.conf.js',
styles: ['apps/proj/src/styles.css'], styles: ['apps/proj/src/styles.css'],
scripts: ['apps/proj/src/scripts.ts'], scripts: ['apps/proj/src/scripts.ts'],
assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'] assets: ['apps/proj/src/favicon.ico', 'apps/proj/src/assets'],
} },
}); });
expect(updatedAngularCLIJson.projects.proj.architect.lint).toEqual({ expect(updatedAngularCLIJson.projects.proj.architect.lint).toEqual({
@ -203,10 +203,10 @@ forEachCli('angular', () => {
options: { options: {
tsConfig: [ tsConfig: [
'apps/proj/tsconfig.app.json', 'apps/proj/tsconfig.app.json',
'apps/proj/tsconfig.spec.json' 'apps/proj/tsconfig.spec.json',
], ],
exclude: ['**/node_modules/**'] exclude: ['**/node_modules/**'],
} },
}); });
expect(updatedAngularCLIJson.projects['proj-e2e'].root).toEqual( expect(updatedAngularCLIJson.projects['proj-e2e'].root).toEqual(
@ -216,21 +216,21 @@ forEachCli('angular', () => {
builder: '@angular-devkit/build-angular:protractor', builder: '@angular-devkit/build-angular:protractor',
configurations: { configurations: {
production: { production: {
devServerTarget: 'proj:serve:production' devServerTarget: 'proj:serve:production',
} },
}, },
options: { options: {
protractorConfig: 'apps/proj-e2e/protractor.conf.js', protractorConfig: 'apps/proj-e2e/protractor.conf.js',
devServerTarget: 'proj:serve' devServerTarget: 'proj:serve',
} },
}); });
expect(updatedAngularCLIJson.projects['proj-e2e'].architect.lint).toEqual( expect(updatedAngularCLIJson.projects['proj-e2e'].architect.lint).toEqual(
{ {
builder: '@angular-devkit/build-angular:tslint', builder: '@angular-devkit/build-angular:tslint',
options: { options: {
tsConfig: 'apps/proj-e2e/tsconfig.json', tsConfig: 'apps/proj-e2e/tsconfig.json',
exclude: ['**/node_modules/**'] exclude: ['**/node_modules/**'],
} },
} }
); );
@ -239,8 +239,8 @@ forEachCli('angular', () => {
true, true,
{ {
allow: [], allow: [],
depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }] depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }],
} },
]); ]);
runCLI('build --prod --outputHashing none'); runCLI('build --prod --outputHashing none');
@ -267,7 +267,7 @@ forEachCli('angular', () => {
updateFile( updateFile(
'.vscode/extensions.json', '.vscode/extensions.json',
JSON.stringify({ JSON.stringify({
recommendations: ['eamodio.gitlens', 'angular.ng-template'] recommendations: ['eamodio.gitlens', 'angular.ng-template'],
}) })
); );
// run the command // run the command
@ -292,7 +292,7 @@ forEachCli('angular', () => {
'angular.ng-template', 'angular.ng-template',
'nrwl.angular-console', 'nrwl.angular-console',
'ms-vscode.vscode-typescript-tslint-plugin', 'ms-vscode.vscode-typescript-tslint-plugin',
'esbenp.prettier-vscode' 'esbenp.prettier-vscode',
]); ]);
}); });

View File

@ -5,7 +5,7 @@ import {
uniq, uniq,
ensureProject, ensureProject,
readJson, readJson,
forEachCli forEachCli,
} from './utils'; } from './utils';
forEachCli(() => { forEachCli(() => {

View File

@ -20,15 +20,15 @@ import {
tmpProjPath, tmpProjPath,
uniq, uniq,
updateFile, updateFile,
workspaceConfigName workspaceConfigName,
} from './utils'; } from './utils';
function getData(): Promise<any> { function getData(): Promise<any> {
return new Promise(resolve => { return new Promise((resolve) => {
http.get('http://localhost:3333/api', res => { http.get('http://localhost:3333/api', (res) => {
expect(res.statusCode).toEqual(200); expect(res.statusCode).toEqual(200);
let data = ''; let data = '';
res.on('data', chunk => { res.on('data', (chunk) => {
data += chunk; data += chunk;
}); });
res.once('end', () => { res.once('end', () => {
@ -38,7 +38,7 @@ function getData(): Promise<any> {
}); });
} }
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint';
describe('Node Applications', () => { describe('Node Applications', () => {
@ -56,12 +56,12 @@ forEachCli(currentCLIName => {
checkFilesExist(`dist/apps/${nodeapp}/main.js`); checkFilesExist(`dist/apps/${nodeapp}/main.js`);
const result = execSync(`node dist/apps/${nodeapp}/main.js`, { const result = execSync(`node dist/apps/${nodeapp}/main.js`, {
cwd: tmpProjPath() cwd: tmpProjPath(),
}).toString(); }).toString();
expect(result).toContain('Hello World!'); expect(result).toContain('Hello World!');
}, 60000); }, 60000);
it('should be able to generate an express application', async done => { it('should be able to generate an express application', async (done) => {
ensureProject(); ensureProject();
const nodeapp = uniq('nodeapp'); const nodeapp = uniq('nodeapp');
@ -93,18 +93,18 @@ forEachCli(currentCLIName => {
const server = fork(`./dist/apps/${nodeapp}/main.js`, [], { const server = fork(`./dist/apps/${nodeapp}/main.js`, [], {
cwd: tmpProjPath(), cwd: tmpProjPath(),
silent: true silent: true,
}); });
expect(server).toBeTruthy(); expect(server).toBeTruthy();
await new Promise(resolve => { await new Promise((resolve) => {
server.stdout.once('data', async data => { server.stdout.once('data', async (data) => {
expect(data.toString()).toContain( expect(data.toString()).toContain(
'Listening at http://localhost:3333' 'Listening at http://localhost:3333'
); );
const result = await getData(); const result = await getData();
expect(result.message).toEqual(`Welcome to ${nodeapp}!`); expect(result.message).toEqual(`Welcome to ${nodeapp}!`);
treeKill(server.pid, 'SIGTERM', err => { treeKill(server.pid, 'SIGTERM', (err) => {
expect(err).toBeFalsy(); expect(err).toBeFalsy();
resolve(); resolve();
}); });
@ -116,22 +116,22 @@ forEachCli(currentCLIName => {
options: { options: {
commands: [ commands: [
{ {
command: 'sleep 1 && echo DONE' command: 'sleep 1 && echo DONE',
} },
], ],
readyWhen: 'DONE' readyWhen: 'DONE',
} },
}; };
config.projects[nodeapp].architect.serve.options.waitUntilTargets = [ config.projects[nodeapp].architect.serve.options.waitUntilTargets = [
`${nodeapp}:waitAndPrint` `${nodeapp}:waitAndPrint`,
]; ];
updateFile(workspaceConfigName(), JSON.stringify(config)); updateFile(workspaceConfigName(), JSON.stringify(config));
const process = spawn( const process = spawn(
'node', 'node',
['./node_modules/.bin/nx', 'serve', nodeapp], ['./node_modules/.bin/nx', 'serve', nodeapp],
{ {
cwd: tmpProjPath() cwd: tmpProjPath(),
} }
); );
let collectedOutput = ''; let collectedOutput = '';
@ -143,7 +143,7 @@ forEachCli(currentCLIName => {
const result = await getData(); const result = await getData();
expect(result.message).toEqual(`Welcome to ${nodeapp}!`); expect(result.message).toEqual(`Welcome to ${nodeapp}!`);
treeKill(process.pid, 'SIGTERM', err => { treeKill(process.pid, 'SIGTERM', (err) => {
expect(collectedOutput.indexOf('DONE') > -1).toBeTruthy(); expect(collectedOutput.indexOf('DONE') > -1).toBeTruthy();
expect(err).toBeFalsy(); expect(err).toBeFalsy();
done(); done();
@ -182,7 +182,7 @@ forEachCli(currentCLIName => {
cleanup(); cleanup();
}, 120000); }, 120000);
it('should be able to generate a nest application', async done => { it('should be able to generate a nest application', async (done) => {
ensureProject(); ensureProject();
const nestapp = uniq('nestapp'); const nestapp = uniq('nestapp');
runCLI(`generate @nrwl/nest:app ${nestapp} --linter=${linter}`); runCLI(`generate @nrwl/nest:app ${nestapp} --linter=${linter}`);
@ -204,18 +204,18 @@ forEachCli(currentCLIName => {
const server = fork(`./dist/apps/${nestapp}/main.js`, [], { const server = fork(`./dist/apps/${nestapp}/main.js`, [], {
cwd: tmpProjPath(), cwd: tmpProjPath(),
silent: true silent: true,
}); });
expect(server).toBeTruthy(); expect(server).toBeTruthy();
await new Promise(resolve => { await new Promise((resolve) => {
server.stdout.on('data', async data => { server.stdout.on('data', async (data) => {
const message = data.toString(); const message = data.toString();
if (message.includes('Listening at http://localhost:3333')) { if (message.includes('Listening at http://localhost:3333')) {
const result = await getData(); const result = await getData();
expect(result.message).toEqual(`Welcome to ${nestapp}!`); expect(result.message).toEqual(`Welcome to ${nestapp}!`);
treeKill(server.pid, 'SIGTERM', err => { treeKill(server.pid, 'SIGTERM', (err) => {
expect(err).toBeFalsy(); expect(err).toBeFalsy();
resolve(); resolve();
}); });
@ -227,7 +227,7 @@ forEachCli(currentCLIName => {
'node', 'node',
['./node_modules/@nrwl/cli/bin/nx', 'serve', nestapp], ['./node_modules/@nrwl/cli/bin/nx', 'serve', nestapp],
{ {
cwd: tmpProjPath() cwd: tmpProjPath(),
} }
); );
@ -237,7 +237,7 @@ forEachCli(currentCLIName => {
} }
const result = await getData(); const result = await getData();
expect(result.message).toEqual(`Welcome to ${nestapp}!`); expect(result.message).toEqual(`Welcome to ${nestapp}!`);
treeKill(process.pid, 'SIGTERM', err => { treeKill(process.pid, 'SIGTERM', (err) => {
expect(err).toBeFalsy(); expect(err).toBeFalsy();
done(); done();
}); });
@ -273,10 +273,10 @@ forEachCli(currentCLIName => {
outDir: '../../dist/out-tsc', outDir: '../../dist/out-tsc',
declaration: true, declaration: true,
rootDir: './src', rootDir: './src',
types: ['node'] types: ['node'],
}, },
exclude: ['**/*.spec.ts'], exclude: ['**/*.spec.ts'],
include: ['**/*.ts'] include: ['**/*.ts'],
}); });
await runCLIAsync(`build ${nodeLib}`); await runCLIAsync(`build ${nodeLib}`);
checkFilesExist( checkFilesExist(
@ -290,7 +290,7 @@ forEachCli(currentCLIName => {
name: `@proj/${nodeLib}`, name: `@proj/${nodeLib}`,
version: '0.0.1', version: '0.0.1',
main: 'index.js', main: 'index.js',
typings: 'index.d.ts' typings: 'index.d.ts',
}); });
}, 60000); }, 60000);
@ -310,7 +310,7 @@ forEachCli(currentCLIName => {
workspace.projects[nodelib].architect.build.options.assets.push({ workspace.projects[nodelib].architect.build.options.assets.push({
input: `./dist/libs/${nglib}`, input: `./dist/libs/${nglib}`,
glob: '**/*', glob: '**/*',
output: '.' output: '.',
}); });
updateFile(workspaceConfigName(), JSON.stringify(workspace)); updateFile(workspaceConfigName(), JSON.stringify(workspace));
@ -424,12 +424,12 @@ forEachCli(currentCLIName => {
`libs/${parent}/src/lib/${parent}.ts`, `libs/${parent}/src/lib/${parent}.ts`,
` `
${children ${children
.map(entry => `import { ${entry} } from '@proj/${entry}';`) .map((entry) => `import { ${entry} } from '@proj/${entry}';`)
.join('\n')} .join('\n')}
export function ${parent}(): string { export function ${parent}(): string {
return '${parent}' + ' ' + ${children return '${parent}' + ' ' + ${children
.map(entry => `${entry}()`) .map((entry) => `${entry}()`)
.join('+')} .join('+')}
} }
` `
@ -446,7 +446,7 @@ forEachCli(currentCLIName => {
); );
// we are setting paths to {} to make sure built libs are read from dist // we are setting paths to {} to make sure built libs are read from dist
updateFile('tsconfig.json', c => { updateFile('tsconfig.json', (c) => {
const json = JSON.parse(c); const json = JSON.parse(c);
json.compilerOptions.paths = {}; json.compilerOptions.paths = {};
return JSON.stringify(json, null, 2); return JSON.stringify(json, null, 2);

View File

@ -8,14 +8,14 @@ import {
runCLIAsync, runCLIAsync,
checkFilesExist, checkFilesExist,
readJson, readJson,
workspaceConfigName workspaceConfigName,
} from './utils'; } from './utils';
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint';
describe('Nx Plugin', () => { describe('Nx Plugin', () => {
it('should be able to generate a Nx Plugin ', async done => { it('should be able to generate a Nx Plugin ', async (done) => {
ensureProject(); ensureProject();
const plugin = uniq('plugin'); const plugin = uniq('plugin');
@ -44,18 +44,18 @@ forEachCli(currentCLIName => {
expect(nxJson).toMatchObject({ expect(nxJson).toMatchObject({
projects: expect.objectContaining({ projects: expect.objectContaining({
[plugin]: { [plugin]: {
tags: [] tags: [],
}, },
[`${plugin}-e2e`]: { [`${plugin}-e2e`]: {
tags: [], tags: [],
implicitDependencies: [`${plugin}`] implicitDependencies: [`${plugin}`],
} },
}) }),
}); });
done(); done();
}, 45000); }, 45000);
it(`should run the plugin's e2e tests`, async done => { it(`should run the plugin's e2e tests`, async (done) => {
ensureProject(); ensureProject();
const plugin = uniq('plugin'); const plugin = uniq('plugin');
runCLI(`generate @nrwl/nx-plugin:plugin ${plugin} --linter=${linter}`); runCLI(`generate @nrwl/nx-plugin:plugin ${plugin} --linter=${linter}`);
@ -66,7 +66,7 @@ forEachCli(currentCLIName => {
done(); done();
}, 150000); }, 150000);
it('should be able to generate a migration', async done => { it('should be able to generate a migration', async (done) => {
ensureProject(); ensureProject();
const plugin = uniq('plugin'); const plugin = uniq('plugin');
const version = '1.0.0'; const version = '1.0.0';
@ -96,14 +96,14 @@ forEachCli(currentCLIName => {
[`update-${version}`]: { [`update-${version}`]: {
version: version, version: version,
description: `update-${version}`, description: `update-${version}`,
factory: `./src/migrations/update-${version}/update-${version}` factory: `./src/migrations/update-${version}/update-${version}`,
} },
}) }),
}); });
done(); done();
}, 45000); }, 45000);
it('should be able to generate a schematic', async done => { it('should be able to generate a schematic', async (done) => {
ensureProject(); ensureProject();
const plugin = uniq('plugin'); const plugin = uniq('plugin');
const schematic = uniq('schematic'); const schematic = uniq('schematic');
@ -136,14 +136,14 @@ forEachCli(currentCLIName => {
[schematic]: { [schematic]: {
factory: `./src/schematics/${schematic}/schematic`, factory: `./src/schematics/${schematic}/schematic`,
schema: `./src/schematics/${schematic}/schema.json`, schema: `./src/schematics/${schematic}/schema.json`,
description: `${schematic} schematic` description: `${schematic} schematic`,
} },
}) }),
}); });
done(); done();
}, 45000); }, 45000);
it('should be able to generate a builder', async done => { it('should be able to generate a builder', async (done) => {
ensureProject(); ensureProject();
const plugin = uniq('plugin'); const plugin = uniq('plugin');
const builder = uniq('builder'); const builder = uniq('builder');
@ -174,9 +174,9 @@ forEachCli(currentCLIName => {
[builder]: { [builder]: {
implementation: `./src/builders/${builder}/builder`, implementation: `./src/builders/${builder}/builder`,
schema: `./src/builders/${builder}/schema.json`, schema: `./src/builders/${builder}/schema.json`,
description: `${builder} builder` description: `${builder} builder`,
} },
}) }),
}); });
done(); done();
}, 45000); }, 45000);

View File

@ -5,10 +5,10 @@ import {
readJson, readJson,
runCLI, runCLI,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli('nx', cli => { forEachCli('nx', (cli) => {
describe('Build React libraries and apps', () => { describe('Build React libraries and apps', () => {
/** /**
* Graph: * Graph:
@ -50,7 +50,7 @@ forEachCli('nx', cli => {
updateFile( updateFile(
`libs/${parent}/src/lib/${parent}.tsx`, `libs/${parent}/src/lib/${parent}.tsx`,
` `
${children.map(entry => `import '@proj/${entry}';`).join('\n')} ${children.map((entry) => `import '@proj/${entry}';`).join('\n')}
` `
); );
@ -66,7 +66,7 @@ forEachCli('nx', cli => {
); );
// we are setting paths to {} to make sure built libs are read from dist // we are setting paths to {} to make sure built libs are read from dist
updateFile('tsconfig.json', c => { updateFile('tsconfig.json', (c) => {
const json = JSON.parse(c); const json = JSON.parse(c);
json.compilerOptions.paths = {}; json.compilerOptions.paths = {};
return JSON.stringify(json, null, 2); return JSON.stringify(json, null, 2);
@ -112,7 +112,7 @@ forEachCli('nx', cli => {
const jsonFile = readJson(`dist/libs/${parentLib}/package.json`); const jsonFile = readJson(`dist/libs/${parentLib}/package.json`);
expect(jsonFile.dependencies).toEqual({ expect(jsonFile.dependencies).toEqual({
[`@proj/${childLib}`]: '0.0.1', [`@proj/${childLib}`]: '0.0.1',
[`@proj/${childLib2}`]: '0.0.1' [`@proj/${childLib2}`]: '0.0.1',
}); });
}); });

View File

@ -11,10 +11,10 @@ import {
runCLIAsync, runCLIAsync,
uniq, uniq,
updateFile, updateFile,
workspaceConfigName workspaceConfigName,
} from './utils'; } from './utils';
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint'; const linter = currentCLIName === 'angular' ? 'tslint' : 'eslint';
describe('React Applications', () => { describe('React Applications', () => {
@ -40,7 +40,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: true, checkStyles: true,
checkLinter: true, checkLinter: true,
checkE2E: true checkE2E: true,
}); });
}, 120000); }, 120000);
@ -123,7 +123,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: true, checkStyles: true,
checkLinter: true, checkLinter: true,
checkE2E: false checkE2E: false,
}); });
}, 120000); }, 120000);
@ -157,7 +157,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: true, checkStyles: true,
checkLinter: true, checkLinter: true,
checkE2E: false checkE2E: false,
}); });
}, 120000); }, 120000);
@ -172,7 +172,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: false, checkStyles: false,
checkLinter: true, checkLinter: true,
checkE2E: false checkE2E: false,
}); });
}, 120000); }, 120000);
@ -187,7 +187,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: false, checkStyles: false,
checkLinter: true, checkLinter: true,
checkE2E: false checkE2E: false,
}); });
expect(() => checkFilesExist(`dist/apps/${appName}/styles.css`)).toThrow( expect(() => checkFilesExist(`dist/apps/${appName}/styles.css`)).toThrow(
@ -281,7 +281,7 @@ forEachCli(currentCLIName => {
await testGeneratedApp(appName, { await testGeneratedApp(appName, {
checkStyles: true, checkStyles: true,
checkLinter: false, checkLinter: false,
checkE2E: false checkE2E: false,
}); });
}, 30000); }, 30000);
@ -300,7 +300,7 @@ forEachCli(currentCLIName => {
`dist/apps/${appName}/polyfills.js`, `dist/apps/${appName}/polyfills.js`,
`dist/apps/${appName}/runtime.js`, `dist/apps/${appName}/runtime.js`,
`dist/apps/${appName}/vendor.js`, `dist/apps/${appName}/vendor.js`,
`dist/apps/${appName}/main.js` `dist/apps/${appName}/main.js`,
]; ];
if (opts.checkStyles) { if (opts.checkStyles) {
filesToCheck.push(`dist/apps/${appName}/styles.js`); filesToCheck.push(`dist/apps/${appName}/styles.js`);
@ -316,7 +316,7 @@ forEachCli(currentCLIName => {
`dist/apps/${appName}/polyfills.esm.js`, `dist/apps/${appName}/polyfills.esm.js`,
`dist/apps/${appName}/main.esm.js`, `dist/apps/${appName}/main.esm.js`,
`dist/apps/${appName}/polyfills.es5.js`, `dist/apps/${appName}/polyfills.es5.js`,
`dist/apps/${appName}/main.es5.js` `dist/apps/${appName}/main.es5.js`,
]; ];
if (opts.checkStyles) { if (opts.checkStyles) {
filesToCheck.push(`dist/apps/${appName}/styles.css`); filesToCheck.push(`dist/apps/${appName}/styles.css`);

View File

@ -6,7 +6,7 @@ import {
ensureProject, ensureProject,
tmpProjPath, tmpProjPath,
checkFilesExist, checkFilesExist,
readFile readFile,
} from './utils'; } from './utils';
import { writeFileSync, mkdirSync } from 'fs'; import { writeFileSync, mkdirSync } from 'fs';

View File

@ -5,7 +5,7 @@ import {
updateFile, updateFile,
forEachCli, forEachCli,
supportUi, supportUi,
patchKarmaToWorkOnWSL patchKarmaToWorkOnWSL,
} from './utils'; } from './utils';
forEachCli('angular', () => { forEachCli('angular', () => {

View File

@ -4,7 +4,7 @@ import {
readFileSync, readFileSync,
renameSync, renameSync,
statSync, statSync,
writeFileSync writeFileSync,
} from 'fs'; } from 'fs';
import { ensureDirSync } from 'fs-extra'; import { ensureDirSync } from 'fs-extra';
import * as path from 'path'; import * as path from 'path';
@ -38,7 +38,7 @@ export function forEachCli(
} }
const cb: any = callback ? callback : selectedCliOrFunction; const cb: any = callback ? callback : selectedCliOrFunction;
clis.forEach(c => { clis.forEach((c) => {
describe(`[${c}]`, () => { describe(`[${c}]`, () => {
beforeEach(() => { beforeEach(() => {
cli = c; cli = c;
@ -91,7 +91,7 @@ function patchPackageJsonDeps(addWorkspace = true) {
export function runYarnInstall(silent: boolean = true) { export function runYarnInstall(silent: boolean = true) {
const install = execSync('yarn install', { const install = execSync('yarn install', {
cwd: tmpProjPath(), cwd: tmpProjPath(),
...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
}); });
return install ? install.toString() : ''; return install ? install.toString() : '';
} }
@ -102,7 +102,7 @@ export function runNgcc(silent: boolean = true, async: boolean = true) {
(!async ? ' --async=false' : ''), (!async ? ' --async=false' : ''),
{ {
cwd: tmpProjPath(), cwd: tmpProjPath(),
...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
} }
); );
return install ? install.toString() : ''; return install ? install.toString() : '';
@ -123,20 +123,22 @@ export function runNew(
let gen; let gen;
if (cli === 'angular') { if (cli === 'angular') {
gen = execSync( gen = execSync(
`../../node_modules/.bin/ng new proj --no-interactive --skip-install ${args || `../../node_modules/.bin/ng new proj --no-interactive --skip-install ${
''}`, args || ''
}`,
{ {
cwd: `./tmp/${cli}`, cwd: `./tmp/${cli}`,
...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) ...(silent ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
} }
); );
} else { } else {
gen = execSync( gen = execSync(
`node ../../node_modules/@nrwl/tao/index.js new proj --no-interactive --skip-install ${args || `node ../../node_modules/@nrwl/tao/index.js new proj --no-interactive --skip-install ${
''}`, args || ''
}`,
{ {
cwd: `./tmp/${cli}`, cwd: `./tmp/${cli}`,
...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}) ...(silent && false ? { stdio: ['ignore', 'ignore', 'ignore'] } : {}),
} }
); );
} }
@ -310,9 +312,9 @@ export function copyMissingPackages(): void {
'less', 'less',
'send', 'send',
'@bazel' '@bazel',
]; ];
modulesToCopy.forEach(m => copyNodeModule(m)); modulesToCopy.forEach((m) => copyNodeModule(m));
updateFile( updateFile(
'node_modules/@angular-devkit/schematics/tasks/node-package/executor.js', 'node_modules/@angular-devkit/schematics/tasks/node-package/executor.js',
` `
@ -357,14 +359,14 @@ export function runCommandAsync(
command: string, command: string,
opts: RunCmdOpts = { opts: RunCmdOpts = {
silenceError: false, silenceError: false,
env: process.env env: process.env,
} }
): Promise<{ stdout: string; stderr: string }> { ): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
exec( exec(
`${command}`, `${command}`,
{ {
cwd: tmpProjPath() cwd: tmpProjPath(),
}, },
(err, stdout, stderr) => { (err, stdout, stderr) => {
if (!opts.silenceError && err) { if (!opts.silenceError && err) {
@ -380,7 +382,7 @@ export function runCLIAsync(
command: string, command: string,
opts: RunCmdOpts = { opts: RunCmdOpts = {
silenceError: false, silenceError: false,
env: process.env env: process.env,
} }
): Promise<{ stdout: string; stderr: string }> { ): Promise<{ stdout: string; stderr: string }> {
return runCommandAsync( return runCommandAsync(
@ -393,13 +395,13 @@ export function runNgAdd(
command?: string, command?: string,
opts: RunCmdOpts = { opts: RunCmdOpts = {
silenceError: false, silenceError: false,
env: process.env env: process.env,
} }
): string { ): string {
try { try {
return execSync(`./node_modules/.bin/ng ${command}`, { return execSync(`./node_modules/.bin/ng ${command}`, {
cwd: tmpProjPath(), cwd: tmpProjPath(),
env: opts.env env: opts.env,
}) })
.toString() .toString()
.replace( .replace(
@ -420,13 +422,13 @@ export function runCLI(
command?: string, command?: string,
opts: RunCmdOpts = { opts: RunCmdOpts = {
silenceError: false, silenceError: false,
env: process.env env: process.env,
} }
): string { ): string {
try { try {
const r = execSync(`node ./node_modules/@nrwl/cli/bin/nx.js ${command}`, { const r = execSync(`node ./node_modules/@nrwl/cli/bin/nx.js ${command}`, {
cwd: tmpProjPath(), cwd: tmpProjPath(),
env: opts.env env: opts.env,
}) })
.toString() .toString()
.replace( .replace(
@ -460,7 +462,7 @@ export function runCommand(command: string): string {
try { try {
const r = execSync(command, { const r = execSync(command, {
cwd: tmpProjPath(), cwd: tmpProjPath(),
stdio: ['pipe', 'pipe', 'pipe'] stdio: ['pipe', 'pipe', 'pipe'],
}).toString(); }).toString();
console.log(r); console.log(r);
return r; return r;
@ -480,9 +482,9 @@ function setMaxWorkers() {
const workspaceFile = workspaceConfigName(); const workspaceFile = workspaceConfigName();
const workspace = readJson(workspaceFile); const workspace = readJson(workspaceFile);
Object.keys(workspace.projects).forEach(appName => { Object.keys(workspace.projects).forEach((appName) => {
const { const {
architect: { build } architect: { build },
} = workspace.projects[appName]; } = workspace.projects[appName];
if (!build) { if (!build) {
@ -520,7 +522,7 @@ export function renameFile(f: string, newPath: string): void {
} }
export function checkFilesExist(...expectedFiles: string[]) { export function checkFilesExist(...expectedFiles: string[]) {
expectedFiles.forEach(f => { expectedFiles.forEach((f) => {
const ff = f.startsWith('/') ? f : tmpProjPath(f); const ff = f.startsWith('/') ? f : tmpProjPath(f);
if (!exists(ff)) { if (!exists(ff)) {
throw new Error(`File '${ff}' does not exist`); throw new Error(`File '${ff}' does not exist`);
@ -529,7 +531,7 @@ export function checkFilesExist(...expectedFiles: string[]) {
} }
export function checkFilesDoNotExist(...expectedFiles: string[]) { export function checkFilesDoNotExist(...expectedFiles: string[]) {
expectedFiles.forEach(f => { expectedFiles.forEach((f) => {
const ff = f.startsWith('/') ? f : tmpProjPath(f); const ff = f.startsWith('/') ? f : tmpProjPath(f);
if (exists(ff)) { if (exists(ff)) {
throw new Error(`File '${ff}' does not exist`); throw new Error(`File '${ff}' does not exist`);

View File

@ -8,10 +8,10 @@ import {
runCLIAsync, runCLIAsync,
supportUi, supportUi,
uniq, uniq,
updateFile updateFile,
} from './utils'; } from './utils';
forEachCli(currentCLIName => { forEachCli((currentCLIName) => {
describe('Web Components Applications', () => { describe('Web Components Applications', () => {
it('should be able to generate a web app', async () => { it('should be able to generate a web app', async () => {
ensureProject(); ensureProject();
@ -137,7 +137,7 @@ forEachCli(currentCLIName => {
updateFile(main, `${newCode}\n${content}`); updateFile(main, `${newCode}\n${content}`);
runCLI(`build ${appName}`, { runCLI(`build ${appName}`, {
env: { ...process.env, NODE_ENV: 'test', NX_BUILD: '52', NX_API: 'QA' } env: { ...process.env, NODE_ENV: 'test', NX_BUILD: '52', NX_API: 'QA' },
}); });
expect(readFile(`dist/apps/${appName}/main.js`)).toContain( expect(readFile(`dist/apps/${appName}/main.js`)).toContain(
'var envVars = ["test", "52", "QA"];' 'var envVars = ["test", "52", "QA"];'

View File

@ -14,10 +14,10 @@ import {
tmpProjPath, tmpProjPath,
uniq, uniq,
updateFile, updateFile,
workspaceConfigName workspaceConfigName,
} from './utils'; } from './utils';
forEachCli(cli => { forEachCli((cli) => {
describe('lint', () => { describe('lint', () => {
it('lint should ensure module boundaries', () => { it('lint should ensure module boundaries', () => {
ensureProject(); ensureProject();
@ -39,7 +39,7 @@ forEachCli(cli => {
const tslint = readJson('tslint.json'); const tslint = readJson('tslint.json');
tslint.rules['nx-enforce-module-boundaries'][1].depConstraints = [ tslint.rules['nx-enforce-module-boundaries'][1].depConstraints = [
{ sourceTag: 'validtag', onlyDependOnLibsWithTags: ['validtag'] }, { sourceTag: 'validtag', onlyDependOnLibsWithTags: ['validtag'] },
...tslint.rules['nx-enforce-module-boundaries'][1].depConstraints ...tslint.rules['nx-enforce-module-boundaries'][1].depConstraints,
]; ];
updateFile('tslint.json', JSON.stringify(tslint, null, 2)); updateFile('tslint.json', JSON.stringify(tslint, null, 2));
@ -178,11 +178,11 @@ forEachCli(cli => {
const json = readJson(`tools/schematics/${custom}/schema.json`); const json = readJson(`tools/schematics/${custom}/schema.json`);
json.properties['directory'] = { json.properties['directory'] = {
type: 'string', type: 'string',
description: 'lib directory' description: 'lib directory',
}; };
json.properties['skipTsConfig'] = { json.properties['skipTsConfig'] = {
type: 'boolean', type: 'boolean',
description: 'skip changes to tsconfig' description: 'skip changes to tsconfig',
}; };
updateFile( updateFile(
`tools/schematics/${custom}/schema.json`, `tools/schematics/${custom}/schema.json`,
@ -299,47 +299,47 @@ forEachCli(cli => {
{ {
source: 'myapp3-e2e', source: 'myapp3-e2e',
target: 'myapp3', target: 'myapp3',
type: 'implicit' type: 'implicit',
} },
], ],
myapp2: [ myapp2: [
{ {
source: 'myapp2', source: 'myapp2',
target: 'mylib', target: 'mylib',
type: 'static' type: 'static',
} },
], ],
'myapp2-e2e': [ 'myapp2-e2e': [
{ {
source: 'myapp2-e2e', source: 'myapp2-e2e',
target: 'myapp2', target: 'myapp2',
type: 'implicit' type: 'implicit',
} },
], ],
mylib: [ mylib: [
{ {
source: 'mylib', source: 'mylib',
target: 'mylib2', target: 'mylib2',
type: 'static' type: 'static',
} },
], ],
mylib2: [], mylib2: [],
myapp: [ myapp: [
{ {
source: 'myapp', source: 'myapp',
target: 'mylib', target: 'mylib',
type: 'static' type: 'static',
}, },
{ source: 'myapp', target: 'mylib2', type: 'dynamic' } { source: 'myapp', target: 'mylib2', type: 'dynamic' },
], ],
'myapp-e2e': [ 'myapp-e2e': [
{ {
source: 'myapp-e2e', source: 'myapp-e2e',
target: 'myapp', target: 'myapp',
type: 'implicit' type: 'implicit',
} },
], ],
myapp3: [] myapp3: [],
}); });
runCommand( runCommand(
@ -592,7 +592,7 @@ forEachCli(cli => {
const nxJson = JSON.parse(readFile('nx.json')) as NxJson; const nxJson = JSON.parse(readFile('nx.json')) as NxJson;
expect(nxJson.projects[`${lib1}-data-access`]).toBeUndefined(); expect(nxJson.projects[`${lib1}-data-access`]).toBeUndefined();
expect(nxJson.projects[newName]).toEqual({ expect(nxJson.projects[newName]).toEqual({
tags: [] tags: [],
}); });
expect(moveOutput).toContain('UPDATE tsconfig.json'); expect(moveOutput).toContain('UPDATE tsconfig.json');
@ -613,7 +613,7 @@ forEachCli(cli => {
expect(project.sourceRoot).toBe(`${newPath}/src`); expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.architect.lint.options.tsConfig).toEqual([ expect(project.architect.lint.options.tsConfig).toEqual([
`libs/shared/${lib1}/data-access/tsconfig.lib.json`, `libs/shared/${lib1}/data-access/tsconfig.lib.json`,
`libs/shared/${lib1}/data-access/tsconfig.spec.json` `libs/shared/${lib1}/data-access/tsconfig.spec.json`,
]); ]);
/** /**

View File

@ -11,12 +11,12 @@ import {
runCommand, runCommand,
uniq, uniq,
updateFile, updateFile,
workspaceConfigName workspaceConfigName,
} from './utils'; } from './utils';
let originalCIValue: any; let originalCIValue: any;
forEachCli(cliName => { forEachCli((cliName) => {
const cliCommand = cliName === 'angular' ? 'ng' : 'nx'; const cliCommand = cliName === 'angular' ? 'ng' : 'nx';
/** /**
@ -269,8 +269,8 @@ forEachCli(cliName => {
results: { results: {
[myapp]: false, [myapp]: false,
[mylib]: true, [mylib]: true,
[mypublishablelib]: true [mypublishablelib]: true,
} },
}); });
// Fix failing Unit Test // Fix failing Unit Test
@ -429,11 +429,11 @@ forEachCli(cliName => {
overrides: {}, overrides: {},
target: { target: {
project: myapp, project: myapp,
target: 'test' target: 'test',
}, },
command: `npm run ${cliCommand} -- test ${myapp}`, command: `npm run ${cliCommand} -- test ${myapp}`,
outputs: [] outputs: [],
} },
]); ]);
compareTwoArrays(resWithTarget.projects, [`${myapp}-e2e`, myapp]); compareTwoArrays(resWithTarget.projects, [`${myapp}-e2e`, myapp]);
@ -448,27 +448,27 @@ forEachCli(cliName => {
overrides: {}, overrides: {},
target: { target: {
project: mypublishablelib, project: mypublishablelib,
target: 'build' target: 'build',
}, },
command: `npm run ${cliCommand} -- build ${mypublishablelib}`, command: `npm run ${cliCommand} -- build ${mypublishablelib}`,
outputs: [`dist/libs/${mypublishablelib}`] outputs: [`dist/libs/${mypublishablelib}`],
}, },
{ {
id: `${myapp}:build`, id: `${myapp}:build`,
overrides: {}, overrides: {},
target: { target: {
project: myapp, project: myapp,
target: 'build' target: 'build',
}, },
command: `npm run ${cliCommand} -- build ${myapp}`, command: `npm run ${cliCommand} -- build ${myapp}`,
outputs: [`dist/apps/${myapp}`] outputs: [`dist/apps/${myapp}`],
} },
]); ]);
compareTwoArrays(resWithDeps.projects, [ compareTwoArrays(resWithDeps.projects, [
mylib, mylib,
mypublishablelib, mypublishablelib,
myapp, myapp,
`${myapp}-e2e` `${myapp}-e2e`,
]); ]);
const resWithTargetWithSelect1 = runCommand( const resWithTargetWithSelect1 = runCommand(
@ -487,8 +487,8 @@ forEachCli(cliName => {
function compareTwoSerializedArrays(a: string, b: string) { function compareTwoSerializedArrays(a: string, b: string) {
compareTwoArrays( compareTwoArrays(
a.split(',').map(_ => _.trim()), a.split(',').map((_) => _.trim()),
b.split(',').map(_ => _.trim()) b.split(',').map((_) => _.trim())
); );
} }
@ -543,7 +543,7 @@ forEachCli(cliName => {
// touch myapp1 // touch myapp1
// -------------------------------------------- // --------------------------------------------
updateFile(`apps/${myapp1}/src/main.ts`, c => { updateFile(`apps/${myapp1}/src/main.ts`, (c) => {
return `${c}\n//some comment`; return `${c}\n//some comment`;
}); });
const outputWithBuildApp2Cached = runCommand( const outputWithBuildApp2Cached = runCommand(
@ -554,7 +554,7 @@ forEachCli(cliName => {
// touch package.json // touch package.json
// -------------------------------------------- // --------------------------------------------
updateFile(`package.json`, c => { updateFile(`package.json`, (c) => {
const r = JSON.parse(c); const r = JSON.parse(c);
r.description = 'different'; r.description = 'different';
return JSON.stringify(r); return JSON.stringify(r);
@ -597,7 +597,7 @@ forEachCli(cliName => {
myapp1, myapp1,
myapp2, myapp2,
`${myapp1}-e2e`, `${myapp1}-e2e`,
`${myapp2}-e2e` `${myapp2}-e2e`,
]); ]);
// run without caching // run without caching
@ -605,14 +605,14 @@ forEachCli(cliName => {
// disable caching // disable caching
// -------------------------------------------- // --------------------------------------------
updateFile('nx.json', c => { updateFile('nx.json', (c) => {
const nxJson = JSON.parse(c); const nxJson = JSON.parse(c);
nxJson.tasksRunnerOptions = { nxJson.tasksRunnerOptions = {
default: { default: {
options: { options: {
cacheableOperations: [] cacheableOperations: [],
} },
} },
}; };
return JSON.stringify(nxJson, null, 2); return JSON.stringify(nxJson, null, 2);
}); });

View File

@ -9,8 +9,8 @@ module.exports = function(config) {
process: true, process: true,
module: false, module: false,
clearImmediate: false, clearImmediate: false,
setImmediate: false setImmediate: false,
} },
}; };
config.set({ config.set({
basePath: '.', basePath: '.',
@ -28,7 +28,7 @@ module.exports = function(config) {
// preprocess matching files before serving them to the browser // preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: { preprocessors: {
'build/test.js': ['webpack'] 'build/test.js': ['webpack'],
}, },
reporters: ['dots'], reporters: ['dots'],
@ -36,13 +36,13 @@ module.exports = function(config) {
webpack: webpackConfig, webpack: webpackConfig,
webpackMiddleware: { webpackMiddleware: {
stats: 'errors-only' stats: 'errors-only',
}, },
plugins: [ plugins: [
require('karma-jasmine'), require('karma-jasmine'),
require('karma-chrome-launcher'), require('karma-chrome-launcher'),
require('karma-webpack') require('karma-webpack'),
], ],
// web server port // web server port
@ -60,14 +60,14 @@ module.exports = function(config) {
customLaunchers: { customLaunchers: {
Chrome_travis_ci: { Chrome_travis_ci: {
base: 'Chrome', base: 'Chrome',
flags: ['--no-sandbox'] flags: ['--no-sandbox'],
} },
}, },
browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'], browsers: process.env.TRAVIS ? ['Chrome_travis_ci'] : ['Chrome'],
// Concurrency level // Concurrency level
// how many browser should be started simultaneous // how many browser should be started simultaneous
concurrency: Infinity concurrency: Infinity,
}); });
}; };

View File

@ -91,7 +91,7 @@
"@types/jasminewd2": "~2.0.3", "@types/jasminewd2": "~2.0.3",
"@types/jest": "25.1.4", "@types/jest": "25.1.4",
"@types/node": "10.0.1", "@types/node": "10.0.1",
"@types/prettier": "^1.10.0", "@types/prettier": "2.0.0",
"@types/react": "16.9.17", "@types/react": "16.9.17",
"@types/react-dom": "16.9.4", "@types/react-dom": "16.9.4",
"@types/react-redux": "7.1.5", "@types/react-redux": "7.1.5",
@ -186,7 +186,7 @@
"postcss-import": "12.0.1", "postcss-import": "12.0.1",
"postcss-loader": "3.0.0", "postcss-loader": "3.0.0",
"precise-commits": "1.0.2", "precise-commits": "1.0.2",
"prettier": "1.18.2", "prettier": "2.0.4",
"protractor": "5.4.3", "protractor": "5.4.3",
"raw-loader": "3.1.0", "raw-loader": "3.1.0",
"react": "16.10.2", "react": "16.10.2",

View File

@ -3,6 +3,6 @@ export {
fetch, fetch,
navigation, navigation,
optimisticUpdate, optimisticUpdate,
pessimisticUpdate pessimisticUpdate,
} from './src/runtime/nx/data-persistence'; } from './src/runtime/nx/data-persistence';
export { NxModule } from './src/runtime/nx/nx.module'; export { NxModule } from './src/runtime/nx/nx.module';

View File

@ -14,8 +14,8 @@ try {
"If you want to use 'ng', you need to create a new workspace powered by the Angular CLI.", "If you want to use 'ng', you need to create a new workspace powered by the Angular CLI.",
'You can do it by selecting Angular CLI when creating a new workspace.', 'You can do it by selecting Angular CLI when creating a new workspace.',
"Or by providing --cli as follows: 'create-nx-workspace --cli=angular'.", "Or by providing --cli as follows: 'create-nx-workspace --cli=angular'.",
"You can invoke the Angular schematics with 'nx generate @nrwl/angular' to generate artifacts." "You can invoke the Angular schematics with 'nx generate @nrwl/angular' to generate artifacts.",
] ],
}); });
} }
} }

View File

@ -6,7 +6,7 @@ import { Actions, Effect, EffectsModule, ofType } from '@ngrx/effects';
import { provideMockActions } from '@ngrx/effects/testing'; import { provideMockActions } from '@ngrx/effects/testing';
import { import {
StoreRouterConnectingModule, StoreRouterConnectingModule,
DefaultRouterStateSerializer DefaultRouterStateSerializer,
} from '@ngrx/router-store'; } from '@ngrx/router-store';
import { Store, StoreModule } from '@ngrx/store'; import { Store, StoreModule } from '@ngrx/store';
import { Observable, of, Subject, throwError } from 'rxjs'; import { Observable, of, Subject, throwError } from 'rxjs';
@ -17,7 +17,7 @@ import {
pessimisticUpdate, pessimisticUpdate,
optimisticUpdate, optimisticUpdate,
fetch, fetch,
NxModule NxModule,
} from '../index'; } from '../index';
import { readAll } from '../testing'; import { readAll } from '../testing';
@ -59,9 +59,7 @@ function userReducer(): string {
} }
@Component({ @Component({
template: ` template: ` ROOT[<router-outlet></router-outlet>] `,
ROOT[<router-outlet></router-outlet>]
`
}) })
class RootCmp {} class RootCmp {}
@ -70,7 +68,7 @@ class RootCmp {}
Todo [ Todo [
<div *ngIf="todo | async as t">ID {{ t.id }} User {{ t.user }}</div> <div *ngIf="todo | async as t">ID {{ t.id }} User {{ t.user }}</div>
] ]
` `,
}) })
class TodoComponent { class TodoComponent {
todo = this.store.select('todos', 'selected'); todo = this.store.select('todos', 'selected');
@ -88,18 +86,18 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
} },
} }
), ),
StoreRouterConnectingModule.forRoot({ StoreRouterConnectingModule.forRoot({
serializer: DefaultRouterStateSerializer serializer: DefaultRouterStateSerializer,
}), }),
RouterTestingModule.withRoutes([ RouterTestingModule.withRoutes([
{ path: 'todo/:id', component: TodoComponent } { path: 'todo/:id', component: TodoComponent },
]), ]),
NxModule.forRoot() NxModule.forRoot(),
] ],
}); });
}); });
@ -111,10 +109,10 @@ describe('DataPersistence', () => {
run: (a, state) => { run: (a, state) => {
return { return {
type: 'TODO_LOADED', type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user } payload: { id: a.params['id'], user: state.user },
}; };
}, },
onError: () => null onError: () => null,
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
@ -122,7 +120,7 @@ describe('DataPersistence', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])] imports: [EffectsModule.forRoot([TodoEffects])],
}); });
}); });
@ -150,18 +148,18 @@ describe('DataPersistence', () => {
} else { } else {
return { return {
type: 'TODO_LOADED', type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user } payload: { id: a.params['id'], user: state.user },
}; };
} }
}, },
onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }) onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }),
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
} }
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])] imports: [EffectsModule.forRoot([TodoEffects])],
}); });
}); });
@ -176,9 +174,9 @@ describe('DataPersistence', () => {
tick(0); tick(0);
root.detectChanges(false); root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123'); expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123');
expect(actions.map(a => a.type)).toContain('ERROR'); expect(actions.map((a) => a.type)).toContain('ERROR');
expect( expect(
actions.find(a => a.type === 'ERROR').payload.error.message actions.find((a) => a.type === 'ERROR').payload.error.message
).toEqual('boom'); ).toEqual('boom');
// can recover after an error // can recover after an error
@ -200,18 +198,18 @@ describe('DataPersistence', () => {
} else { } else {
return { return {
type: 'TODO_LOADED', type: 'TODO_LOADED',
payload: { id: a.params['id'], user: state.user } payload: { id: a.params['id'], user: state.user },
}; };
} }
}, },
onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }) onError: (a, e) => ({ type: 'ERROR', payload: { error: e } }),
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
} }
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [EffectsModule.forRoot([TodoEffects])] imports: [EffectsModule.forRoot([TodoEffects])],
}); });
}); });
@ -226,8 +224,8 @@ describe('DataPersistence', () => {
tick(0); tick(0);
root.detectChanges(false); root.detectChanges(false);
expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123'); expect(root.elementRef.nativeElement.innerHTML).not.toContain('ID 123');
expect(actions.map(a => a.type)).toContain('ERROR'); expect(actions.map((a) => a.type)).toContain('ERROR');
expect(actions.find(a => a.type === 'ERROR').payload.error).toEqual( expect(actions.find((a) => a.type === 'ERROR').payload.error).toEqual(
'boom' 'boom'
); );
@ -257,11 +255,11 @@ describe('DataPersistence', () => {
// we need to introduce the delay to "enable" switchMap // we need to introduce the delay to "enable" switchMap
return of({ return of({
type: 'TODOS', type: 'TODOS',
payload: { user: state.user, todos: 'some todos' } payload: { user: state.user, todos: 'some todos' },
}).pipe(delay(1)); }).pipe(delay(1));
}, },
onError: () => null onError: () => null,
}); });
@Effect() @Effect()
@ -272,9 +270,9 @@ describe('DataPersistence', () => {
run: (action, state) => { run: (action, state) => {
return of({ return of({
type: 'TODOS', type: 'TODOS',
payload: { user: state.user, todos: 'some todos' } payload: { user: state.user, todos: 'some todos' },
}).pipe(delay(1)); }).pipe(delay(1));
} },
}) })
); );
@ -297,15 +295,15 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of( actions = of(
{ type: 'GET_TODOS', payload: {} }, { type: 'GET_TODOS', payload: {} },
{ type: 'GET_TODOS', payload: {} } { type: 'GET_TODOS', payload: {} }
@ -313,13 +311,13 @@ describe('DataPersistence', () => {
expect(await readAll(TestBed.get(TodoEffects).loadTodos)).toEqual([ expect(await readAll(TestBed.get(TodoEffects).loadTodos)).toEqual([
{ type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } },
{ type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } } { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } },
]); ]);
done(); done();
}); });
it('should work with an operator', async done => { it('should work with an operator', async (done) => {
actions = of( actions = of(
{ type: 'GET_TODOS', payload: {} }, { type: 'GET_TODOS', payload: {} },
{ type: 'GET_TODOS', payload: {} } { type: 'GET_TODOS', payload: {} }
@ -329,7 +327,7 @@ describe('DataPersistence', () => {
await readAll(TestBed.get(TodoEffects).loadTodosWithOperator) await readAll(TestBed.get(TodoEffects).loadTodosWithOperator)
).toEqual([ ).toEqual([
{ type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } }, { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } },
{ type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } } { type: 'TODOS', payload: { user: 'bob', todos: 'some todos' } },
]); ]);
done(); done();
@ -346,9 +344,9 @@ describe('DataPersistence', () => {
class TodoEffects { class TodoEffects {
@Effect() @Effect()
loadTodo = this.s.fetch<GetTodo>('GET_TODO', { loadTodo = this.s.fetch<GetTodo>('GET_TODO', {
id: a => a.payload.id, id: (a) => a.payload.id,
run: a => of({ type: 'TODO', payload: a.payload }).pipe(delay(1)), run: (a) => of({ type: 'TODO', payload: a.payload }).pipe(delay(1)),
onError: () => null onError: () => null,
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
@ -370,15 +368,15 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of( actions = of(
{ type: 'GET_TODO', payload: { id: 1, value: '1' } }, { type: 'GET_TODO', payload: { id: 1, value: '1' } },
{ type: 'GET_TODO', payload: { id: 2, value: '2a' } }, { type: 'GET_TODO', payload: { id: 2, value: '2a' } },
@ -387,7 +385,7 @@ describe('DataPersistence', () => {
expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([ expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([
{ type: 'TODO', payload: { id: 1, value: '1' } }, { type: 'TODO', payload: { id: 1, value: '1' } },
{ type: 'TODO', payload: { id: 2, value: '2b' } } { type: 'TODO', payload: { id: 2, value: '2b' } },
]); ]);
done(); done();
@ -407,9 +405,9 @@ describe('DataPersistence', () => {
loadTodo = this.s.pessimisticUpdate<UpdateTodo>('UPDATE_TODO', { loadTodo = this.s.pessimisticUpdate<UpdateTodo>('UPDATE_TODO', {
run: (a, state) => ({ run: (a, state) => ({
type: 'TODO_UPDATED', type: 'TODO_UPDATED',
payload: { user: state.user, newTitle: a.payload.newTitle } payload: { user: state.user, newTitle: a.payload.newTitle },
}), }),
onError: () => null onError: () => null,
}); });
@Effect() @Effect()
@ -419,9 +417,9 @@ describe('DataPersistence', () => {
pessimisticUpdate({ pessimisticUpdate({
run: (a, state) => ({ run: (a, state) => ({
type: 'TODO_UPDATED', type: 'TODO_UPDATED',
payload: { user: state.user, newTitle: a.payload.newTitle } payload: { user: state.user, newTitle: a.payload.newTitle },
}), }),
onError: () => null onError: () => null,
}) })
); );
@ -444,34 +442,34 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([ expect(await readAll(TestBed.get(TodoEffects).loadTodo)).toEqual([
{ {
type: 'TODO_UPDATED', type: 'TODO_UPDATED',
payload: { user: 'bob', newTitle: 'newTitle' } payload: { user: 'bob', newTitle: 'newTitle' },
} },
]); ]);
done(); done();
}); });
it('should work with an operator', async done => { it('should work with an operator', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
expect( expect(
@ -479,8 +477,8 @@ describe('DataPersistence', () => {
).toEqual([ ).toEqual([
{ {
type: 'TODO_UPDATED', type: 'TODO_UPDATED',
payload: { user: 'bob', newTitle: 'newTitle' } payload: { user: 'bob', newTitle: 'newTitle' },
} },
]); ]);
done(); done();
@ -498,8 +496,8 @@ describe('DataPersistence', () => {
onError: (a, e: any) => ({ onError: (a, e: any) => ({
type: 'ERROR', type: 'ERROR',
payload: { error: e } payload: { error: e },
}) }),
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
@ -521,18 +519,18 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo);
@ -555,8 +553,8 @@ describe('DataPersistence', () => {
onError: (a, e: any) => ({ onError: (a, e: any) => ({
type: 'ERROR', type: 'ERROR',
payload: { error: e } payload: { error: e },
}) }),
}); });
constructor(private s: DataPersistence<TodosState>) {} constructor(private s: DataPersistence<TodosState>) {}
@ -578,18 +576,18 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo);
@ -616,10 +614,10 @@ describe('DataPersistence', () => {
throw new Error('boom'); throw new Error('boom');
}, },
undoAction: a => ({ undoAction: (a) => ({
type: 'UNDO_UPDATE_TODO', type: 'UNDO_UPDATE_TODO',
payload: a.payload payload: a.payload,
}) }),
}); });
@Effect() @Effect()
@ -631,10 +629,10 @@ describe('DataPersistence', () => {
throw new Error('boom'); throw new Error('boom');
}, },
undoAction: a => ({ undoAction: (a) => ({
type: 'UNDO_UPDATE_TODO', type: 'UNDO_UPDATE_TODO',
payload: a.payload payload: a.payload,
}) }),
}) })
); );
@ -657,18 +655,18 @@ describe('DataPersistence', () => {
{ {
runtimeChecks: { runtimeChecks: {
strictStateImmutability: false, strictStateImmutability: false,
strictStateSerializability: false strictStateSerializability: false,
},
} }
} ),
) ],
]
}); });
}); });
it('should work', async done => { it('should work', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo); const [a]: any = await readAll(TestBed.get(TodoEffects).loadTodo);
@ -679,10 +677,10 @@ describe('DataPersistence', () => {
done(); done();
}); });
it('should work with an operator', async done => { it('should work with an operator', async (done) => {
actions = of({ actions = of({
type: 'UPDATE_TODO', type: 'UPDATE_TODO',
payload: { newTitle: 'newTitle' } payload: { newTitle: 'newTitle' },
}); });
const [a]: any = await readAll( const [a]: any = await readAll(

View File

@ -3,7 +3,7 @@ import { readAll, readFirst } from '../testing/src/testing-utils';
describe('TestingUtils', () => { describe('TestingUtils', () => {
describe('readAll', () => { describe('readAll', () => {
it('should transform Observable<T> to Promise<Array<T>>', async done => { it('should transform Observable<T> to Promise<Array<T>>', async (done) => {
const obs = from([1, 2, 3]); const obs = from([1, 2, 3]);
const result = await readAll(obs); const result = await readAll(obs);
@ -14,7 +14,7 @@ describe('TestingUtils', () => {
}); });
describe('readFirst', () => { describe('readFirst', () => {
it('should transform first item emitted from Observable<T> to Promise<T>', async done => { it('should transform first item emitted from Observable<T> to Promise<T>', async (done) => {
const obs = from([1, 2, 3]); const obs = from([1, 2, 3]);
const result = await readFirst(obs); const result = await readFirst(obs);

View File

@ -5,7 +5,7 @@ import { getMockContext } from '../../utils/testing';
import * as projectGraphUtils from '@nrwl/workspace/src/core/project-graph'; import * as projectGraphUtils from '@nrwl/workspace/src/core/project-graph';
import { import {
ProjectGraph, ProjectGraph,
ProjectType ProjectType,
} from '@nrwl/workspace/src/core/project-graph'; } from '@nrwl/workspace/src/core/project-graph';
import * as fileUtils from '@nrwl/workspace/src/utils/fileutils'; import * as fileUtils from '@nrwl/workspace/src/utils/fileutils';
@ -48,21 +48,21 @@ describe('AngularLibraryWebBuildBuilder', () => {
return { return {
options: { options: {
paths: { paths: {
'@proj/buildable-child': [] '@proj/buildable-child': [],
} },
} },
}; };
}); });
spyOn(fileUtils, 'fileExists').and.returnValue(true); spyOn(fileUtils, 'fileExists').and.returnValue(true);
context.target = { context.target = {
project: 'buildable-parent', project: 'buildable-parent',
target: 'build' target: 'build',
}; };
testOptions = { testOptions = {
tsConfig: 'libs/publishable-parent/tsconfig.lib.json', tsConfig: 'libs/publishable-parent/tsconfig.lib.json',
project: 'libs/publishable-parent/ng-package.json' project: 'libs/publishable-parent/ng-package.json',
}; };
}); });
@ -73,10 +73,10 @@ describe('AngularLibraryWebBuildBuilder', () => {
'buildable-parent': { 'buildable-parent': {
type: ProjectType.lib, type: ProjectType.lib,
name: 'buildable-parent', name: 'buildable-parent',
data: { files: [], root: 'libs/buildable-parent' } data: { files: [], root: 'libs/buildable-parent' },
}
}, },
dependencies: {} },
dependencies: {},
} as ProjectGraph; } as ProjectGraph;
}); });
@ -101,10 +101,10 @@ describe('AngularLibraryWebBuildBuilder', () => {
root: 'libs/buildable-parent', root: 'libs/buildable-parent',
architect: { architect: {
build: { build: {
builder: 'any builder' builder: 'any builder',
} },
} },
} },
}, },
'buildable-child': { 'buildable-child': {
type: ProjectType.lib, type: ProjectType.lib,
@ -115,22 +115,22 @@ describe('AngularLibraryWebBuildBuilder', () => {
prefix: 'proj', prefix: 'proj',
architect: { architect: {
build: { build: {
builder: 'any builder' builder: 'any builder',
} },
} },
} },
} },
}, },
dependencies: { dependencies: {
'buildable-parent': [ 'buildable-parent': [
{ {
type: ProjectType.lib, type: ProjectType.lib,
target: 'buildable-child', target: 'buildable-child',
source: null source: null,
} },
], ],
'buildable-child': [] 'buildable-child': [],
} },
} as ProjectGraph; } as ProjectGraph;
}); });
}); });
@ -138,7 +138,7 @@ describe('AngularLibraryWebBuildBuilder', () => {
it('should properly set the TSConfig paths', async () => { it('should properly set the TSConfig paths', async () => {
spyOn(fileUtils, 'readJsonFile').and.returnValue({ spyOn(fileUtils, 'readJsonFile').and.returnValue({
name: '@proj/buildable-child', name: '@proj/buildable-child',
version: '1.2.3' version: '1.2.3',
}); });
// act // act
@ -149,8 +149,8 @@ describe('AngularLibraryWebBuildBuilder', () => {
expect(ngPackagrMock.withTsConfig).toHaveBeenCalledWith( expect(ngPackagrMock.withTsConfig).toHaveBeenCalledWith(
jasmine.objectContaining({ jasmine.objectContaining({
options: { options: {
paths: { '@proj/buildable-child': ['dist/libs/buildable-child'] } paths: { '@proj/buildable-child': ['dist/libs/buildable-child'] },
} },
}) })
); );
}); });
@ -160,12 +160,12 @@ describe('AngularLibraryWebBuildBuilder', () => {
if (path.endsWith('buildable-parent/package.json')) { if (path.endsWith('buildable-parent/package.json')) {
return { return {
name: '@proj/buildable-parent', name: '@proj/buildable-parent',
version: '3.3.3' version: '3.3.3',
}; };
} else { } else {
return { return {
name: '@proj/buildable-child', name: '@proj/buildable-child',
version: '1.2.3' version: '1.2.3',
}; };
} }
}); });
@ -179,8 +179,8 @@ describe('AngularLibraryWebBuildBuilder', () => {
'dist/libs/buildable-parent/package.json', 'dist/libs/buildable-parent/package.json',
jasmine.objectContaining({ jasmine.objectContaining({
dependencies: { dependencies: {
'@proj/buildable-child': '1.2.3' '@proj/buildable-child': '1.2.3',
} },
}) })
); );
}); });
@ -194,13 +194,13 @@ describe('AngularLibraryWebBuildBuilder', () => {
name: '@proj/buildable-parent', name: '@proj/buildable-parent',
version: '1.2.3', version: '1.2.3',
[depConfigName]: { [depConfigName]: {
'@proj/buildable-child': '1.1.1' '@proj/buildable-child': '1.1.1',
} },
}; };
} else { } else {
return { return {
name: '@proj/buildable-child', name: '@proj/buildable-child',
version: '1.2.3' version: '1.2.3',
}; };
} }
}); });

View File

@ -1,7 +1,7 @@
import { import {
BuilderContext, BuilderContext,
BuilderOutput, BuilderOutput,
createBuilder createBuilder,
} from '@angular-devkit/architect'; } from '@angular-devkit/architect';
import { JsonObject } from '@angular-devkit/core'; import { JsonObject } from '@angular-devkit/core';
import * as ng from '@angular/compiler-cli'; import * as ng from '@angular/compiler-cli';
@ -13,7 +13,7 @@ import {
checkDependentProjectsHaveBeenBuilt, checkDependentProjectsHaveBeenBuilt,
DependentBuildableProjectNode, DependentBuildableProjectNode,
updateBuildableProjectPackageJsonDependencies, updateBuildableProjectPackageJsonDependencies,
updatePaths updatePaths,
} from '@nrwl/workspace/src/utils/buildable-libs-utils'; } from '@nrwl/workspace/src/utils/buildable-libs-utils';
import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph'; import { createProjectGraph } from '@nrwl/workspace/src/core/project-graph';
@ -61,10 +61,10 @@ export function run(
context context
); );
return of(checkDependentProjectsHaveBeenBuilt(context, dependencies)).pipe( return of(checkDependentProjectsHaveBeenBuilt(context, dependencies)).pipe(
switchMap(result => { switchMap((result) => {
if (result) { if (result) {
return from(initializeNgPackagr(options, context, dependencies)).pipe( return from(initializeNgPackagr(options, context, dependencies)).pipe(
switchMap(packager => switchMap((packager) =>
options.watch ? packager.watch() : packager.build() options.watch ? packager.watch() : packager.build()
), ),
tap(() => { tap(() => {

View File

@ -4,7 +4,7 @@ import { createEmptyWorkspace } from '@nrwl/workspace/testing';
import { runMigration } from '@nrwl/workspace/src/utils/testing'; import { runMigration } from '@nrwl/workspace/src/utils/testing';
import { import {
SchematicTestRunner, SchematicTestRunner,
UnitTestTree UnitTestTree,
} from '@angular-devkit/schematics/testing'; } from '@angular-devkit/schematics/testing';
import { join } from 'path'; import { join } from 'path';
@ -30,23 +30,23 @@ describe('Update Angular library builder', () => {
projectType: 'library', projectType: 'library',
architect: { architect: {
build: { build: {
builder: '@angular-devkit/build-ng-packagr:build' builder: '@angular-devkit/build-ng-packagr:build',
} },
} },
}, },
['anotherbuildable-lib']: { ['anotherbuildable-lib']: {
projectType: 'library', projectType: 'library',
architect: { architect: {
build: { build: {
builder: '@angular-devkit/build-ng-packagr:build' builder: '@angular-devkit/build-ng-packagr:build',
} },
} },
}, },
['nonbuildable-lib']: { ['nonbuildable-lib']: {
projectType: 'library', projectType: 'library',
architect: {} architect: {},
} },
} },
}) })
); );

View File

@ -2,7 +2,7 @@ import {
chain, chain,
Rule, Rule,
SchematicContext, SchematicContext,
Tree Tree,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { stripIndents } from '@angular-devkit/core/src/utils/literals';
import { formatFiles } from '@nrwl/workspace/src/utils/rules/format-files'; import { formatFiles } from '@nrwl/workspace/src/utils/rules/format-files';
@ -10,8 +10,8 @@ import { readWorkspaceJson, updateWorkspaceInTree } from '@nrwl/workspace';
export default function (): Rule { export default function (): Rule {
return chain([ return chain([
updateWorkspaceInTree(config => { updateWorkspaceInTree((config) => {
Object.keys(config.projects).forEach(name => { Object.keys(config.projects).forEach((name) => {
if ( if (
config.projects[name].architect && config.projects[name].architect &&
config.projects[name].architect.build && config.projects[name].architect.build &&
@ -25,6 +25,6 @@ export default function(): Rule {
return config; return config;
}), }),
, ,
formatFiles() formatFiles(),
]); ]);
} }

View File

@ -5,14 +5,14 @@ import {
formatFiles, formatFiles,
updateJsonInTree, updateJsonInTree,
checkAndCleanWithSemver, checkAndCleanWithSemver,
addInstallTask addInstallTask,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { gt } from 'semver'; import { gt } from 'semver';
function updateCLI() { function updateCLI() {
const tasks: TaskId[] = []; const tasks: TaskId[] = [];
const rule = chain([ const rule = chain([
updateJsonInTree('package.json', json => { updateJsonInTree('package.json', (json) => {
json.devDependencies = json.devDependencies || {}; json.devDependencies = json.devDependencies || {};
const cliVersion = json.devDependencies['@angular/cli']; const cliVersion = json.devDependencies['@angular/cli'];
const cleanCliVersion = checkAndCleanWithSemver( const cleanCliVersion = checkAndCleanWithSemver(
@ -39,7 +39,7 @@ function updateCLI() {
return json; return json;
}), }),
addInstallTask() addInstallTask(),
]); ]);
return { rule, tasks }; return { rule, tasks };
@ -52,7 +52,7 @@ function updateNgrx(updateDeps: TaskId[]) {
if (dependencies && dependencies['@ngrx/store']) { if (dependencies && dependencies['@ngrx/store']) {
return chain([ return chain([
addUpdateTask('@ngrx/store', '8.1.0', updateDeps), addUpdateTask('@ngrx/store', '8.1.0', updateDeps),
formatFiles() formatFiles(),
]); ]);
} }

View File

@ -2,7 +2,7 @@ import { Tree } from '@angular-devkit/schematics';
import { readJsonInTree } from '@nrwl/workspace'; import { readJsonInTree } from '@nrwl/workspace';
import { import {
SchematicTestRunner, SchematicTestRunner,
UnitTestTree UnitTestTree,
} from '@angular-devkit/schematics/testing'; } from '@angular-devkit/schematics/testing';
import { serializeJson } from '@nrwl/workspace'; import { serializeJson } from '@nrwl/workspace';
import { runMigration } from '../../utils/testing'; import { runMigration } from '../../utils/testing';
@ -21,8 +21,8 @@ describe('Update 8.5.0', () => {
'package.json', 'package.json',
serializeJson({ serializeJson({
devDependencies: { devDependencies: {
'@angular/cli': '8.0.0' '@angular/cli': '8.0.0',
} },
}) })
); );
@ -38,8 +38,8 @@ describe('Update 8.5.0', () => {
'package.json', 'package.json',
serializeJson({ serializeJson({
devDependencies: { devDependencies: {
'@angular/cli': '^8.0.0' '@angular/cli': '^8.0.0',
} },
}) })
); );
@ -55,8 +55,8 @@ describe('Update 8.5.0', () => {
'package.json', 'package.json',
serializeJson({ serializeJson({
devDependencies: { devDependencies: {
'@angular/cli': '~8.0.0' '@angular/cli': '~8.0.0',
} },
}) })
); );
@ -74,8 +74,8 @@ describe('Update 8.5.0', () => {
'package.json', 'package.json',
serializeJson({ serializeJson({
devDependencies: { devDependencies: {
'@angular/cli': '>=8.0.0' '@angular/cli': '>=8.0.0',
} },
}) })
); );

View File

@ -5,7 +5,7 @@ import {
formatFiles, formatFiles,
updateJsonInTree, updateJsonInTree,
checkAndCleanWithSemver, checkAndCleanWithSemver,
addInstallTask addInstallTask,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { gt } from 'semver'; import { gt } from 'semver';
@ -14,7 +14,7 @@ const updateAngular = addUpdateTask('@angular/core', '8.2.4');
function updateCLI() { function updateCLI() {
const tasks: TaskId[] = []; const tasks: TaskId[] = [];
const rule = chain([ const rule = chain([
updateJsonInTree('package.json', json => { updateJsonInTree('package.json', (json) => {
json.devDependencies = json.devDependencies || {}; json.devDependencies = json.devDependencies || {};
const cliVersion = json.devDependencies['@angular/cli']; const cliVersion = json.devDependencies['@angular/cli'];
const cleanCliVersion = checkAndCleanWithSemver( const cleanCliVersion = checkAndCleanWithSemver(
@ -41,7 +41,7 @@ function updateCLI() {
return json; return json;
}), }),
addInstallTask() addInstallTask(),
]); ]);
return { rule, tasks }; return { rule, tasks };
@ -54,7 +54,7 @@ function updateNgrx(updateDeps: TaskId[]) {
if (dependencies && dependencies['@ngrx/store']) { if (dependencies && dependencies['@ngrx/store']) {
return chain([ return chain([
addUpdateTask('@ngrx/store', '8.3.0', updateDeps), addUpdateTask('@ngrx/store', '8.3.0', updateDeps),
formatFiles() formatFiles(),
]); ]);
} }
@ -68,6 +68,6 @@ export default function() {
updateAngular, updateAngular,
updateCLIRule, updateCLIRule,
updateNgrx(tasks), updateNgrx(tasks),
formatFiles() formatFiles(),
]); ]);
} }

View File

@ -6,7 +6,10 @@ describe('add-postinstall', () => {
let tree: Tree; let tree: Tree;
beforeEach(async () => { beforeEach(async () => {
tree = Tree.empty(); tree = Tree.empty();
tree = await callRule(updateJsonInTree('package.json', () => ({})), tree); tree = await callRule(
updateJsonInTree('package.json', () => ({})),
tree
);
}); });
it('should add a postinstall for "ngcc"', async () => { it('should add a postinstall for "ngcc"', async () => {
const result = await runMigration('add-postinstall', {}, tree); const result = await runMigration('add-postinstall', {}, tree);
@ -20,9 +23,9 @@ describe('add-postinstall', () => {
it('should not add a postinstall if one exists', async () => { it('should not add a postinstall if one exists', async () => {
tree = await callRule( tree = await callRule(
updateJsonInTree('package.json', json => { updateJsonInTree('package.json', (json) => {
json.scripts = { json.scripts = {
postinstall: './postinstall.sh' postinstall: './postinstall.sh',
}; };
return json; return json;
}), }),

View File

@ -24,6 +24,6 @@ export default function() {
} }
return json; return json;
}), }),
formatFiles() formatFiles(),
]); ]);
} }

View File

@ -15,7 +15,7 @@ export default function() {
return chain([ return chain([
addUpdateTask('@angular/core', '9.0.0', [postInstallTask]), addUpdateTask('@angular/core', '9.0.0', [postInstallTask]),
addUpdateTask('@angular/cli', '9.0.1', [postInstallTask]), addUpdateTask('@angular/cli', '9.0.1', [postInstallTask]),
formatFiles() formatFiles(),
]); ]);
}; };
} }

View File

@ -12,7 +12,7 @@ import {
map, map,
mergeMap, mergeMap,
switchMap, switchMap,
withLatestFrom withLatestFrom,
} from 'rxjs/operators'; } from 'rxjs/operators';
/** /**
@ -83,7 +83,7 @@ export function fetch<T, A extends Action>(opts: FetchOpts<T, A>) {
); );
return groupedFetches.pipe( return groupedFetches.pipe(
mergeMap(pairs => mergeMap((pairs) =>
pairs.pipe(switchMap(runWithErrorHandling(opts.run, opts.onError))) pairs.pipe(switchMap(runWithErrorHandling(opts.run, opts.onError)))
) )
); );
@ -113,7 +113,7 @@ export function navigation<T, A extends Action>(
return [ return [
findSnapshot(component, action.payload.routerState.root), findSnapshot(component, action.payload.routerState.root),
state state,
] as [ActivatedRouteSnapshot, T]; ] as [ActivatedRouteSnapshot, T];
}), }),
filter(([snapshot, state]) => !!snapshot) filter(([snapshot, state]) => !!snapshot)
@ -136,7 +136,7 @@ function runWithErrorHandling<T, A, R>(
return ([action, state]: [A, T]): Observable<R> => { return ([action, state]: [A, T]): Observable<R> => {
try { try {
const r = wrapIntoObservable(run(action, state)); const r = wrapIntoObservable(run(action, state));
return r.pipe(catchError(e => wrapIntoObservable(onError(action, e)))); return r.pipe(catchError((e) => wrapIntoObservable(onError(action, e))));
} catch (e) { } catch (e) {
return wrapIntoObservable(onError(action, e)); return wrapIntoObservable(onError(action, e));
} }
@ -150,7 +150,7 @@ function runWithErrorHandling<T, A, R>(
function mapActionAndState<T, A>() { function mapActionAndState<T, A>() {
return (source: Observable<ActionOrActionWithState<T, A>>) => { return (source: Observable<ActionOrActionWithState<T, A>>) => {
return source.pipe( return source.pipe(
map(value => { map((value) => {
const [action, store] = normalizeActionAndState(value); const [action, store] = normalizeActionAndState(value);
return [action, store] as [A, T]; return [action, store] as [A, T];
}) })

View File

@ -45,12 +45,12 @@ describe('app', () => {
const nxJson = readJsonInTree<NxJson>(tree, '/nx.json'); const nxJson = readJsonInTree<NxJson>(tree, '/nx.json');
expect(nxJson.projects).toEqual({ expect(nxJson.projects).toEqual({
'my-app': { 'my-app': {
tags: ['one', 'two'] tags: ['one', 'two'],
}, },
'my-app-e2e': { 'my-app-e2e': {
implicitDependencies: ['my-app'], implicitDependencies: ['my-app'],
tags: [] tags: [],
} },
}); });
}); });
@ -138,9 +138,9 @@ describe('app', () => {
xit('should work if the new project root is changed', async () => { xit('should work if the new project root is changed', async () => {
appTree = await callRule( appTree = await callRule(
updateJsonInTree('/workspace.json', json => ({ updateJsonInTree('/workspace.json', (json) => ({
...json, ...json,
newProjectRoot: 'newProjectRoot' newProjectRoot: 'newProjectRoot',
})), })),
appTree appTree
); );
@ -191,12 +191,12 @@ describe('app', () => {
const nxJson = readJsonInTree<NxJson>(tree, '/nx.json'); const nxJson = readJsonInTree<NxJson>(tree, '/nx.json');
expect(nxJson.projects).toEqual({ expect(nxJson.projects).toEqual({
'my-dir-my-app': { 'my-dir-my-app': {
tags: ['one', 'two'] tags: ['one', 'two'],
}, },
'my-dir-my-app-e2e': { 'my-dir-my-app-e2e': {
implicitDependencies: ['my-dir-my-app'], implicitDependencies: ['my-dir-my-app'],
tags: [] tags: [],
} },
}); });
}); });
@ -222,8 +222,8 @@ describe('app', () => {
'apps/my-dir/my-app/src/main.ts', 'apps/my-dir/my-app/src/main.ts',
'apps/my-dir/my-app/src/app/app.module.ts', 'apps/my-dir/my-app/src/app/app.module.ts',
'apps/my-dir/my-app/src/app/app.component.ts', 'apps/my-dir/my-app/src/app/app.component.ts',
'apps/my-dir/my-app-e2e/cypress.json' 'apps/my-dir/my-app-e2e/cypress.json',
].forEach(path => { ].forEach((path) => {
expect(tree.exists(path)).toBeTruthy(); expect(tree.exists(path)).toBeTruthy();
}); });
@ -231,18 +231,18 @@ describe('app', () => {
[ [
{ {
path: 'apps/my-dir/my-app/tsconfig.json', path: 'apps/my-dir/my-app/tsconfig.json',
lookupFn: json => json.extends, lookupFn: (json) => json.extends,
expectedValue: '../../../tsconfig.json' expectedValue: '../../../tsconfig.json',
}, },
{ {
path: 'apps/my-dir/my-app/tsconfig.app.json', path: 'apps/my-dir/my-app/tsconfig.app.json',
lookupFn: json => json.compilerOptions.outDir, lookupFn: (json) => json.compilerOptions.outDir,
expectedValue: '../../../dist/out-tsc' expectedValue: '../../../dist/out-tsc',
}, },
{ {
path: 'apps/my-dir/my-app-e2e/tsconfig.json', path: 'apps/my-dir/my-app-e2e/tsconfig.json',
lookupFn: json => json.extends, lookupFn: (json) => json.extends,
expectedValue: '../../../tsconfig.json' expectedValue: '../../../tsconfig.json',
}, },
// { // {
// path: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json', // path: 'apps/my-dir/my-app-e2e/tsconfig.e2e.json',
@ -251,9 +251,9 @@ describe('app', () => {
// }, // },
{ {
path: 'apps/my-dir/my-app/tslint.json', path: 'apps/my-dir/my-app/tslint.json',
lookupFn: json => json.extends, lookupFn: (json) => json.extends,
expectedValue: '../../../tslint.json' expectedValue: '../../../tslint.json',
} },
].forEach(hasJsonValue); ].forEach(hasJsonValue);
}); });
}); });
@ -349,8 +349,8 @@ describe('app', () => {
expect(workspaceJson.projects['my-app'].schematics).toEqual({ expect(workspaceJson.projects['my-app'].schematics).toEqual({
'@nrwl/angular:component': { '@nrwl/angular:component': {
style: 'scss' style: 'scss',
} },
}); });
}); });
}); });
@ -390,7 +390,7 @@ describe('app', () => {
workspaceJson.projects['my-app'].architect.lint.options.tsConfig workspaceJson.projects['my-app'].architect.lint.options.tsConfig
).toEqual([ ).toEqual([
'apps/my-app/tsconfig.app.json', 'apps/my-app/tsconfig.app.json',
'apps/my-app/tsconfig.spec.json' 'apps/my-app/tsconfig.spec.json',
]); ]);
const tsconfigAppJson = readJsonInTree( const tsconfigAppJson = readJsonInTree(
tree, tree,
@ -444,22 +444,22 @@ describe('app', () => {
builder: '@angular-devkit/build-angular:protractor', builder: '@angular-devkit/build-angular:protractor',
options: { options: {
devServerTarget: 'my-app:serve', devServerTarget: 'my-app:serve',
protractorConfig: 'apps/my-app-e2e/protractor.conf.js' protractorConfig: 'apps/my-app-e2e/protractor.conf.js',
}, },
configurations: { configurations: {
production: { production: {
devServerTarget: 'my-app:serve:production' devServerTarget: 'my-app:serve:production',
} },
} },
}, },
lint: { lint: {
builder: '@angular-devkit/build-angular:tslint', builder: '@angular-devkit/build-angular:tslint',
options: { options: {
tsConfig: 'apps/my-app-e2e/tsconfig.e2e.json', tsConfig: 'apps/my-app-e2e/tsconfig.e2e.json',
exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'] exclude: ['**/node_modules/**', '!apps/my-app-e2e/**'],
} },
} },
} },
}); });
}); });
@ -527,8 +527,8 @@ describe('app', () => {
{ {
'/customer-api': { '/customer-api': {
target: 'http://localhost:3333', target: 'http://localhost:3333',
secure: false secure: false,
} },
}, },
null, null,
2 2

View File

@ -10,7 +10,7 @@ import {
SchematicContext, SchematicContext,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { Schema } from './schema'; import { Schema } from './schema';
import * as ts from 'typescript'; import * as ts from 'typescript';
@ -27,19 +27,19 @@ import {
updateJsonInTree, updateJsonInTree,
updateWorkspace, updateWorkspace,
addLintFiles, addLintFiles,
NxJson NxJson,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { join, normalize } from '@angular-devkit/core'; import { join, normalize } from '@angular-devkit/core';
import init from '../init/init'; import init from '../init/init';
import { import {
addImportToModule, addImportToModule,
addImportToTestBed, addImportToTestBed,
getDecoratorPropertyValueNode getDecoratorPropertyValueNode,
} from '../../utils/ast-utils'; } from '../../utils/ast-utils';
import { import {
insertImport, insertImport,
getProjectConfig, getProjectConfig,
updateWorkspaceInTree updateWorkspaceInTree,
} from '@nrwl/workspace/src/utils/ast-utils'; } from '@nrwl/workspace/src/utils/ast-utils';
interface NormalizedSchema extends Schema { interface NormalizedSchema extends Schema {
@ -272,7 +272,7 @@ summary {
width: 16px; width: 16px;
margin-right: 4px; margin-right: 4px;
} }
` `,
}; };
function addRouterRootConfiguration(options: NormalizedSchema): Rule { function addRouterRootConfiguration(options: NormalizedSchema): Rule {
@ -291,7 +291,7 @@ function addRouterRootConfiguration(options: NormalizedSchema): Rule {
sourceFile, sourceFile,
modulePath, modulePath,
`RouterModule.forRoot([], {initialNavigation: 'enabled'})` `RouterModule.forRoot([], {initialNavigation: 'enabled'})`
) ),
]); ]);
return host; return host;
@ -307,7 +307,7 @@ function updateComponentStyles(options: NormalizedSchema): Rule {
css: `${options.appProjectRoot}/src/app/app.component.css`, css: `${options.appProjectRoot}/src/app/app.component.css`,
scss: `${options.appProjectRoot}/src/app/app.component.scss`, scss: `${options.appProjectRoot}/src/app/app.component.scss`,
less: `${options.appProjectRoot}/src/app/app.component.less`, less: `${options.appProjectRoot}/src/app/app.component.less`,
styl: `${options.appProjectRoot}/src/app/app.component.styl` styl: `${options.appProjectRoot}/src/app/app.component.styl`,
}; };
return host.overwrite(filesMap[options.style], content); return host.overwrite(filesMap[options.style], content);
} }
@ -401,7 +401,7 @@ function updateComponentSpec(options: NormalizedSchema) {
componentSpecSourceFile, componentSpecSourceFile,
componentSpecPath, componentSpecPath,
`RouterTestingModule` `RouterTestingModule`
) ),
]); ]);
} }
} }
@ -412,7 +412,7 @@ function updateComponentSpec(options: NormalizedSchema) {
function updateLinting(options: NormalizedSchema): Rule { function updateLinting(options: NormalizedSchema): Rule {
return chain([ return chain([
updateJsonInTree('tslint.json', json => { updateJsonInTree('tslint.json', (json) => {
if ( if (
json.rulesDirectory && json.rulesDirectory &&
json.rulesDirectory.indexOf('node_modules/codelyzer') === -1 json.rulesDirectory.indexOf('node_modules/codelyzer') === -1
@ -434,18 +434,18 @@ function updateLinting(options: NormalizedSchema): Rule {
'template-banana-in-box': true, 'template-banana-in-box': true,
'template-no-negated-async': true, 'template-no-negated-async': true,
'use-lifecycle-interface': true, 'use-lifecycle-interface': true,
'use-pipe-transform-interface': true 'use-pipe-transform-interface': true,
}; };
} }
return json; return json;
}), }),
updateJsonInTree(`${options.appProjectRoot}/tslint.json`, json => { updateJsonInTree(`${options.appProjectRoot}/tslint.json`, (json) => {
json.extends = `${offsetFromRoot(options.appProjectRoot)}tslint.json`; json.extends = `${offsetFromRoot(options.appProjectRoot)}tslint.json`;
json.linterOptions = { json.linterOptions = {
exclude: ['!**/*'] exclude: ['!**/*'],
}; };
return json; return json;
}) }),
]); ]);
} }
@ -454,23 +454,23 @@ function addSchematicFiles(
options: NormalizedSchema options: NormalizedSchema
): Rule { ): Rule {
return chain([ return chain([
host => host.delete(`${appProjectRoot}/src/favicon.ico`), (host) => host.delete(`${appProjectRoot}/src/favicon.ico`),
mergeWith( mergeWith(
apply(url('./files'), [ apply(url('./files'), [
template({ template({
...options, ...options,
offsetFromRoot: offsetFromRoot(options.appProjectRoot) offsetFromRoot: offsetFromRoot(options.appProjectRoot),
}), }),
move(options.appProjectRoot) move(options.appProjectRoot),
]) ])
) ),
]); ]);
} }
function updateProject(options: NormalizedSchema): Rule { function updateProject(options: NormalizedSchema): Rule {
return (host: Tree) => { return (host: Tree) => {
return chain([ return chain([
updateJsonInTree(getWorkspacePath(host), json => { updateJsonInTree(getWorkspacePath(host), (json) => {
const project = json.projects[options.name]; const project = json.projects[options.name];
let fixedProject = replaceAppNameWithPath( let fixedProject = replaceAppNameWithPath(
project, project,
@ -485,11 +485,11 @@ function updateProject(options: NormalizedSchema): Rule {
'guard', 'guard',
'module', 'module',
'pipe', 'pipe',
'service' 'service',
]; ];
if (fixedProject.schematics) { if (fixedProject.schematics) {
angularSchematicNames.forEach(type => { angularSchematicNames.forEach((type) => {
const schematic = `@schematics/angular:${type}`; const schematic = `@schematics/angular:${type}`;
if (schematic in fixedProject.schematics) { if (schematic in fixedProject.schematics) {
fixedProject.schematics[`@nrwl/angular:${type}`] = fixedProject.schematics[`@nrwl/angular:${type}`] =
@ -502,7 +502,7 @@ function updateProject(options: NormalizedSchema): Rule {
delete fixedProject.architect.test; delete fixedProject.architect.test;
fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter( fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter(
path => (path) =>
path !== path !==
join(normalize(options.appProjectRoot), 'tsconfig.spec.json') && join(normalize(options.appProjectRoot), 'tsconfig.spec.json') &&
path !== path !==
@ -518,53 +518,56 @@ function updateProject(options: NormalizedSchema): Rule {
json.projects[options.name] = fixedProject; json.projects[options.name] = fixedProject;
return json; return json;
}), }),
updateJsonInTree(`${options.appProjectRoot}/tsconfig.app.json`, json => { updateJsonInTree(
`${options.appProjectRoot}/tsconfig.app.json`,
(json) => {
return { return {
...json, ...json,
extends: `./tsconfig.json`, extends: `./tsconfig.json`,
compilerOptions: { compilerOptions: {
...json.compilerOptions, ...json.compilerOptions,
outDir: `${offsetFromRoot(options.appProjectRoot)}dist/out-tsc` outDir: `${offsetFromRoot(options.appProjectRoot)}dist/out-tsc`,
}, },
exclude: options.enableIvy exclude: options.enableIvy
? undefined ? undefined
: options.unitTestRunner === 'jest' : options.unitTestRunner === 'jest'
? ['src/test-setup.ts', '**/*.spec.ts'] ? ['src/test-setup.ts', '**/*.spec.ts']
: ['src/test.ts', '**/*.spec.ts'], : ['src/test.ts', '**/*.spec.ts'],
include: options.enableIvy ? undefined : ['src/**/*.d.ts'] include: options.enableIvy ? undefined : ['src/**/*.d.ts'],
}; };
}), }
host => { ),
(host) => {
host.delete(`${options.appProjectRoot}/tsconfig.spec.json`); host.delete(`${options.appProjectRoot}/tsconfig.spec.json`);
return host; return host;
}, },
updateJsonInTree(`/nx.json`, json => { updateJsonInTree(`/nx.json`, (json) => {
const resultJson = { const resultJson = {
...json, ...json,
projects: { projects: {
...json.projects, ...json.projects,
[options.name]: { tags: options.parsedTags } [options.name]: { tags: options.parsedTags },
} },
}; };
if (options.e2eTestRunner === 'protractor') { if (options.e2eTestRunner === 'protractor') {
resultJson.projects[options.e2eProjectName] = { tags: [] }; resultJson.projects[options.e2eProjectName] = { tags: [] };
resultJson.projects[options.e2eProjectName].implicitDependencies = [ resultJson.projects[options.e2eProjectName].implicitDependencies = [
options.name options.name,
]; ];
} }
return resultJson; return resultJson;
}), }),
host => { (host) => {
host.delete(`${options.appProjectRoot}/karma.conf.js`); host.delete(`${options.appProjectRoot}/karma.conf.js`);
host.delete(`${options.appProjectRoot}/src/test.ts`); host.delete(`${options.appProjectRoot}/src/test.ts`);
} },
]); ]);
}; };
} }
function removeE2e(options: NormalizedSchema, e2eProjectRoot: string): Rule { function removeE2e(options: NormalizedSchema, e2eProjectRoot: string): Rule {
return chain([ return chain([
host => { (host) => {
if (host.read(`${e2eProjectRoot}/src/app.e2e-spec.ts`)) { if (host.read(`${e2eProjectRoot}/src/app.e2e-spec.ts`)) {
host.delete(`${e2eProjectRoot}/src/app.e2e-spec.ts`); host.delete(`${e2eProjectRoot}/src/app.e2e-spec.ts`);
} }
@ -578,9 +581,9 @@ function removeE2e(options: NormalizedSchema, e2eProjectRoot: string): Rule {
host.delete(`${e2eProjectRoot}/tsconfig.json`); host.delete(`${e2eProjectRoot}/tsconfig.json`);
} }
}, },
updateWorkspace(workspace => { updateWorkspace((workspace) => {
workspace.projects.get(options.name).targets.delete('e2e'); workspace.projects.get(options.name).targets.delete('e2e');
}) }),
]); ]);
} }
@ -602,7 +605,7 @@ function updateE2eProject(options: NormalizedSchema): Rule {
host.overwrite(page, pageContent.replace(`.content span`, `header h1`)); host.overwrite(page, pageContent.replace(`.content span`, `header h1`));
return chain([ return chain([
updateJsonInTree(getWorkspacePath(host), json => { updateJsonInTree(getWorkspacePath(host), (json) => {
const project = { const project = {
root: options.e2eProjectRoot, root: options.e2eProjectRoot,
projectType: 'application', projectType: 'application',
@ -614,11 +617,11 @@ function updateE2eProject(options: NormalizedSchema): Rule {
tsConfig: `${options.e2eProjectRoot}/tsconfig.e2e.json`, tsConfig: `${options.e2eProjectRoot}/tsconfig.e2e.json`,
exclude: [ exclude: [
'**/node_modules/**', '**/node_modules/**',
'!' + join(normalize(options.e2eProjectRoot), '**') '!' + join(normalize(options.e2eProjectRoot), '**'),
] ],
} },
} },
} },
}; };
project.architect.e2e.options.protractorConfig = `${options.e2eProjectRoot}/protractor.conf.js`; project.architect.e2e.options.protractorConfig = `${options.e2eProjectRoot}/protractor.conf.js`;
@ -627,16 +630,19 @@ function updateE2eProject(options: NormalizedSchema): Rule {
delete json.projects[options.name].architect.e2e; delete json.projects[options.name].architect.e2e;
return json; return json;
}), }),
updateJsonInTree(`${options.e2eProjectRoot}/tsconfig.e2e.json`, json => { updateJsonInTree(
`${options.e2eProjectRoot}/tsconfig.e2e.json`,
(json) => {
return { return {
...json, ...json,
extends: `./tsconfig.json`, extends: `./tsconfig.json`,
compilerOptions: { compilerOptions: {
...json.compilerOptions, ...json.compilerOptions,
outDir: `${offsetFromRoot(options.e2eProjectRoot)}dist/out-tsc` outDir: `${offsetFromRoot(options.e2eProjectRoot)}dist/out-tsc`,
} },
}; };
}) }
),
]); ]);
}; };
} }
@ -648,19 +654,19 @@ function addProxyConfig(options: NormalizedSchema): Rule {
const pathToProxyFile = `${projectConfig.root}/proxy.conf.json`; const pathToProxyFile = `${projectConfig.root}/proxy.conf.json`;
return chain([ return chain([
updateJsonInTree(pathToProxyFile, json => { updateJsonInTree(pathToProxyFile, (json) => {
return { return {
[`/${options.backendProject}`]: { [`/${options.backendProject}`]: {
target: 'http://localhost:3333', target: 'http://localhost:3333',
secure: false secure: false,
} },
}; };
}), }),
updateWorkspaceInTree(json => { updateWorkspaceInTree((json) => {
projectConfig.architect.serve.options.proxyConfig = pathToProxyFile; projectConfig.architect.serve.options.proxyConfig = pathToProxyFile;
json.projects[options.name] = projectConfig; json.projects[options.name] = projectConfig;
return json; return json;
}) }),
])(host, context); ])(host, context);
} }
}; };
@ -684,10 +690,10 @@ export default function(schema: Schema): Rule {
return chain([ return chain([
init({ init({
...options, ...options,
skipFormat: true skipFormat: true,
}), }),
addLintFiles(options.appProjectRoot, options.linter, { addLintFiles(options.appProjectRoot, options.linter, {
onlyGlobal: true onlyGlobal: true,
}), }),
externalSchematic('@schematics/angular', 'application', { externalSchematic('@schematics/angular', 'application', {
name: options.name, name: options.name,
@ -700,7 +706,7 @@ export default function(schema: Schema): Rule {
enableIvy: options.enableIvy, enableIvy: options.enableIvy,
routing: false, routing: false,
skipInstall: true, skipInstall: true,
skipPackageJson: false skipPackageJson: false,
}), }),
addSchematicFiles(appProjectRoot, options), addSchematicFiles(appProjectRoot, options),
options.e2eTestRunner === 'protractor' options.e2eTestRunner === 'protractor'
@ -721,12 +727,12 @@ export default function(schema: Schema): Rule {
project: options.name, project: options.name,
supportTsx: false, supportTsx: false,
skipSerializers: false, skipSerializers: false,
setupFile: 'angular' setupFile: 'angular',
}) })
: noop(), : noop(),
options.unitTestRunner === 'karma' options.unitTestRunner === 'karma'
? schematic('karma-project', { ? schematic('karma-project', {
project: options.name project: options.name,
}) })
: noop(), : noop(),
options.e2eTestRunner === 'cypress' options.e2eTestRunner === 'cypress'
@ -734,11 +740,11 @@ export default function(schema: Schema): Rule {
name: options.e2eProjectName, name: options.e2eProjectName,
directory: options.directory, directory: options.directory,
project: options.name, project: options.name,
linter: options.linter linter: options.linter,
}) })
: noop(), : noop(),
options.backendProject ? addProxyConfig(options) : noop(), options.backendProject ? addProxyConfig(options) : noop(),
formatFiles(options) formatFiles(options),
])(host, context); ])(host, context);
}; };
} }
@ -758,7 +764,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema {
const e2eProjectRoot = `apps/${appDirectory}-e2e`; const e2eProjectRoot = `apps/${appDirectory}-e2e`;
const parsedTags = options.tags const parsedTags = options.tags
? options.tags.split(',').map(s => s.trim()) ? options.tags.split(',').map((s) => s.trim())
: []; : [];
const defaultPrefix = getNpmScope(host); const defaultPrefix = getNpmScope(host);
@ -769,6 +775,6 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema {
appProjectRoot, appProjectRoot,
e2eProjectRoot, e2eProjectRoot,
e2eProjectName, e2eProjectName,
parsedTags parsedTags,
}; };
} }

View File

@ -8,18 +8,18 @@ import {
SchematicsException, SchematicsException,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { findNodes, getProjectConfig } from '@nrwl/workspace'; import { findNodes, getProjectConfig } from '@nrwl/workspace';
import { import {
PropertyAssignment, PropertyAssignment,
PropertyDeclaration, PropertyDeclaration,
SyntaxKind SyntaxKind,
} from 'typescript'; } from 'typescript';
import { getTsSourceFile, getDecoratorMetadata } from '../../utils/ast-utils'; import { getTsSourceFile, getDecoratorMetadata } from '../../utils/ast-utils';
import { import {
getInputPropertyDeclarations, getInputPropertyDeclarations,
getKnobType getKnobType,
} from '../component-story/component-story'; } from '../component-story/component-story';
import { applyWithSkipExisting } from '@nrwl/workspace/src/utils/ast-utils'; import { applyWithSkipExisting } from '@nrwl/workspace/src/utils/ast-utils';
@ -40,7 +40,7 @@ export function createComponentSpecFile({
libPath, libPath,
componentName, componentName,
componentPath, componentPath,
componentFileName componentFileName,
}: CreateComponentSpecFileSchema): Rule { }: CreateComponentSpecFileSchema): Rule {
return (tree: Tree, context: SchematicContext): Rule => { return (tree: Tree, context: SchematicContext): Rule => {
const e2eLibIntegrationFolderPath = const e2eLibIntegrationFolderPath =
@ -48,7 +48,7 @@ export function createComponentSpecFile({
const fullComponentPath = const fullComponentPath =
libPath + '/' + componentPath + '/' + componentFileName + '.ts'; libPath + '/' + componentPath + '/' + componentFileName + '.ts';
const props = getInputPropertyDeclarations(tree, fullComponentPath).map( const props = getInputPropertyDeclarations(tree, fullComponentPath).map(
node => { (node) => {
const decoratorContent = findNodes( const decoratorContent = findNodes(
findNodes(node, SyntaxKind.Decorator)[0], findNodes(node, SyntaxKind.Decorator)[0],
SyntaxKind.StringLiteral SyntaxKind.StringLiteral
@ -63,7 +63,7 @@ export function createComponentSpecFile({
return { return {
name, name,
type, type,
defaultValue defaultValue,
}; };
} }
); );
@ -75,9 +75,9 @@ export function createComponentSpecFile({
componentName: componentName, componentName: componentName,
componentSelector, componentSelector,
props, props,
tmpl: '' tmpl: '',
}), }),
move(e2eLibIntegrationFolderPath + '/' + componentPath) move(e2eLibIntegrationFolderPath + '/' + componentPath),
]); ]);
}; };
} }

View File

@ -5,14 +5,14 @@ import {
SchematicContext, SchematicContext,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { findNodes } from '@nrwl/workspace'; import { findNodes } from '@nrwl/workspace';
import { PropertyDeclaration, SyntaxKind } from 'typescript'; import { PropertyDeclaration, SyntaxKind } from 'typescript';
import { getTsSourceFile } from '../../utils/ast-utils'; import { getTsSourceFile } from '../../utils/ast-utils';
import { import {
getSourceNodes, getSourceNodes,
applyWithSkipExisting applyWithSkipExisting,
} from '@nrwl/workspace/src/utils/ast-utils'; } from '@nrwl/workspace/src/utils/ast-utils';
export interface CreateComponentStoriesFileSchema { export interface CreateComponentStoriesFileSchema {
@ -30,7 +30,7 @@ export function createComponentStoriesFile({
libPath, libPath,
componentName, componentName,
componentPath, componentPath,
componentFileName componentFileName,
}: CreateComponentStoriesFileSchema): Rule { }: CreateComponentStoriesFileSchema): Rule {
return (tree: Tree, context: SchematicContext): Rule => { return (tree: Tree, context: SchematicContext): Rule => {
const props = getInputDescriptors( const props = getInputDescriptors(
@ -42,9 +42,9 @@ export function createComponentStoriesFile({
componentFileName: componentFileName, componentFileName: componentFileName,
componentName: componentName, componentName: componentName,
props, props,
tmpl: '' tmpl: '',
}), }),
move(libPath + '/' + componentPath) move(libPath + '/' + componentPath),
]); ]);
}; };
} }
@ -63,23 +63,23 @@ export function getInputPropertyDeclarations(
const file = getTsSourceFile(tree, path); const file = getTsSourceFile(tree, path);
const decorators = getSourceNodes(file).filter( const decorators = getSourceNodes(file).filter(
node => node.kind === SyntaxKind.Decorator (node) => node.kind === SyntaxKind.Decorator
); );
return decorators return decorators
.filter(decorator => .filter((decorator) =>
findNodes(decorator, SyntaxKind.Identifier).some( findNodes(decorator, SyntaxKind.Identifier).some(
node => node.getText() === 'Input' (node) => node.getText() === 'Input'
) )
) )
.map(node => node.parent as PropertyDeclaration); .map((node) => node.parent as PropertyDeclaration);
} }
export function getInputDescriptors( export function getInputDescriptors(
tree: Tree, tree: Tree,
path: string path: string
): InputDescriptor[] { ): InputDescriptor[] {
return getInputPropertyDeclarations(tree, path).map(node => { return getInputPropertyDeclarations(tree, path).map((node) => {
const decoratorContent = findNodes( const decoratorContent = findNodes(
findNodes(node, SyntaxKind.Decorator)[0], findNodes(node, SyntaxKind.Decorator)[0],
SyntaxKind.StringLiteral SyntaxKind.StringLiteral
@ -94,7 +94,7 @@ export function getInputDescriptors(
return { return {
name, name,
type, type,
defaultValue defaultValue,
}; };
}); });
} }
@ -105,7 +105,7 @@ export function getKnobType(property: PropertyDeclaration): KnobType {
const typeNameToKnobType: Record<string, KnobType> = { const typeNameToKnobType: Record<string, KnobType> = {
string: 'text', string: 'text',
number: 'number', number: 'number',
boolean: 'boolean' boolean: 'boolean',
}; };
return typeNameToKnobType[typeName] || 'text'; return typeNameToKnobType[typeName] || 'text';
} }
@ -114,7 +114,7 @@ export function getKnobType(property: PropertyDeclaration): KnobType {
[SyntaxKind.StringLiteral]: 'text', [SyntaxKind.StringLiteral]: 'text',
[SyntaxKind.NumericLiteral]: 'number', [SyntaxKind.NumericLiteral]: 'number',
[SyntaxKind.TrueKeyword]: 'boolean', [SyntaxKind.TrueKeyword]: 'boolean',
[SyntaxKind.FalseKeyword]: 'boolean' [SyntaxKind.FalseKeyword]: 'boolean',
}; };
return initializerKindToKnobType[property.initializer.kind] || 'text'; return initializerKindToKnobType[property.initializer.kind] || 'text';
} }
@ -125,7 +125,7 @@ export function getKnobDefaultValue(property: PropertyDeclaration): string {
const typeNameToDefault = { const typeNameToDefault = {
string: "''", string: "''",
number: '0', number: '0',
boolean: 'false' boolean: 'false',
}; };
return property.initializer return property.initializer
? property.initializer.getText() ? property.initializer.getText()

View File

@ -17,7 +17,7 @@ describe('downgrade-module', () => {
'downgrade-module', 'downgrade-module',
{ {
name: 'legacy', name: 'legacy',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -35,7 +35,7 @@ describe('downgrade-module', () => {
'downgrade-module', 'downgrade-module',
{ {
name: 'legacy', name: 'legacy',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -51,8 +51,8 @@ describe('downgrade-module', () => {
`/package.json`, `/package.json`,
JSON.stringify({ JSON.stringify({
dependencies: { dependencies: {
'@angular/core': '4.4.4' '@angular/core': '4.4.4',
} },
}) })
); );
@ -60,7 +60,7 @@ describe('downgrade-module', () => {
'downgrade-module', 'downgrade-module',
{ {
name: 'legacy', name: 'legacy',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -75,8 +75,8 @@ describe('downgrade-module', () => {
`/package.json`, `/package.json`,
JSON.stringify({ JSON.stringify({
dependencies: { dependencies: {
'@angular/core': '4.4.4' '@angular/core': '4.4.4',
} },
}) })
); );
@ -85,7 +85,7 @@ describe('downgrade-module', () => {
{ {
name: 'legacy', name: 'legacy',
skipPackageJson: true, skipPackageJson: true,
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -100,7 +100,7 @@ describe('downgrade-module', () => {
{ {
name: 'legacy', name: 'legacy',
angularJsImport: 'legacy-app', angularJsImport: 'legacy-app',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );

View File

@ -6,7 +6,7 @@ import { addUpgradeToPackageJson } from '../../utils/upgrade';
import { import {
addEntryComponents, addEntryComponents,
readBootstrapInfo, readBootstrapInfo,
removeFromNgModule removeFromNgModule,
} from '../../utils/ast-utils'; } from '../../utils/ast-utils';
function updateMain(angularJsImport: string, options: Schema): Rule { function updateMain(angularJsImport: string, options: Schema): Rule {
@ -16,7 +16,7 @@ function updateMain(angularJsImport: string, options: Schema): Rule {
moduleClassName, moduleClassName,
moduleSpec, moduleSpec,
bootstrapComponentClassName, bootstrapComponentClassName,
bootstrapComponentFileName bootstrapComponentFileName,
} = readBootstrapInfo(host, options.project); } = readBootstrapInfo(host, options.project);
host.overwrite( host.overwrite(
@ -64,9 +64,9 @@ function rewriteBootstrapLogic(options: Schema): Rule {
...addMethod(moduleSource, modulePath, { ...addMethod(moduleSource, modulePath, {
className: moduleClassName, className: moduleClassName,
methodHeader: 'ngDoBootstrap(): void', methodHeader: 'ngDoBootstrap(): void',
body: `` body: ``,
}), }),
...removeFromNgModule(moduleSource, modulePath, 'bootstrap') ...removeFromNgModule(moduleSource, modulePath, 'bootstrap'),
]); ]);
return host; return host;
}; };
@ -76,7 +76,7 @@ function addEntryComponentsToModule(options: Schema): Rule {
const { const {
modulePath, modulePath,
moduleSource, moduleSource,
bootstrapComponentClassName bootstrapComponentClassName,
} = readBootstrapInfo(host, options.project); } = readBootstrapInfo(host, options.project);
insert( insert(
host, host,
@ -97,6 +97,6 @@ export default function(options: Schema): Rule {
addEntryComponentsToModule(options), addEntryComponentsToModule(options),
rewriteBootstrapLogic(options), rewriteBootstrapLogic(options),
options.skipPackageJson ? noop() : addUpgradeToPackageJson(), options.skipPackageJson ? noop() : addUpgradeToPackageJson(),
formatFiles(options) formatFiles(options),
]); ]);
} }

View File

@ -36,7 +36,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'karma' unitTestRunner: 'karma',
}, },
appTree appTree
); );
@ -54,7 +54,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'karma' unitTestRunner: 'karma',
}, },
appTree appTree
); );
@ -75,7 +75,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'karma' unitTestRunner: 'karma',
}, },
appTree appTree
); );
@ -86,7 +86,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'karma' unitTestRunner: 'karma',
}, },
appTree appTree
); );
@ -105,7 +105,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'jest' unitTestRunner: 'jest',
}, },
appTree appTree
); );
@ -119,7 +119,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'jest' unitTestRunner: 'jest',
}, },
appTree appTree
); );
@ -130,7 +130,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
unitTestRunner: 'jest' unitTestRunner: 'jest',
}, },
appTree appTree
); );
@ -152,7 +152,7 @@ describe('init', () => {
'init', 'init',
{ {
unitTestRunner: 'none', unitTestRunner: 'none',
e2eTestRunner: 'cypress' e2eTestRunner: 'cypress',
}, },
appTree appTree
); );
@ -165,7 +165,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
e2eTestRunner: 'cypress' e2eTestRunner: 'cypress',
}, },
appTree appTree
); );
@ -181,7 +181,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
e2eTestRunner: 'protractor' e2eTestRunner: 'protractor',
}, },
appTree appTree
); );
@ -197,7 +197,7 @@ describe('init', () => {
const tree = await runSchematic( const tree = await runSchematic(
'init', 'init',
{ {
e2eTestRunner: 'protractor' e2eTestRunner: 'protractor',
}, },
appTree appTree
); );

View File

@ -4,20 +4,20 @@ import {
noop, noop,
Rule, Rule,
schematic, schematic,
Tree Tree,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { import {
addDepsToPackageJson, addDepsToPackageJson,
formatFiles, formatFiles,
readJsonInTree, readJsonInTree,
updateJsonInTree, updateJsonInTree,
updateWorkspace updateWorkspace,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { import {
angularDevkitVersion, angularDevkitVersion,
angularVersion, angularVersion,
jestPresetAngularVersion, jestPresetAngularVersion,
rxjsVersion rxjsVersion,
} from '../../utils/versions'; } from '../../utils/versions';
import { Schema } from './schema'; import { Schema } from './schema';
import { E2eTestRunner, UnitTestRunner } from '../../utils/test-runners'; import { E2eTestRunner, UnitTestRunner } from '../../utils/test-runners';
@ -36,13 +36,13 @@ const updateDependencies = addDepsToPackageJson(
'@angular/router': angularVersion, '@angular/router': angularVersion,
'core-js': '^2.5.4', 'core-js': '^2.5.4',
rxjs: rxjsVersion, rxjs: rxjsVersion,
'zone.js': '^0.10.2' 'zone.js': '^0.10.2',
}, },
{ {
'@angular/compiler-cli': angularVersion, '@angular/compiler-cli': angularVersion,
'@angular/language-service': angularVersion, '@angular/language-service': angularVersion,
'@angular-devkit/build-angular': angularDevkitVersion, '@angular-devkit/build-angular': angularDevkitVersion,
codelyzer: '~5.0.1' codelyzer: '~5.0.1',
} }
); );
@ -57,7 +57,7 @@ export function addUnitTestRunner(
addDepsToPackageJson( addDepsToPackageJson(
{}, {},
{ {
'jest-preset-angular': jestPresetAngularVersion 'jest-preset-angular': jestPresetAngularVersion,
} }
), ),
(host: Tree) => { (host: Tree) => {
@ -70,10 +70,10 @@ export function addUnitTestRunner(
'init', 'init',
{}, {},
{ {
interactive: false interactive: false,
} }
); );
} },
]); ]);
default: default:
return noop(); return noop();
@ -95,7 +95,7 @@ export function addE2eTestRunner(options: Pick<Schema, 'e2eTestRunner'>): Rule {
'jasmine-core': '~2.99.1', 'jasmine-core': '~2.99.1',
'jasmine-spec-reporter': '~4.2.1', 'jasmine-spec-reporter': '~4.2.1',
'@types/jasmine': '~2.8.6', '@types/jasmine': '~2.8.6',
'@types/jasminewd2': '~2.0.3' '@types/jasminewd2': '~2.0.3',
} }
); );
}; };
@ -110,7 +110,7 @@ export function addE2eTestRunner(options: Pick<Schema, 'e2eTestRunner'>): Rule {
'ng-add', 'ng-add',
{}, {},
{ {
interactive: false interactive: false,
} }
); );
}; };
@ -120,7 +120,7 @@ export function addE2eTestRunner(options: Pick<Schema, 'e2eTestRunner'>): Rule {
} }
export function setDefaults(options: Schema): Rule { export function setDefaults(options: Schema): Rule {
const updateAngularWorkspace = updateWorkspace(workspace => { const updateAngularWorkspace = updateWorkspace((workspace) => {
workspace.extensions.schematics = workspace.extensions.schematics || {}; workspace.extensions.schematics = workspace.extensions.schematics || {};
workspace.extensions.schematics['@nrwl/angular:application'] = workspace.extensions.schematics['@nrwl/angular:application'] =
@ -173,6 +173,6 @@ export default function(options: Schema): Rule {
updateDependencies, updateDependencies,
addUnitTestRunner(options), addUnitTestRunner(options),
addE2eTestRunner(options), addE2eTestRunner(options),
formatFiles() formatFiles(),
]); ]);
} }

View File

@ -13,7 +13,7 @@ describe('karmaProject', () => {
'lib', 'lib',
{ {
name: 'lib1', name: 'lib1',
unitTestRunner: 'none' unitTestRunner: 'none',
}, },
appTree appTree
); );
@ -21,7 +21,7 @@ describe('karmaProject', () => {
'app', 'app',
{ {
name: 'app1', name: 'app1',
unitTestRunner: 'none' unitTestRunner: 'none',
}, },
appTree appTree
); );
@ -31,7 +31,7 @@ describe('karmaProject', () => {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -43,7 +43,7 @@ describe('karmaProject', () => {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -71,7 +71,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -85,7 +85,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -95,8 +95,8 @@ module.exports = function(config) {
options: { options: {
main: 'libs/lib1/src/test.ts', main: 'libs/lib1/src/test.ts',
tsConfig: 'libs/lib1/tsconfig.spec.json', tsConfig: 'libs/lib1/tsconfig.spec.json',
karmaConfig: 'libs/lib1/karma.conf.js' karmaConfig: 'libs/lib1/karma.conf.js',
} },
}); });
expect( expect(
workspaceJson.projects.lib1.architect.lint.options.tsConfig workspaceJson.projects.lib1.architect.lint.options.tsConfig
@ -107,7 +107,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -119,10 +119,10 @@ module.exports = function(config) {
extends: './tsconfig.json', extends: './tsconfig.json',
compilerOptions: { compilerOptions: {
outDir: '../../dist/out-tsc', outDir: '../../dist/out-tsc',
types: ['jasmine', 'node'] types: ['jasmine', 'node'],
}, },
files: ['src/test.ts'], files: ['src/test.ts'],
include: ['**/*.spec.ts', '**/*.d.ts'] include: ['**/*.spec.ts', '**/*.d.ts'],
}); });
}); });
@ -130,7 +130,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'lib1' project: 'lib1',
}, },
appTree appTree
); );
@ -145,7 +145,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'app1' project: 'app1',
}, },
appTree appTree
); );
@ -159,8 +159,8 @@ module.exports = function(config) {
karmaConfig: 'apps/app1/karma.conf.js', karmaConfig: 'apps/app1/karma.conf.js',
styles: [], styles: [],
scripts: [], scripts: [],
assets: [] assets: [],
} },
}); });
expect( expect(
workspaceJson.projects.app1.architect.lint.options.tsConfig workspaceJson.projects.app1.architect.lint.options.tsConfig
@ -171,7 +171,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'app1' project: 'app1',
}, },
appTree appTree
); );
@ -183,10 +183,10 @@ module.exports = function(config) {
extends: './tsconfig.json', extends: './tsconfig.json',
compilerOptions: { compilerOptions: {
outDir: '../../dist/out-tsc', outDir: '../../dist/out-tsc',
types: ['jasmine', 'node'] types: ['jasmine', 'node'],
}, },
files: ['src/test.ts', 'src/polyfills.ts'], files: ['src/test.ts', 'src/polyfills.ts'],
include: ['**/*.spec.ts', '**/*.d.ts'] include: ['**/*.spec.ts', '**/*.d.ts'],
}); });
}); });
@ -194,7 +194,7 @@ module.exports = function(config) {
const resultTree = await runSchematic( const resultTree = await runSchematic(
'karma-project', 'karma-project',
{ {
project: 'app1' project: 'app1',
}, },
appTree appTree
); );

View File

@ -8,13 +8,13 @@ import {
SchematicContext, SchematicContext,
move, move,
template, template,
schematic schematic,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { import {
readJsonInTree, readJsonInTree,
updateJsonInTree, updateJsonInTree,
offsetFromRoot, offsetFromRoot,
updateWorkspaceInTree updateWorkspaceInTree,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { join, normalize } from '@angular-devkit/core'; import { join, normalize } from '@angular-devkit/core';
import { getProjectConfig } from '@nrwl/workspace'; import { getProjectConfig } from '@nrwl/workspace';
@ -35,9 +35,9 @@ function generateFiles(options: KarmaProjectSchema): Rule {
...options, ...options,
projectRoot: projectConfig.root, projectRoot: projectConfig.root,
isLibrary: projectConfig.projectType === 'library', isLibrary: projectConfig.projectType === 'library',
offsetFromRoot: offsetFromRoot(projectConfig.root) offsetFromRoot: offsetFromRoot(projectConfig.root),
}), }),
move(projectConfig.root) move(projectConfig.root),
]) ])
)(host, context); )(host, context);
}; };
@ -46,17 +46,20 @@ function generateFiles(options: KarmaProjectSchema): Rule {
function updateTsConfig(options: KarmaProjectSchema): Rule { function updateTsConfig(options: KarmaProjectSchema): Rule {
return (host: Tree) => { return (host: Tree) => {
const projectConfig = getProjectConfig(host, options.project); const projectConfig = getProjectConfig(host, options.project);
return updateJsonInTree(join(projectConfig.root, 'tsconfig.json'), json => { return updateJsonInTree(
join(projectConfig.root, 'tsconfig.json'),
(json) => {
return { return {
...json, ...json,
compilerOptions: { compilerOptions: {
...json.compilerOptions, ...json.compilerOptions,
types: Array.from( types: Array.from(
new Set([...(json.compilerOptions.types || []), 'jasmine']) new Set([...(json.compilerOptions.types || []), 'jasmine'])
) ),
} },
}; };
}); }
);
}; };
} }
@ -67,10 +70,10 @@ function updateTsSpecConfig(options: KarmaProjectSchema): Rule {
projectConfig.projectType === 'library' ? [] : ['src/polyfills.ts']; projectConfig.projectType === 'library' ? [] : ['src/polyfills.ts'];
return updateJsonInTree( return updateJsonInTree(
join(projectConfig.root, 'tsconfig.spec.json'), join(projectConfig.root, 'tsconfig.spec.json'),
json => { (json) => {
return { return {
...json, ...json,
files: [...json.files, ...extraFiles] files: [...json.files, ...extraFiles],
}; };
} }
); );
@ -78,15 +81,15 @@ function updateTsSpecConfig(options: KarmaProjectSchema): Rule {
} }
function updateworkspaceJson(options: KarmaProjectSchema): Rule { function updateworkspaceJson(options: KarmaProjectSchema): Rule {
return updateWorkspaceInTree(json => { return updateWorkspaceInTree((json) => {
const projectConfig = json.projects[options.project]; const projectConfig = json.projects[options.project];
projectConfig.architect.test = { projectConfig.architect.test = {
builder: '@angular-devkit/build-angular:karma', builder: '@angular-devkit/build-angular:karma',
options: { options: {
main: join(normalize(projectConfig.sourceRoot), 'test.ts'), main: join(normalize(projectConfig.sourceRoot), 'test.ts'),
tsConfig: join(normalize(projectConfig.root), 'tsconfig.spec.json'), tsConfig: join(normalize(projectConfig.root), 'tsconfig.spec.json'),
karmaConfig: join(normalize(projectConfig.root), 'karma.conf.js') karmaConfig: join(normalize(projectConfig.root), 'karma.conf.js'),
} },
}; };
if (projectConfig.projectType === 'application') { if (projectConfig.projectType === 'application') {
@ -95,13 +98,13 @@ function updateworkspaceJson(options: KarmaProjectSchema): Rule {
polyfills: join(normalize(projectConfig.sourceRoot), 'polyfills.ts'), polyfills: join(normalize(projectConfig.sourceRoot), 'polyfills.ts'),
styles: [], styles: [],
scripts: [], scripts: [],
assets: [] assets: [],
}; };
} }
if (projectConfig.architect.lint) { if (projectConfig.architect.lint) {
projectConfig.architect.lint.options.tsConfig = [ projectConfig.architect.lint.options.tsConfig = [
...projectConfig.architect.lint.options.tsConfig, ...projectConfig.architect.lint.options.tsConfig,
join(normalize(projectConfig.root), 'tsconfig.spec.json') join(normalize(projectConfig.root), 'tsconfig.spec.json'),
]; ];
} }
return json; return json;
@ -125,6 +128,6 @@ export default function(options: KarmaProjectSchema): Rule {
generateFiles(options), generateFiles(options),
updateTsConfig(options), updateTsConfig(options),
updateTsSpecConfig(options), updateTsSpecConfig(options),
updateworkspaceJson(options) updateworkspaceJson(options),
]); ]);
} }

View File

@ -13,15 +13,15 @@ module.exports = () => {
require('karma-chrome-launcher'), require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'), require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'), require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma') require('@angular-devkit/build-angular/plugins/karma'),
], ],
client: { client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser clearContext: false, // leave Jasmine Spec Runner output visible in browser
}, },
coverageIstanbulReporter: { coverageIstanbulReporter: {
dir: join(__dirname, '../../coverage'), dir: join(__dirname, '../../coverage'),
reports: ['html', 'lcovonly'], reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true fixWebpackSourcePaths: true,
}, },
reporters: ['progress', 'kjhtml'], reporters: ['progress', 'kjhtml'],
port: 9876, port: 9876,
@ -29,6 +29,6 @@ module.exports = () => {
logLevel: constants.LOG_INFO, logLevel: constants.LOG_INFO,
autoWatch: true, autoWatch: true,
browsers: ['Chrome'], browsers: ['Chrome'],
singleRun: true singleRun: true,
}; };
}; };

View File

@ -19,9 +19,9 @@ export default function() {
'karma-jasmine-html-reporter': '^0.2.2', 'karma-jasmine-html-reporter': '^0.2.2',
'jasmine-core': '~2.99.1', 'jasmine-core': '~2.99.1',
'jasmine-spec-reporter': '~4.2.1', 'jasmine-spec-reporter': '~4.2.1',
'@types/jasmine': '~2.8.8' '@types/jasmine': '~2.8.8',
} }
) ),
]); ]);
}; };
} }

View File

@ -6,7 +6,7 @@ import { NxJson, readJsonInTree } from '@nrwl/workspace';
import { UnitTestTree } from '@angular-devkit/schematics/testing'; import { UnitTestTree } from '@angular-devkit/schematics/testing';
import { import {
stripIndents, stripIndents,
stripIndent stripIndent,
} from '@angular-devkit/core/src/utils/literals'; } from '@angular-devkit/core/src/utils/literals';
describe('lib', () => { describe('lib', () => {
@ -97,7 +97,7 @@ describe('lib', () => {
workspaceJson.projects['my-lib'].architect.lint.options.tsConfig workspaceJson.projects['my-lib'].architect.lint.options.tsConfig
).toEqual([ ).toEqual([
'libs/my-lib/tsconfig.lib.json', 'libs/my-lib/tsconfig.lib.json',
'libs/my-lib/tsconfig.spec.json' 'libs/my-lib/tsconfig.spec.json',
]); ]);
expect( expect(
workspaceJson.projects['my-lib'].architect.lint.options.exclude workspaceJson.projects['my-lib'].architect.lint.options.exclude
@ -139,8 +139,8 @@ describe('lib', () => {
const nxJson = readJsonInTree<NxJson>(tree, '/nx.json'); const nxJson = readJsonInTree<NxJson>(tree, '/nx.json');
expect(nxJson.projects).toEqual({ expect(nxJson.projects).toEqual({
'my-lib': { 'my-lib': {
tags: ['one', 'two'] tags: ['one', 'two'],
} },
}); });
}); });
@ -148,7 +148,7 @@ describe('lib', () => {
const tree = await runSchematic('lib', { name: 'myLib' }, appTree); const tree = await runSchematic('lib', { name: 'myLib' }, appTree);
const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json');
expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([ expect(tsconfigJson.compilerOptions.paths['@proj/my-lib']).toEqual([
'libs/my-lib/src/index.ts' 'libs/my-lib/src/index.ts',
]); ]);
}); });
@ -158,9 +158,9 @@ describe('lib', () => {
expect(tsconfigJson).toEqual({ expect(tsconfigJson).toEqual({
extends: '../../tsconfig.json', extends: '../../tsconfig.json',
compilerOptions: { compilerOptions: {
types: ['node', 'jest'] types: ['node', 'jest'],
}, },
include: ['**/*.ts'] include: ['**/*.ts'],
}); });
}); });
@ -195,7 +195,7 @@ describe('lib', () => {
); );
expect(tsconfigJson.exclude).toEqual([ expect(tsconfigJson.exclude).toEqual([
'src/test-setup.ts', 'src/test-setup.ts',
'**/*.spec.ts' '**/*.spec.ts',
]); ]);
}); });
@ -300,7 +300,7 @@ describe('lib', () => {
'lib', 'lib',
{ {
name: 'myLib', name: 'myLib',
framework: 'none' framework: 'none',
}, },
appTree appTree
); );
@ -328,15 +328,15 @@ describe('lib', () => {
name: 'myLib', name: 'myLib',
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
tags: 'one' tags: 'one',
}, },
appTree appTree
); );
const nxJson = readJsonInTree<NxJson>(tree, '/nx.json'); const nxJson = readJsonInTree<NxJson>(tree, '/nx.json');
expect(nxJson.projects).toEqual({ expect(nxJson.projects).toEqual({
'my-dir-my-lib': { 'my-dir-my-lib': {
tags: ['one'] tags: ['one'],
} },
}); });
const tree2 = await runSchematic( const tree2 = await runSchematic(
@ -346,18 +346,18 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
tags: 'one,two', tags: 'one,two',
simpleModuleName: true simpleModuleName: true,
}, },
tree tree
); );
const nxJson2 = readJsonInTree<NxJson>(tree2, '/nx.json'); const nxJson2 = readJsonInTree<NxJson>(tree2, '/nx.json');
expect(nxJson2.projects).toEqual({ expect(nxJson2.projects).toEqual({
'my-dir-my-lib': { 'my-dir-my-lib': {
tags: ['one'] tags: ['one'],
}, },
'my-dir-my-lib2': { 'my-dir-my-lib2': {
tags: ['one', 'two'] tags: ['one', 'two'],
} },
}); });
}); });
@ -392,7 +392,7 @@ describe('lib', () => {
name: 'myLib2', name: 'myLib2',
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
simpleModuleName: true simpleModuleName: true,
}, },
tree tree
); );
@ -423,7 +423,7 @@ describe('lib', () => {
name: 'myLib', name: 'myLib',
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
publishable: true publishable: true,
}, },
appTree appTree
); );
@ -451,7 +451,7 @@ describe('lib', () => {
workspaceJson.projects['my-dir-my-lib'].architect.lint.options.tsConfig workspaceJson.projects['my-dir-my-lib'].architect.lint.options.tsConfig
).toEqual([ ).toEqual([
'libs/my-dir/my-lib/tsconfig.lib.json', 'libs/my-dir/my-lib/tsconfig.lib.json',
'libs/my-dir/my-lib/tsconfig.spec.json' 'libs/my-dir/my-lib/tsconfig.spec.json',
]); ]);
expect( expect(
workspaceJson.projects['my-dir-my-lib'].architect.lint.options.exclude workspaceJson.projects['my-dir-my-lib'].architect.lint.options.exclude
@ -465,9 +465,9 @@ describe('lib', () => {
appTree appTree
); );
const tsconfigJson = readJsonInTree(tree, '/tsconfig.json'); const tsconfigJson = readJsonInTree(tree, '/tsconfig.json');
expect(tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']).toEqual( expect(
['libs/my-dir/my-lib/src/index.ts'] tsconfigJson.compilerOptions.paths['@proj/my-dir/my-lib']
); ).toEqual(['libs/my-dir/my-lib/src/index.ts']);
expect( expect(
tsconfigJson.compilerOptions.paths['my-dir-my-lib/*'] tsconfigJson.compilerOptions.paths['my-dir-my-lib/*']
).toBeUndefined(); ).toBeUndefined();
@ -487,9 +487,9 @@ describe('lib', () => {
expect(tsconfigJson).toEqual({ expect(tsconfigJson).toEqual({
extends: '../../../tsconfig.json', extends: '../../../tsconfig.json',
compilerOptions: { compilerOptions: {
types: ['node', 'jest'] types: ['node', 'jest'],
}, },
include: ['**/*.ts'] include: ['**/*.ts'],
}); });
}); });
}); });
@ -513,7 +513,7 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
routing: true, routing: true,
lazy: true lazy: true,
}, },
appTree appTree
); );
@ -536,7 +536,7 @@ describe('lib', () => {
routing: true, routing: true,
framework: 'angular', framework: 'angular',
lazy: true, lazy: true,
simpleModuleName: true simpleModuleName: true,
}, },
tree tree
); );
@ -559,7 +559,7 @@ describe('lib', () => {
routing: true, routing: true,
lazy: true, lazy: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
appTree appTree
); );
@ -572,7 +572,9 @@ describe('lib', () => {
{ {
path: 'my-dir-my-lib', path: 'my-dir-my-lib',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) import('@proj/my-dir/my-lib').then(
(module) => module.MyDirMyLibModule
),
}`); }`);
const tsConfigAppJson = JSON.parse( const tsConfigAppJson = JSON.parse(
@ -582,7 +584,7 @@ describe('lib', () => {
); );
expect(tsConfigAppJson.include).toEqual([ expect(tsConfigAppJson.include).toEqual([
'**/*.ts', '**/*.ts',
'../../libs/my-dir/my-lib/src/index.ts' '../../libs/my-dir/my-lib/src/index.ts',
]); ]);
const tree2 = await runSchematic( const tree2 = await runSchematic(
@ -593,7 +595,7 @@ describe('lib', () => {
routing: true, routing: true,
framework: 'angular', framework: 'angular',
lazy: true, lazy: true,
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
tree tree
); );
@ -606,15 +608,17 @@ describe('lib', () => {
{ {
path: 'my-dir-my-lib', path: 'my-dir-my-lib',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) import('@proj/my-dir/my-lib').then(
(module) => module.MyDirMyLibModule
),
}`); }`);
expect(moduleContents2).toContain(` expect(moduleContents2).toContain(`
{ {
path: 'my-dir-my-lib2', path: 'my-dir-my-lib2',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib2').then( import('@proj/my-dir/my-lib2').then(
module => module.MyDirMyLib2Module (module) => module.MyDirMyLib2Module
) ),
}`); }`);
const tsConfigAppJson2 = JSON.parse( const tsConfigAppJson2 = JSON.parse(
@ -625,7 +629,7 @@ describe('lib', () => {
expect(tsConfigAppJson2.include).toEqual([ expect(tsConfigAppJson2.include).toEqual([
'**/*.ts', '**/*.ts',
'../../libs/my-dir/my-lib/src/index.ts', '../../libs/my-dir/my-lib/src/index.ts',
'../../libs/my-dir/my-lib2/src/index.ts' '../../libs/my-dir/my-lib2/src/index.ts',
]); ]);
const tree3 = await runSchematic( const tree3 = await runSchematic(
@ -637,7 +641,7 @@ describe('lib', () => {
framework: 'angular', framework: 'angular',
lazy: true, lazy: true,
parentModule: 'apps/myapp/src/app/app.module.ts', parentModule: 'apps/myapp/src/app/app.module.ts',
simpleModuleName: true simpleModuleName: true,
}, },
tree2 tree2
); );
@ -650,21 +654,23 @@ describe('lib', () => {
{ {
path: 'my-dir-my-lib', path: 'my-dir-my-lib',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) import('@proj/my-dir/my-lib').then(
(module) => module.MyDirMyLibModule
),
}`); }`);
expect(moduleContents3).toContain(` expect(moduleContents3).toContain(`
{ {
path: 'my-dir-my-lib2', path: 'my-dir-my-lib2',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib2').then( import('@proj/my-dir/my-lib2').then(
module => module.MyDirMyLib2Module (module) => module.MyDirMyLib2Module
) ),
}`); }`);
expect(moduleContents3).toContain(` expect(moduleContents3).toContain(`
{ {
path: 'my-lib3', path: 'my-lib3',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib3').then(module => module.MyLib3Module) import('@proj/my-dir/my-lib3').then((module) => module.MyLib3Module),
}`); }`);
const tsConfigAppJson3 = JSON.parse( const tsConfigAppJson3 = JSON.parse(
@ -676,7 +682,7 @@ describe('lib', () => {
'**/*.ts', '**/*.ts',
'../../libs/my-dir/my-lib/src/index.ts', '../../libs/my-dir/my-lib/src/index.ts',
'../../libs/my-dir/my-lib2/src/index.ts', '../../libs/my-dir/my-lib2/src/index.ts',
'../../libs/my-dir/my-lib3/src/index.ts' '../../libs/my-dir/my-lib3/src/index.ts',
]); ]);
}); });
@ -709,7 +715,7 @@ describe('lib', () => {
routing: true, routing: true,
lazy: true, lazy: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
appTree appTree
); );
@ -724,8 +730,8 @@ describe('lib', () => {
{ {
path: 'my-dir-my-lib', path: 'my-dir-my-lib',
loadChildren: () => loadChildren: () =>
import('@proj/my-dir/my-lib').then(module => module.MyDirMyLibModule) import('@proj/my-dir/my-lib').then((module) => module.MyDirMyLibModule),
} },
];`); ];`);
}); });
}); });
@ -738,7 +744,7 @@ describe('lib', () => {
name: 'myLib', name: 'myLib',
directory: 'myDir', directory: 'myDir',
framework: 'angular', framework: 'angular',
routing: true routing: true,
}, },
appTree appTree
); );
@ -765,7 +771,7 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
routing: true, routing: true,
framework: 'angular', framework: 'angular',
simpleModuleName: true simpleModuleName: true,
}, },
tree tree
); );
@ -789,7 +795,7 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
routing: true, routing: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
appTree appTree
); );
@ -810,7 +816,7 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
routing: true, routing: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
tree tree
); );
@ -835,7 +841,7 @@ describe('lib', () => {
routing: true, routing: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts', parentModule: 'apps/myapp/src/app/app.module.ts',
simpleModuleName: true simpleModuleName: true,
}, },
tree2 tree2
); );
@ -884,7 +890,7 @@ describe('lib', () => {
directory: 'myDir', directory: 'myDir',
routing: true, routing: true,
framework: 'angular', framework: 'angular',
parentModule: 'apps/myapp/src/app/app.module.ts' parentModule: 'apps/myapp/src/app/app.module.ts',
}, },
appTree appTree
); );
@ -913,8 +919,8 @@ describe('lib', () => {
expect(workspaceJson.projects['my-lib'].schematics).toEqual({ expect(workspaceJson.projects['my-lib'].schematics).toEqual({
'@nrwl/angular:component': { '@nrwl/angular:component': {
style: 'scss' style: 'scss',
} },
}); });
}); });
}); });
@ -939,7 +945,7 @@ describe('lib', () => {
workspaceJson.projects['my-lib'].architect.lint.options.tsConfig workspaceJson.projects['my-lib'].architect.lint.options.tsConfig
).toEqual([ ).toEqual([
'libs/my-lib/tsconfig.lib.json', 'libs/my-lib/tsconfig.lib.json',
'libs/my-lib/tsconfig.spec.json' 'libs/my-lib/tsconfig.spec.json',
]); ]);
expect( expect(
workspaceJson.projects['my-lib'].architect.lint.options.exclude workspaceJson.projects['my-lib'].architect.lint.options.exclude

View File

@ -12,7 +12,7 @@ import {
SchematicContext, SchematicContext,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { Schema } from './schema'; import { Schema } from './schema';
import * as path from 'path'; import * as path from 'path';
@ -34,7 +34,7 @@ import {
toClassName, toClassName,
toFileName, toFileName,
toPropertyName, toPropertyName,
updateJsonInTree updateJsonInTree,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { addUnitTestRunner } from '../init/init'; import { addUnitTestRunner } from '../init/init';
import { addImportToModule, addRoute } from '../../utils/ast-utils'; import { addImportToModule, addRoute } from '../../utils/ast-utils';
@ -74,7 +74,7 @@ function addLazyLoadedRouterConfiguration(options: NormalizedSchema): Rule {
RouterModule.forChild([ RouterModule.forChild([
/* {path: '', pathMatch: 'full', component: InsertYourComponentHere} */ /* {path: '', pathMatch: 'full', component: InsertYourComponentHere} */
]) ` ]) `
) ),
]); ]);
return host; return host;
}; };
@ -107,7 +107,7 @@ function addRouterConfiguration(options: NormalizedSchema): Rule {
moduleSourceFile, moduleSourceFile,
options.modulePath, options.modulePath,
`export const ${constName}: Route[] = [];` `export const ${constName}: Route[] = [];`
) ),
]); ]);
return host; return host;
}; };
@ -138,7 +138,7 @@ function addLoadChildren(options: NormalizedSchema): Rule {
)}', loadChildren: () => import('@${npmScope}/${ )}', loadChildren: () => import('@${npmScope}/${
options.projectDirectory options.projectDirectory
}').then(module => module.${options.moduleName})}` }').then(module => module.${options.moduleName})}`
) ),
]); ]);
const tsConfig = findClosestTsConfigApp(host, options.parentModule); const tsConfig = findClosestTsConfigApp(host, options.parentModule);
@ -157,7 +157,7 @@ function addLoadChildren(options: NormalizedSchema): Rule {
tsConfig, tsConfig,
tsConfigAppFile, tsConfigAppFile,
`\n , "${offset}${options.projectRoot}/src/index.ts"\n` `\n , "${offset}${options.projectRoot}/src/index.ts"\n`
) ),
]); ]);
} else { } else {
// we should warn the user about not finding the config // we should warn the user about not finding the config
@ -213,7 +213,7 @@ function addChildren(options: NormalizedSchema): Rule {
options.parentModule, options.parentModule,
sourceFile, sourceFile,
`{path: '${toFileName(options.fileName)}', children: ${constName}}` `{path: '${toFileName(options.fileName)}', children: ${constName}}`
) ),
]); ]);
return host; return host;
}; };
@ -227,7 +227,7 @@ function updateNgPackage(options: NormalizedSchema): Rule {
options.projectDirectory options.projectDirectory
}`; }`;
return chain([ return chain([
updateJsonInTree(`${options.projectRoot}/ng-package.json`, json => { updateJsonInTree(`${options.projectRoot}/ng-package.json`, (json) => {
let $schema = json.$schema; let $schema = json.$schema;
if (json.$schema && json.$schema.indexOf('node_modules') >= 0) { if (json.$schema && json.$schema.indexOf('node_modules') >= 0) {
$schema = `${offsetFromRoot( $schema = `${offsetFromRoot(
@ -240,9 +240,9 @@ function updateNgPackage(options: NormalizedSchema): Rule {
return { return {
...json, ...json,
dest, dest,
$schema $schema,
}; };
}) }),
]); ]);
} }
@ -315,13 +315,13 @@ function updateProject(options: NormalizedSchema): Rule {
apply(url('./files/lib'), [ apply(url('./files/lib'), [
template({ template({
...options, ...options,
offsetFromRoot: offsetFromRoot(options.projectRoot) offsetFromRoot: offsetFromRoot(options.projectRoot),
}), }),
move(options.projectRoot) move(options.projectRoot),
]), ]),
MergeStrategy.Overwrite MergeStrategy.Overwrite
), ),
updateJsonInTree(getWorkspacePath(host), json => { updateJsonInTree(getWorkspacePath(host), (json) => {
const project = json.projects[options.name]; const project = json.projects[options.name];
const fixedProject = replaceAppNameWithPath( const fixedProject = replaceAppNameWithPath(
project, project,
@ -334,8 +334,8 @@ function updateProject(options: NormalizedSchema): Rule {
fixedProject.schematics = { fixedProject.schematics = {
...fixedProject.schematics, ...fixedProject.schematics,
'@nrwl/angular:component': { '@nrwl/angular:component': {
style: options.style style: options.style,
} },
}; };
} }
@ -349,7 +349,7 @@ function updateProject(options: NormalizedSchema): Rule {
delete fixedProject.architect.test; delete fixedProject.architect.test;
fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter( fixedProject.architect.lint.options.tsConfig = fixedProject.architect.lint.options.tsConfig.filter(
path => (path) =>
path !== join(normalize(options.projectRoot), 'tsconfig.spec.json') path !== join(normalize(options.projectRoot), 'tsconfig.spec.json')
); );
fixedProject.architect.lint.options.exclude.push( fixedProject.architect.lint.options.exclude.push(
@ -359,7 +359,7 @@ function updateProject(options: NormalizedSchema): Rule {
json.projects[options.name] = fixedProject; json.projects[options.name] = fixedProject;
return json; return json;
}), }),
updateJsonInTree(`${options.projectRoot}/tsconfig.lib.json`, json => { updateJsonInTree(`${options.projectRoot}/tsconfig.lib.json`, (json) => {
if (options.unitTestRunner === 'jest') { if (options.unitTestRunner === 'jest') {
json.exclude = ['src/test-setup.ts', '**/*.spec.ts']; json.exclude = ['src/test-setup.ts', '**/*.spec.ts'];
} else if (options.unitTestRunner === 'none') { } else if (options.unitTestRunner === 'none') {
@ -373,29 +373,29 @@ function updateProject(options: NormalizedSchema): Rule {
extends: `./tsconfig.json`, extends: `./tsconfig.json`,
compilerOptions: { compilerOptions: {
...json.compilerOptions, ...json.compilerOptions,
outDir: `${offsetFromRoot(options.projectRoot)}dist/out-tsc` outDir: `${offsetFromRoot(options.projectRoot)}dist/out-tsc`,
} },
}; };
}), }),
updateJsonInTree(`${options.projectRoot}/tslint.json`, json => { updateJsonInTree(`${options.projectRoot}/tslint.json`, (json) => {
return { return {
...json, ...json,
extends: `${offsetFromRoot(options.projectRoot)}tslint.json`, extends: `${offsetFromRoot(options.projectRoot)}tslint.json`,
linterOptions: { linterOptions: {
exclude: ['!**/*'] exclude: ['!**/*'],
} },
}; };
}), }),
updateJsonInTree(`/nx.json`, json => { updateJsonInTree(`/nx.json`, (json) => {
return { return {
...json, ...json,
projects: { projects: {
...json.projects, ...json.projects,
[options.name]: { tags: options.parsedTags } [options.name]: { tags: options.parsedTags },
} },
}; };
}), }),
updateNgPackage(options) updateNgPackage(options),
])(host, context); ])(host, context);
}; };
} }
@ -404,21 +404,21 @@ function updateTsConfig(options: NormalizedSchema): Rule {
return chain([ return chain([
(host: Tree, context: SchematicContext) => { (host: Tree, context: SchematicContext) => {
const nxJson = readJsonInTree<NxJson>(host, 'nx.json'); const nxJson = readJsonInTree<NxJson>(host, 'nx.json');
return updateJsonInTree('tsconfig.json', json => { return updateJsonInTree('tsconfig.json', (json) => {
const c = json.compilerOptions; const c = json.compilerOptions;
delete c.paths[options.name]; delete c.paths[options.name];
c.paths[`@${nxJson.npmScope}/${options.projectDirectory}`] = [ c.paths[`@${nxJson.npmScope}/${options.projectDirectory}`] = [
`libs/${options.projectDirectory}/src/index.ts` `libs/${options.projectDirectory}/src/index.ts`,
]; ];
return json; return json;
})(host, context); })(host, context);
} },
]); ]);
} }
function updateLibPackageNpmScope(options: NormalizedSchema): Rule { function updateLibPackageNpmScope(options: NormalizedSchema): Rule {
return (host: Tree) => { return (host: Tree) => {
return updateJsonInTree(`${options.projectRoot}/package.json`, json => { return updateJsonInTree(`${options.projectRoot}/package.json`, (json) => {
json.name = `@${getNpmScope(host)}/${options.name}`; json.name = `@${getNpmScope(host)}/${options.name}`;
return json; return json;
}); });
@ -436,7 +436,7 @@ function addModule(options: NormalizedSchema): Rule {
options.routing && !options.lazy ? addRouterConfiguration(options) : noop(), options.routing && !options.lazy ? addRouterConfiguration(options) : noop(),
options.routing && !options.lazy && options.parentModule options.routing && !options.lazy && options.parentModule
? addChildren(options) ? addChildren(options)
: noop() : noop(),
]); ]);
} }
@ -456,7 +456,7 @@ export default function(schema: Schema): Rule {
style: options.style, style: options.style,
entryFile: 'index', entryFile: 'index',
skipPackageJson: !options.publishable, skipPackageJson: !options.publishable,
skipTsConfig: true skipTsConfig: true,
}), }),
move(options.name, options.projectRoot), move(options.name, options.projectRoot),
@ -467,17 +467,17 @@ export default function(schema: Schema): Rule {
project: options.name, project: options.name,
setupFile: 'angular', setupFile: 'angular',
supportTsx: false, supportTsx: false,
skipSerializers: false skipSerializers: false,
}) })
: noop(), : noop(),
options.unitTestRunner === 'karma' options.unitTestRunner === 'karma'
? schematic('karma-project', { ? schematic('karma-project', {
project: options.name project: options.name,
}) })
: noop(), : noop(),
options.publishable ? updateLibPackageNpmScope(options) : noop(), options.publishable ? updateLibPackageNpmScope(options) : noop(),
addModule(options), addModule(options),
formatFiles(options) formatFiles(options),
])(host, context); ])(host, context);
}; };
} }
@ -494,7 +494,7 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema {
const moduleName = `${toClassName(fileName)}Module`; const moduleName = `${toClassName(fileName)}Module`;
const parsedTags = options.tags const parsedTags = options.tags
? options.tags.split(',').map(s => s.trim()) ? options.tags.split(',').map((s) => s.trim())
: []; : [];
const modulePath = `${projectRoot}/src/lib/${fileName}.module.ts`; const modulePath = `${projectRoot}/src/lib/${fileName}.module.ts`;
const defaultPrefix = getNpmScope(host); const defaultPrefix = getNpmScope(host);
@ -509,6 +509,6 @@ function normalizeOptions(host: Tree, options: Schema): NormalizedSchema {
projectDirectory, projectDirectory,
modulePath, modulePath,
parsedTags, parsedTags,
fileName fileName,
}; };
} }

View File

@ -9,7 +9,7 @@ describe('updateModuleName Rule', () => {
let tree: UnitTestTree; let tree: UnitTestTree;
const schema: Schema = { const schema: Schema = {
projectName: 'my-source', projectName: 'my-source',
destination: 'my-destination' destination: 'my-destination',
}; };
const modulePath = '/libs/my-destination/src/lib/my-destination.module.ts'; const modulePath = '/libs/my-destination/src/lib/my-destination.module.ts';

View File

@ -17,7 +17,7 @@ import { Schema } from '../schema';
export function updateModuleName(schema: Schema) { export function updateModuleName(schema: Schema) {
return (tree: Tree, _context: SchematicContext): Observable<Tree> => { return (tree: Tree, _context: SchematicContext): Observable<Tree> => {
return from(getWorkspace(tree)).pipe( return from(getWorkspace(tree)).pipe(
map(workspace => { map((workspace) => {
const newProjectName = getNewProjectName(schema.destination); const newProjectName = getNewProjectName(schema.destination);
const project = workspace.projects.get(newProjectName); const project = workspace.projects.get(newProjectName);
@ -29,14 +29,14 @@ export function updateModuleName(schema: Schema) {
const moduleName = { const moduleName = {
from: classify(schema.projectName), from: classify(schema.projectName),
to: classify(newProjectName) to: classify(newProjectName),
}; };
const findModuleName = new RegExp(`\\b${moduleName.from}`, 'g'); const findModuleName = new RegExp(`\\b${moduleName.from}`, 'g');
const moduleFile = { const moduleFile = {
from: `${schema.projectName}.module`, from: `${schema.projectName}.module`,
to: `${newProjectName}.module` to: `${newProjectName}.module`,
}; };
const replaceImport = new RegExp(moduleFile.from, 'g'); const replaceImport = new RegExp(moduleFile.from, 'g');
@ -44,16 +44,16 @@ export function updateModuleName(schema: Schema) {
const filesToChange = [ const filesToChange = [
{ {
from: `${project.sourceRoot}/lib/${moduleFile.from}.ts`, from: `${project.sourceRoot}/lib/${moduleFile.from}.ts`,
to: `${project.sourceRoot}/lib/${moduleFile.to}.ts` to: `${project.sourceRoot}/lib/${moduleFile.to}.ts`,
}, },
{ {
from: `${project.sourceRoot}/lib/${moduleFile.from}.spec.ts`, from: `${project.sourceRoot}/lib/${moduleFile.from}.spec.ts`,
to: `${project.sourceRoot}/lib/${moduleFile.to}.spec.ts` to: `${project.sourceRoot}/lib/${moduleFile.to}.spec.ts`,
} },
]; ];
// Update the module file and its spec file // Update the module file and its spec file
filesToChange.forEach(file => { filesToChange.forEach((file) => {
if (tree.exists(file.from)) { if (tree.exists(file.from)) {
let content = tree.read(file.from).toString('utf-8'); let content = tree.read(file.from).toString('utf-8');
@ -78,7 +78,7 @@ export function updateModuleName(schema: Schema) {
} }
const projectDir = tree.getDir(definition.root); const projectDir = tree.getDir(definition.root);
projectDir.visit(file => { projectDir.visit((file) => {
const contents = tree.read(file).toString('utf-8'); const contents = tree.read(file).toString('utf-8');
if (!findModuleName.test(contents)) { if (!findModuleName.test(contents)) {
return; return;

View File

@ -12,6 +12,6 @@ import { Schema } from './schema';
export default function (schema: Schema) { export default function (schema: Schema) {
return chain([ return chain([
externalSchematic('@nrwl/workspace', 'move', schema), externalSchematic('@nrwl/workspace', 'move', schema),
updateModuleName(schema) updateModuleName(schema),
]); ]);
} }

View File

@ -10,7 +10,7 @@ import {
createLib, createLib,
getAppConfig, getAppConfig,
getLibConfig, getLibConfig,
runSchematic runSchematic,
} from '../../utils/testing'; } from '../../utils/testing';
import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { createEmptyWorkspace } from '@nrwl/workspace/testing';
@ -31,7 +31,7 @@ describe('ngrx', () => {
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
onlyEmptyRoot: true, onlyEmptyRoot: true,
minimal: false, minimal: false,
root: true root: true,
}, },
appTree appTree
); );
@ -56,7 +56,7 @@ describe('ngrx', () => {
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
root: true, root: true,
onlyEmptyRoot: false, onlyEmptyRoot: false,
minimal: true minimal: true,
}, },
appTree appTree
); );
@ -80,7 +80,7 @@ describe('ngrx', () => {
name: 'app', name: 'app',
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
root: true, root: true,
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -92,8 +92,8 @@ describe('ngrx', () => {
'/apps/myapp/src/app/+state/app.reducer.ts', '/apps/myapp/src/app/+state/app.reducer.ts',
'/apps/myapp/src/app/+state/app.reducer.spec.ts', '/apps/myapp/src/app/+state/app.reducer.spec.ts',
'/apps/myapp/src/app/+state/app.selectors.ts', '/apps/myapp/src/app/+state/app.selectors.ts',
'/apps/myapp/src/app/+state/app.selectors.spec.ts' '/apps/myapp/src/app/+state/app.selectors.spec.ts',
].forEach(fileName => { ].forEach((fileName) => {
expect(tree.exists(fileName)).toBeTruthy(); expect(tree.exists(fileName)).toBeTruthy();
}); });
@ -128,7 +128,7 @@ describe('ngrx', () => {
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
root: true, root: true,
facade: true, facade: true,
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -155,8 +155,8 @@ describe('ngrx', () => {
'/apps/myapp/src/app/+state/app.facade.ts', '/apps/myapp/src/app/+state/app.facade.ts',
'/apps/myapp/src/app/+state/app.facade.spec.ts', '/apps/myapp/src/app/+state/app.facade.spec.ts',
'/apps/myapp/src/app/+state/app.selectors.ts', '/apps/myapp/src/app/+state/app.selectors.ts',
'/apps/myapp/src/app/+state/app.selectors.spec.ts' '/apps/myapp/src/app/+state/app.selectors.spec.ts',
].forEach(fileName => { ].forEach((fileName) => {
expect(tree.exists(fileName)).toBeTruthy(); expect(tree.exists(fileName)).toBeTruthy();
}); });
}); });
@ -168,7 +168,7 @@ describe('ngrx', () => {
{ {
name: 'app', name: 'app',
module: 'apps/myapp-norouter/src/app/app.module.ts', module: 'apps/myapp-norouter/src/app/app.module.ts',
root: true root: true,
}, },
newTree newTree
); );
@ -185,7 +185,7 @@ describe('ngrx', () => {
{ {
name: 'state', name: 'state',
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -207,7 +207,7 @@ describe('ngrx', () => {
name: 'state', name: 'state',
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
directory: 'myCustomState', directory: 'myCustomState',
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -230,7 +230,7 @@ describe('ngrx', () => {
module: 'apps/myapp/src/app/app.module.ts', module: 'apps/myapp/src/app/app.module.ts',
onlyAddFiles: true, onlyAddFiles: true,
facade: true, facade: true,
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -246,8 +246,8 @@ describe('ngrx', () => {
'/apps/myapp/src/app/+state/state.selectors.ts', '/apps/myapp/src/app/+state/state.selectors.ts',
'/apps/myapp/src/app/+state/state.effects.spec.ts', '/apps/myapp/src/app/+state/state.effects.spec.ts',
'/apps/myapp/src/app/+state/state.facade.spec.ts', '/apps/myapp/src/app/+state/state.facade.spec.ts',
'/apps/myapp/src/app/+state/state.selectors.spec.ts' '/apps/myapp/src/app/+state/state.selectors.spec.ts',
].forEach(fileName => { ].forEach((fileName) => {
expect(tree.exists(fileName)).toBeTruthy(); expect(tree.exists(fileName)).toBeTruthy();
}); });
}); });
@ -261,7 +261,7 @@ describe('ngrx', () => {
onlyAddFiles: false, onlyAddFiles: false,
skipImport: true, skipImport: true,
facade: true, facade: true,
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -277,8 +277,8 @@ describe('ngrx', () => {
'/apps/myapp/src/app/+state/state.selectors.ts', '/apps/myapp/src/app/+state/state.selectors.ts',
'/apps/myapp/src/app/+state/state.effects.spec.ts', '/apps/myapp/src/app/+state/state.effects.spec.ts',
'/apps/myapp/src/app/+state/state.facade.spec.ts', '/apps/myapp/src/app/+state/state.facade.spec.ts',
'/apps/myapp/src/app/+state/state.selectors.spec.ts' '/apps/myapp/src/app/+state/state.selectors.spec.ts',
].forEach(fileName => { ].forEach((fileName) => {
expect(tree.exists(fileName)).toBeTruthy(); expect(tree.exists(fileName)).toBeTruthy();
}); });
}); });
@ -288,7 +288,7 @@ describe('ngrx', () => {
'ngrx', 'ngrx',
{ {
name: 'state', name: 'state',
module: 'apps/myapp/src/app/app.module.ts' module: 'apps/myapp/src/app/app.module.ts',
}, },
appTree appTree
); );
@ -306,7 +306,7 @@ describe('ngrx', () => {
'ngrx', 'ngrx',
{ {
name: 'state', name: 'state',
module: '' module: '',
}, },
appTree appTree
); );
@ -322,7 +322,7 @@ describe('ngrx', () => {
'ngrx', 'ngrx',
{ {
name: 'state', name: 'state',
module: 'does-not-exist.ts' module: 'does-not-exist.ts',
}, },
appTree appTree
); );
@ -334,8 +334,8 @@ describe('ngrx', () => {
describe('code generation', () => { describe('code generation', () => {
it('should scaffold the ngrx "user" files without a facade', async () => { it('should scaffold the ngrx "user" files without a facade', async () => {
const appConfig = getAppConfig(); const appConfig = getAppConfig();
const hasFile = file => expect(tree.exists(file)).toBeTruthy(); const hasFile = (file) => expect(tree.exists(file)).toBeTruthy();
const missingFile = file => expect(tree.exists(file)).not.toBeTruthy(); const missingFile = (file) => expect(tree.exists(file)).not.toBeTruthy();
const statePath = `${findModuleParent(appConfig.appModule)}/+state`; const statePath = `${findModuleParent(appConfig.appModule)}/+state`;
const tree = await buildNgrxTree(appConfig); const tree = await buildNgrxTree(appConfig);
@ -352,7 +352,7 @@ describe('ngrx', () => {
it('should scaffold the ngrx "user" files WITH a facade', async () => { it('should scaffold the ngrx "user" files WITH a facade', async () => {
const appConfig = getAppConfig(); const appConfig = getAppConfig();
const hasFile = file => expect(tree.exists(file)).toBeTruthy(); const hasFile = (file) => expect(tree.exists(file)).toBeTruthy();
const tree = await buildNgrxTree(appConfig, 'user', true); const tree = await buildNgrxTree(appConfig, 'user', true);
const statePath = `${findModuleParent(appConfig.appModule)}/+state`; const statePath = `${findModuleParent(appConfig.appModule)}/+state`;
@ -398,8 +398,8 @@ describe('ngrx', () => {
[ [
`import { USERS_FEATURE_KEY, UsersState } from './users.reducer'`, `import { USERS_FEATURE_KEY, UsersState } from './users.reducer'`,
`export const usersQuery` `export const usersQuery`,
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -415,8 +415,8 @@ describe('ngrx', () => {
[ [
`import { UsersPartialState } from './users.reducer'`, `import { UsersPartialState } from './users.reducer'`,
`import { usersQuery } from './users.selectors'`, `import { usersQuery } from './users.selectors'`,
`export class UsersFacade` `export class UsersFacade`,
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -436,8 +436,8 @@ describe('ngrx', () => {
'state: UserState = initialState', 'state: UserState = initialState',
'action: UserAction', 'action: UserAction',
'): UserState', '): UserState',
'case UserActionTypes.UserLoaded' 'case UserActionTypes.UserLoaded',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -455,15 +455,15 @@ import {
LoadUsers, LoadUsers,
UsersLoaded, UsersLoaded,
UsersLoadError, UsersLoadError,
UsersActionTypes UsersActionTypes,
} from './users.actions';`, } from './users.actions';`,
`loadUsers$`, `loadUsers$`,
`run: (action: LoadUsers, state: UsersPartialState)`, `run: (action: LoadUsers, state: UsersPartialState)`,
`return new UsersLoaded([])`, `return new UsersLoaded([])`,
`return new UsersLoadError(error)`, `return new UsersLoadError(error)`,
'private actions$: Actions', 'private actions$: Actions',
'private dataPersistence: DataPersistence<UsersPartialState>' 'private dataPersistence: DataPersistence<UsersPartialState>',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -491,7 +491,7 @@ import {
{ {
name: 'super-users', name: 'super-users',
module: libConfig.module, module: libConfig.module,
facade: true facade: true,
}, },
appTree appTree
); );
@ -510,7 +510,7 @@ import {
{ {
name: 'super-users', name: 'super-users',
module: libConfig.module, module: libConfig.module,
facade: false facade: false,
}, },
appTree appTree
); );
@ -528,7 +528,7 @@ import {
{ {
name: 'super-users', name: 'super-users',
module: appConfig.appModule, module: appConfig.appModule,
minimal: false minimal: false,
}, },
appTree appTree
); );
@ -560,7 +560,7 @@ import {
syntax: 'creators', syntax: 'creators',
minimal: false, minimal: false,
facade: true, facade: true,
useDataPersistance: false useDataPersistance: false,
}, },
appTree appTree
); );
@ -576,8 +576,8 @@ import {
'[Users] Load Users Success', '[Users] Load Users Success',
'props<{ users: UsersEntity[] }>()', 'props<{ users: UsersEntity[] }>()',
'[Users] Load Users Failure', '[Users] Load Users Failure',
'props<{ error: any }>()' 'props<{ error: any }>()',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -588,8 +588,8 @@ import {
[ [
`export const USERS_FEATURE_KEY = 'users';`, `export const USERS_FEATURE_KEY = 'users';`,
`const usersReducer = createReducer`, `const usersReducer = createReducer`,
'export function reducer(state: State | undefined, action: Action) {' 'export function reducer(state: State | undefined, action: Action) {',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -599,8 +599,8 @@ import {
[ [
`import { createEffect, Actions, ofType } from '@ngrx/effects';`, `import { createEffect, Actions, ofType } from '@ngrx/effects';`,
'fetch({' 'fetch({',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -614,10 +614,10 @@ import {
USERS_FEATURE_KEY, USERS_FEATURE_KEY,
State, State,
UsersPartialState, UsersPartialState,
usersAdapter usersAdapter,
} from './users.reducer';`, } from './users.reducer';`,
`const { selectAll, selectEntities } = usersAdapter.getSelectors();` `const { selectAll, selectEntities } = usersAdapter.getSelectors();`,
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -628,8 +628,8 @@ import {
[ [
`loaded$ = this.store.pipe(select(UsersSelectors.getUsersLoaded));`, `loaded$ = this.store.pipe(select(UsersSelectors.getUsersLoaded));`,
`allUsers$ = this.store.pipe(select(UsersSelectors.getAllUsers));`, `allUsers$ = this.store.pipe(select(UsersSelectors.getAllUsers));`,
`selectedUsers$ = this.store.pipe(select(UsersSelectors.getSelected));` `selectedUsers$ = this.store.pipe(select(UsersSelectors.getSelected));`,
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -639,8 +639,8 @@ import {
[ [
'export interface UsersEntity', 'export interface UsersEntity',
'id: string | number; // Primary ID' 'id: string | number; // Primary ID',
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -656,14 +656,14 @@ import {
module: appConfig.appModule, module: appConfig.appModule,
syntax: 'creators', syntax: 'creators',
facade: true, facade: true,
minimal: false minimal: false,
}, },
appTree appTree
); );
const content = tree.readContent(`${statePath}/users.effects.ts`); const content = tree.readContent(`${statePath}/users.effects.ts`);
[`{ fetch }`, `, ofType`, `ofType(UsersActions.loadUsers),`].forEach( [`{ fetch }`, `, ofType`, `ofType(UsersActions.loadUsers),`].forEach(
text => { (text) => {
expect(content).toContain(text); expect(content).toContain(text);
} }
); );
@ -683,7 +683,7 @@ import {
name: 'users', name: 'users',
module: appConfig.appModule, module: appConfig.appModule,
syntax: 'creators', syntax: 'creators',
barrels: true barrels: true,
}, },
appTree appTree
); );
@ -695,8 +695,8 @@ import {
`import * as UsersFeature from './lib/+state/users.reducer';`, `import * as UsersFeature from './lib/+state/users.reducer';`,
`import * as UsersSelectors from './lib/+state/users.selectors';`, `import * as UsersSelectors from './lib/+state/users.selectors';`,
`export { UsersActions, UsersFeature, UsersSelectors };`, `export { UsersActions, UsersFeature, UsersSelectors };`,
`export * from './lib/+state/users.models';` `export * from './lib/+state/users.models';`,
].forEach(text => { ].forEach((text) => {
expect(content).toContain(text); expect(content).toContain(text);
}); });
}); });
@ -715,7 +715,7 @@ import {
facade: withFacade, facade: withFacade,
syntax: 'classes', syntax: 'classes',
minimal: false, minimal: false,
useDataPersistance: true useDataPersistance: true,
}, },
appTree appTree
); );

View File

@ -9,7 +9,7 @@ import {
filter, filter,
Rule, Rule,
Tree, Tree,
SchematicContext SchematicContext,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { Schema } from './schema'; import { Schema } from './schema';
@ -21,7 +21,7 @@ import {
addImportsToModule, addImportsToModule,
addNgRxToPackageJson, addNgRxToPackageJson,
addExportsToBarrel, addExportsToBarrel,
RequestContext RequestContext,
} from './rules'; } from './rules';
import { formatFiles } from '@nrwl/workspace'; import { formatFiles } from '@nrwl/workspace';
@ -43,7 +43,7 @@ export default function generateNgrxCollection(_options: Schema): Rule {
featureName: options.name, featureName: options.name,
moduleDir: path.dirname(options.module), moduleDir: path.dirname(options.module),
options, options,
host host,
}; };
if (options.minimal) { if (options.minimal) {
@ -62,7 +62,7 @@ export default function generateNgrxCollection(_options: Schema): Rule {
const moduleModification = !options.onlyAddFiles const moduleModification = !options.onlyAddFiles
? [ ? [
addImportsToModule(requestContext), addImportsToModule(requestContext),
addExportsToBarrel(requestContext.options) addExportsToBarrel(requestContext.options),
] ]
: []; : [];
@ -74,7 +74,7 @@ export default function generateNgrxCollection(_options: Schema): Rule {
...fileGeneration, ...fileGeneration,
...moduleModification, ...moduleModification,
...packageJsonModification, ...packageJsonModification,
formatFiles(options) formatFiles(options),
])(host, context); ])(host, context);
}; };
} }
@ -89,14 +89,14 @@ export default function generateNgrxCollection(_options: Schema): Rule {
function generateNgrxFilesFromTemplates(options: Schema) { function generateNgrxFilesFromTemplates(options: Schema) {
const name = options.name; const name = options.name;
const moduleDir = path.dirname(options.module); const moduleDir = path.dirname(options.module);
const excludeFacade = path => path.match(/^((?!facade).)*$/); const excludeFacade = (path) => path.match(/^((?!facade).)*$/);
const templateSource = apply( const templateSource = apply(
url(options.syntax === 'creators' ? './creator-files' : './files'), url(options.syntax === 'creators' ? './creator-files' : './files'),
[ [
!options.facade ? filter(excludeFacade) : noop(), !options.facade ? filter(excludeFacade) : noop(),
template({ ...options, tmpl: '', ...names(name) }), template({ ...options, tmpl: '', ...names(name) }),
move(moduleDir) move(moduleDir),
] ]
); );
@ -109,6 +109,6 @@ function generateNgrxFilesFromTemplates(options: Schema) {
function normalizeOptions(options: Schema): Schema { function normalizeOptions(options: Schema): Schema {
return { return {
...options, ...options,
directory: toFileName(options.directory) directory: toFileName(options.directory),
}; };
} }

View File

@ -83,7 +83,7 @@ export function addExportsToBarrel(options: Schema): Rule {
indexFilePath, indexFilePath,
`export * from '${statePath}.facade';` `export * from '${statePath}.facade';`
) )
: []) : []),
]); ]);
} }
} }

View File

@ -5,7 +5,7 @@ import { insert } from '@nrwl/workspace';
import { RequestContext } from './request-context'; import { RequestContext } from './request-context';
import { import {
addImportToModule, addImportToModule,
addProviderToModule addProviderToModule,
} from '../../../utils/ast-utils'; } from '../../../utils/ast-utils';
import { Change, insertImport } from '@nrwl/workspace/src/utils/ast-utils'; import { Change, insertImport } from '@nrwl/workspace/src/utils/ast-utils';
@ -85,20 +85,20 @@ export function addImportsToModule(context: RequestContext): Rule {
...addImportToModule(source, modulePath, devTools), ...addImportToModule(source, modulePath, devTools),
...(hasRouter ...(hasRouter
? addImportToModule(source, modulePath, storeRouterModule) ? addImportToModule(source, modulePath, storeRouterModule)
: []) : []),
]); ]);
} else { } else {
let common = [ let common = [
addImport.apply(this, storeModule), addImport.apply(this, storeModule),
addImport.apply(this, effectsModule), addImport.apply(this, effectsModule),
addImport(reducerImports, reducerPath, true), addImport(reducerImports, reducerPath, true),
addImport(effectsName, effectsPath) addImport(effectsName, effectsPath),
]; ];
if (context.options.facade) { if (context.options.facade) {
common = [ common = [
...common, ...common,
addImport(facadeName, facadePath), addImport(facadeName, facadePath),
...addProviderToModule(source, modulePath, `${facadeName}`) ...addProviderToModule(source, modulePath, `${facadeName}`),
]; ];
} }
@ -118,13 +118,13 @@ export function addImportsToModule(context: RequestContext): Rule {
...(hasRouter ...(hasRouter
? addImportToModule(source, modulePath, storeRouterModule) ? addImportToModule(source, modulePath, storeRouterModule)
: []), : []),
...addImportToModule(source, modulePath, storeForFeature) ...addImportToModule(source, modulePath, storeForFeature),
]); ]);
} else { } else {
insert(host, modulePath, [ insert(host, modulePath, [
...common, ...common,
...addImportToModule(source, modulePath, storeForFeature), ...addImportToModule(source, modulePath, storeForFeature),
...addImportToModule(source, modulePath, effectsForFeature) ...addImportToModule(source, modulePath, effectsForFeature),
]); ]);
} }
} }

View File

@ -8,11 +8,11 @@ export function addNgRxToPackageJson(): Rule {
'@ngrx/store': ngrxVersion, '@ngrx/store': ngrxVersion,
'@ngrx/effects': ngrxVersion, '@ngrx/effects': ngrxVersion,
'@ngrx/entity': ngrxVersion, '@ngrx/entity': ngrxVersion,
'@ngrx/router-store': ngrxVersion '@ngrx/router-store': ngrxVersion,
}, },
{ {
'@ngrx/schematics': ngrxVersion, '@ngrx/schematics': ngrxVersion,
'@ngrx/store-devtools': ngrxVersion '@ngrx/store-devtools': ngrxVersion,
} }
); );
} }

View File

@ -3,7 +3,7 @@ import { StorybookStoriesSchema } from './stories';
import { import {
runSchematic, runSchematic,
runExternalSchematic, runExternalSchematic,
callRule callRule,
} from '../../utils/testing'; } from '../../utils/testing';
import { createEmptyWorkspace } from '@nrwl/workspace/testing'; import { createEmptyWorkspace } from '@nrwl/workspace/testing';
@ -41,12 +41,12 @@ describe('schematic:stories', () => {
`buttonType: text('buttonType', 'button'),`, `buttonType: text('buttonType', 'button'),`,
`style: text('style', 'default'),`, `style: text('style', 'default'),`,
`age: number('age', ''),`, `age: number('age', ''),`,
`isOn: boolean('isOn', false), ` `isOn: boolean('isOn', false), `,
]; ];
const storyContent = tree.readContent( const storyContent = tree.readContent(
'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts' 'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts'
); );
propLines.forEach(propLine => { propLines.forEach((propLine) => {
storyContent.includes(propLine); storyContent.includes(propLine);
}); });
}); });
@ -78,12 +78,12 @@ describe('schematic:stories', () => {
`buttonType: text('buttonType', 'button'),`, `buttonType: text('buttonType', 'button'),`,
`style: text('style', 'default'),`, `style: text('style', 'default'),`,
`age: number('age', ''),`, `age: number('age', ''),`,
`isOn: boolean('isOn', false), ` `isOn: boolean('isOn', false), `,
]; ];
const storyContent = tree.readContent( const storyContent = tree.readContent(
'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts' 'libs/test-ui-lib/src/lib/test-button/test-button.component.stories.ts'
); );
propLines.forEach(propLine => { propLines.forEach((propLine) => {
storyContent.includes(propLine); storyContent.includes(propLine);
}); });
@ -125,14 +125,14 @@ export async function createTestUILib(libName: string): Promise<Tree> {
appTree = createEmptyWorkspace(appTree); appTree = createEmptyWorkspace(appTree);
appTree = await callRule( appTree = await callRule(
externalSchematic('@nrwl/angular', 'library', { externalSchematic('@nrwl/angular', 'library', {
name: libName name: libName,
}), }),
appTree appTree
); );
appTree = await callRule( appTree = await callRule(
externalSchematic('@schematics/angular', 'component', { externalSchematic('@schematics/angular', 'component', {
name: 'test-button', name: 'test-button',
project: libName project: libName,
}), }),
appTree appTree
); );
@ -146,7 +146,7 @@ export async function createTestUILib(libName: string): Promise<Tree> {
externalSchematic('@schematics/angular', 'module', { externalSchematic('@schematics/angular', 'module', {
name: 'nested', name: 'nested',
project: libName, project: libName,
path: `libs/${libName}/src/lib` path: `libs/${libName}/src/lib`,
}), }),
appTree appTree
); );
@ -155,7 +155,7 @@ export async function createTestUILib(libName: string): Promise<Tree> {
name: 'nested-button', name: 'nested-button',
project: libName, project: libName,
module: 'nested', module: 'nested',
path: `libs/${libName}/src/lib/nested` path: `libs/${libName}/src/lib/nested`,
}), }),
appTree appTree
); );
@ -192,7 +192,7 @@ export class TestButtonComponent implements OnInit {
appTree = await callRule( appTree = await callRule(
externalSchematic('@schematics/angular', 'component', { externalSchematic('@schematics/angular', 'component', {
name: 'test-other', name: 'test-other',
project: libName project: libName,
}), }),
appTree appTree
); );

View File

@ -4,7 +4,7 @@ import {
schematic, schematic,
SchematicContext, SchematicContext,
SchematicsException, SchematicsException,
Tree Tree,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { getProjectConfig } from '@nrwl/workspace'; import { getProjectConfig } from '@nrwl/workspace';
import { SyntaxKind } from 'typescript'; import { SyntaxKind } from 'typescript';
@ -30,14 +30,14 @@ export function createAllStories(
const libPath = getProjectConfig(tree, projectName).sourceRoot + '/lib'; const libPath = getProjectConfig(tree, projectName).sourceRoot + '/lib';
let moduleFilePaths = [] as string[]; let moduleFilePaths = [] as string[];
tree.getDir(libPath).visit(filePath => { tree.getDir(libPath).visit((filePath) => {
if (!filePath.endsWith('.module.ts')) { if (!filePath.endsWith('.module.ts')) {
return; return;
} }
moduleFilePaths.push(filePath); moduleFilePaths.push(filePath);
}); });
return chain( return chain(
moduleFilePaths.map(filePath => { moduleFilePaths.map((filePath) => {
const file = getTsSourceFile(tree, filePath); const file = getTsSourceFile(tree, filePath);
const ngModuleDecorators = getDecoratorMetadata( const ngModuleDecorators = getDecoratorMetadata(
@ -51,12 +51,12 @@ export function createAllStories(
); );
} }
const ngModuleDecorator = ngModuleDecorators[0]; const ngModuleDecorator = ngModuleDecorators[0];
const syntaxList = ngModuleDecorator.getChildren().find(node => { const syntaxList = ngModuleDecorator.getChildren().find((node) => {
return node.kind === SyntaxKind.SyntaxList; return node.kind === SyntaxKind.SyntaxList;
}); });
const declarationsPropertyAssignment = syntaxList const declarationsPropertyAssignment = syntaxList
.getChildren() .getChildren()
.find(node => { .find((node) => {
return ( return (
node.kind === SyntaxKind.PropertyAssignment && node.kind === SyntaxKind.PropertyAssignment &&
node.getChildren()[0].getText() === 'declarations' node.getChildren()[0].getText() === 'declarations'
@ -69,38 +69,38 @@ export function createAllStories(
} }
const declaredComponents = declarationsPropertyAssignment const declaredComponents = declarationsPropertyAssignment
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.ArrayLiteralExpression) .find((node) => node.kind === SyntaxKind.ArrayLiteralExpression)
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.SyntaxList) .find((node) => node.kind === SyntaxKind.SyntaxList)
.getChildren() .getChildren()
.filter(node => node.kind === SyntaxKind.Identifier) .filter((node) => node.kind === SyntaxKind.Identifier)
.map(node => node.getText()) .map((node) => node.getText())
.filter(name => name.endsWith('Component')); .filter((name) => name.endsWith('Component'));
const imports = file.statements.filter( const imports = file.statements.filter(
statement => statement.kind === SyntaxKind.ImportDeclaration (statement) => statement.kind === SyntaxKind.ImportDeclaration
); );
const componentInfo = declaredComponents.map(componentName => { const componentInfo = declaredComponents.map((componentName) => {
try { try {
const importStatement = imports.find(statement => { const importStatement = imports.find((statement) => {
const namedImports = statement const namedImports = statement
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.ImportClause) .find((node) => node.kind === SyntaxKind.ImportClause)
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.NamedImports); .find((node) => node.kind === SyntaxKind.NamedImports);
if (namedImports === undefined) return false; if (namedImports === undefined) return false;
const importedIdentifiers = namedImports const importedIdentifiers = namedImports
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.SyntaxList) .find((node) => node.kind === SyntaxKind.SyntaxList)
.getChildren() .getChildren()
.filter(node => node.kind === SyntaxKind.ImportSpecifier) .filter((node) => node.kind === SyntaxKind.ImportSpecifier)
.map(node => node.getText()); .map((node) => node.getText());
return importedIdentifiers.includes(componentName); return importedIdentifiers.includes(componentName);
}); });
const fullPath = importStatement const fullPath = importStatement
.getChildren() .getChildren()
.find(node => node.kind === SyntaxKind.StringLiteral) .find((node) => node.kind === SyntaxKind.StringLiteral)
.getText() .getText()
.slice(1, -1); .slice(1, -1);
const path = fullPath.slice(0, fullPath.lastIndexOf('/')); const path = fullPath.slice(0, fullPath.lastIndexOf('/'));
@ -119,14 +119,14 @@ export function createAllStories(
const modulePath = filePath.substr(0, filePath.lastIndexOf('/')); const modulePath = filePath.substr(0, filePath.lastIndexOf('/'));
return chain( return chain(
componentInfo componentInfo
.filter(info => info !== undefined) .filter((info) => info !== undefined)
.map(info => .map((info) =>
chain([ chain([
schematic<CreateComponentStoriesFileSchema>('component-story', { schematic<CreateComponentStoriesFileSchema>('component-story', {
libPath: modulePath, libPath: modulePath,
componentName: info.name, componentName: info.name,
componentPath: info.path, componentPath: info.path,
componentFileName: info.componentFileName componentFileName: info.componentFileName,
}), }),
generateCypressSpecs generateCypressSpecs
? schematic<CreateComponentSpecFileSchema>( ? schematic<CreateComponentSpecFileSchema>(
@ -136,10 +136,10 @@ export function createAllStories(
libPath: modulePath, libPath: modulePath,
componentName: info.name, componentName: info.name,
componentPath: info.path, componentPath: info.path,
componentFileName: info.componentFileName componentFileName: info.componentFileName,
} }
) )
: () => {} : () => {},
]) ])
) )
); );

View File

@ -17,7 +17,7 @@ describe('schematic:configuration', () => {
name: 'test-ui-lib', name: 'test-ui-lib',
configureCypress: false, configureCypress: false,
generateCypressSpecs: false, generateCypressSpecs: false,
generateStories: false generateStories: false,
}, },
appTree appTree
); );
@ -56,7 +56,7 @@ describe('schematic:configuration', () => {
name: 'test-ui-lib', name: 'test-ui-lib',
configureCypress: true, configureCypress: true,
generateCypressSpecs: true, generateCypressSpecs: true,
generateStories: true generateStories: true,
}, },
appTree appTree
); );

View File

@ -3,7 +3,7 @@ import {
externalSchematic, externalSchematic,
Rule, Rule,
schematic, schematic,
noop noop,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { StorybookStoriesSchema } from '../stories/stories'; import { StorybookStoriesSchema } from '../stories/stories';
import { StorybookConfigureSchema } from './schema'; import { StorybookConfigureSchema } from './schema';
@ -19,9 +19,9 @@ export default function(schema: StorybookConfigureSchema): Rule {
externalSchematic('@nrwl/storybook', 'configuration', { externalSchematic('@nrwl/storybook', 'configuration', {
name: schema.name, name: schema.name,
uiFramework: '@storybook/angular', uiFramework: '@storybook/angular',
configureCypress: schema.configureCypress configureCypress: schema.configureCypress,
}), }),
schema.generateStories ? generateStories(schema) : noop() schema.generateStories ? generateStories(schema) : noop(),
]); ]);
} }
@ -30,7 +30,7 @@ function generateStories(schema: StorybookConfigureSchema): Rule {
return schematic<StorybookStoriesSchema>('stories', { return schematic<StorybookStoriesSchema>('stories', {
name: schema.name, name: schema.name,
generateCypressSpecs: generateCypressSpecs:
schema.configureCypress && schema.generateCypressSpecs schema.configureCypress && schema.generateCypressSpecs,
}); });
}; };
} }

View File

@ -17,7 +17,7 @@ describe('upgrade-module', () => {
'upgrade-module', 'upgrade-module',
{ {
name: 'legacy', name: 'legacy',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -39,8 +39,8 @@ describe('upgrade-module', () => {
`/package.json`, `/package.json`,
JSON.stringify({ JSON.stringify({
dependencies: { dependencies: {
'@angular/core': '4.4.4' '@angular/core': '4.4.4',
} },
}) })
); );
@ -48,7 +48,7 @@ describe('upgrade-module', () => {
'upgrade-module', 'upgrade-module',
{ {
name: 'legacy', name: 'legacy',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -63,8 +63,8 @@ describe('upgrade-module', () => {
`/package.json`, `/package.json`,
JSON.stringify({ JSON.stringify({
dependencies: { dependencies: {
'@angular/core': '4.4.4' '@angular/core': '4.4.4',
} },
}) })
); );
@ -73,7 +73,7 @@ describe('upgrade-module', () => {
{ {
name: 'legacy', name: 'legacy',
skipPackageJson: true, skipPackageJson: true,
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -88,7 +88,7 @@ describe('upgrade-module', () => {
{ {
name: 'legacy', name: 'legacy',
router: true, router: true,
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );
@ -103,7 +103,7 @@ describe('upgrade-module', () => {
{ {
name: 'legacy', name: 'legacy',
angularJsImport: 'legacy-app', angularJsImport: 'legacy-app',
project: 'myapp' project: 'myapp',
}, },
appTree appTree
); );

View File

@ -9,7 +9,7 @@ import {
SchematicContext, SchematicContext,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { names, toClassName, toFileName } from '@nrwl/workspace'; import { names, toClassName, toFileName } from '@nrwl/workspace';
@ -24,7 +24,7 @@ import {
addImportToModule, addImportToModule,
getBootstrapComponent, getBootstrapComponent,
readBootstrapInfo, readBootstrapInfo,
removeFromNgModule removeFromNgModule,
} from '../../utils/ast-utils'; } from '../../utils/ast-utils';
import { insertImport } from '@nrwl/workspace/src/utils/ast-utils'; import { insertImport } from '@nrwl/workspace/src/utils/ast-utils';
@ -58,7 +58,7 @@ function addImportsToModule(options: Schema): Rule {
moduleSource, moduleSource,
modulePath, modulePath,
getBootstrapComponent(moduleSource, moduleClassName) getBootstrapComponent(moduleSource, moduleClassName)
) ),
]); ]);
return host; return host;
@ -75,7 +75,7 @@ function addNgDoBootstrapToModule(options: Schema): Rule {
insert(host, modulePath, [ insert(host, modulePath, [
...addParameterToConstructor(moduleSource, modulePath, { ...addParameterToConstructor(moduleSource, modulePath, {
className: moduleClassName, className: moduleClassName,
param: 'private upgrade: UpgradeModule' param: 'private upgrade: UpgradeModule',
}), }),
...addMethod(moduleSource, modulePath, { ...addMethod(moduleSource, modulePath, {
className: moduleClassName, className: moduleClassName,
@ -83,9 +83,9 @@ function addNgDoBootstrapToModule(options: Schema): Rule {
body: ` body: `
configure${toClassName(options.name)}(this.upgrade.injector); configure${toClassName(options.name)}(this.upgrade.injector);
this.upgrade.bootstrap(document.body, ['downgraded', '${options.name}']); this.upgrade.bootstrap(document.body, ['downgraded', '${options.name}']);
` `,
}), }),
...removeFromNgModule(moduleSource, modulePath, 'bootstrap') ...removeFromNgModule(moduleSource, modulePath, 'bootstrap'),
]); ]);
return host; return host;
@ -99,7 +99,7 @@ function createFiles(angularJsImport: string, options: Schema): Rule {
mainPath, mainPath,
moduleSpec, moduleSpec,
bootstrapComponentClassName, bootstrapComponentClassName,
bootstrapComponentFileName bootstrapComponentFileName,
} = readBootstrapInfo(host, options.project); } = readBootstrapInfo(host, options.project);
const dir = path.dirname(mainPath); const dir = path.dirname(mainPath);
@ -113,9 +113,9 @@ function createFiles(angularJsImport: string, options: Schema): Rule {
angularJsModule: options.name, angularJsModule: options.name,
bootstrapComponentClassName, bootstrapComponentClassName,
bootstrapComponentFileName, bootstrapComponentFileName,
...names(options.name) ...names(options.name),
}), }),
move(dir) move(dir),
]); ]);
const r = branchAndMerge(chain([mergeWith(templateSource)])); const r = branchAndMerge(chain([mergeWith(templateSource)]));
return r(host, context); return r(host, context);
@ -132,6 +132,6 @@ export default function(options: Schema): Rule {
addImportsToModule(options), addImportsToModule(options),
addNgDoBootstrapToModule(options), addNgDoBootstrapToModule(options),
options.skipPackageJson ? noop() : addUpgradeToPackageJson(), options.skipPackageJson ? noop() : addUpgradeToPackageJson(),
formatFiles(options) formatFiles(options),
]); ]);
} }

View File

@ -8,7 +8,7 @@ describe('ast-utils', () => {
const fileName = 'app.module.ts'; const fileName = 'app.module.ts';
const createTemplate = (content: string, close: string) => ({ const createTemplate = (content: string, close: string) => ({
start: content.length, start: content.length,
text: content + close text: content + close,
}); });
const createStockModule = (content: string) => const createStockModule = (content: string) =>
createSourceFile(fileName, content, ScriptTarget.Latest, true); createSourceFile(fileName, content, ScriptTarget.Latest, true);
@ -23,7 +23,7 @@ describe('ast-utils', () => {
const source = createStockModule(text); const source = createStockModule(text);
const change = addProviderToModule(source, fileName, toAdd); const change = addProviderToModule(source, fileName, toAdd);
const expectedChange = [ const expectedChange = [
new InsertChange(fileName, start, ` providers: [${toAdd}]\n`) new InsertChange(fileName, start, ` providers: [${toAdd}]\n`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);
@ -53,7 +53,7 @@ describe('ast-utils', () => {
let source = createStockModule(template.text); let source = createStockModule(template.text);
let change = addProviderToModule(source, fileName, toAdd); let change = addProviderToModule(source, fileName, toAdd);
let expectedChange = [ let expectedChange = [
new InsertChange(fileName, template.start, `, ${toAdd}`) new InsertChange(fileName, template.start, `, ${toAdd}`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);
@ -66,7 +66,7 @@ describe('ast-utils', () => {
source = createStockModule(template.text); source = createStockModule(template.text);
change = addProviderToModule(source, fileName, toAdd); change = addProviderToModule(source, fileName, toAdd);
expectedChange = [ expectedChange = [
new InsertChange(fileName, template.start, `, ${toAdd}`) new InsertChange(fileName, template.start, `, ${toAdd}`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);
@ -78,7 +78,7 @@ describe('ast-utils', () => {
source = createStockModule(template.text); source = createStockModule(template.text);
change = addProviderToModule(source, fileName, toAdd); change = addProviderToModule(source, fileName, toAdd);
expectedChange = [ expectedChange = [
new InsertChange(fileName, template.start, `, ${toAdd}`) new InsertChange(fileName, template.start, `, ${toAdd}`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);
@ -91,7 +91,7 @@ describe('ast-utils', () => {
source = createStockModule(template.text); source = createStockModule(template.text);
change = addProviderToModule(source, fileName, toAdd); change = addProviderToModule(source, fileName, toAdd);
expectedChange = [ expectedChange = [
new InsertChange(fileName, template.start, `, ${toAdd}`) new InsertChange(fileName, template.start, `, ${toAdd}`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);
@ -103,7 +103,7 @@ describe('ast-utils', () => {
source = createStockModule(template.text); source = createStockModule(template.text);
change = addProviderToModule(source, fileName, toAdd); change = addProviderToModule(source, fileName, toAdd);
expectedChange = [ expectedChange = [
new InsertChange(fileName, template.start, `, ${toAdd}`) new InsertChange(fileName, template.start, `, ${toAdd}`),
]; ];
expect(change).toEqual(expectedChange); expect(change).toEqual(expectedChange);

View File

@ -6,7 +6,7 @@ import {
getProjectConfig, getProjectConfig,
getSourceNodes, getSourceNodes,
InsertChange, InsertChange,
RemoveChange RemoveChange,
} from '@nrwl/workspace/src/utils/ast-utils'; } from '@nrwl/workspace/src/utils/ast-utils';
import { import {
Tree, Tree,
@ -16,7 +16,7 @@ import {
SchematicContext, SchematicContext,
mergeWith, mergeWith,
apply, apply,
forEach forEach,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import * as path from 'path'; import * as path from 'path';
import { toFileName } from '@nrwl/workspace/src/utils/name-utils'; import { toFileName } from '@nrwl/workspace/src/utils/name-utils';
@ -48,7 +48,7 @@ function _angularImportsFromNode(
if (nb.kind == ts.SyntaxKind.NamespaceImport) { if (nb.kind == ts.SyntaxKind.NamespaceImport) {
// This is of the form `import * as name from 'path'`. Return `name.`. // This is of the form `import * as name from 'path'`. Return `name.`.
return { return {
[(nb as ts.NamespaceImport).name.text + '.']: modulePath [(nb as ts.NamespaceImport).name.text + '.']: modulePath,
}; };
} else { } else {
// This is of the form `import {a,b,c} from 'path'` // This is of the form `import {a,b,c} from 'path'`
@ -98,14 +98,14 @@ export function getDecoratorMetadata(
); );
return getSourceNodes(source) return getSourceNodes(source)
.filter(node => { .filter((node) => {
return ( return (
node.kind == ts.SyntaxKind.Decorator && node.kind == ts.SyntaxKind.Decorator &&
(node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression
); );
}) })
.map(node => (node as ts.Decorator).expression as ts.CallExpression) .map((node) => (node as ts.Decorator).expression as ts.CallExpression)
.filter(expr => { .filter((expr) => {
if (expr.expression.kind == ts.SyntaxKind.Identifier) { if (expr.expression.kind == ts.SyntaxKind.Identifier) {
const id = expr.expression as ts.Identifier; const id = expr.expression as ts.Identifier;
@ -132,11 +132,11 @@ export function getDecoratorMetadata(
return false; return false;
}) })
.filter( .filter(
expr => (expr) =>
expr.arguments[0] && expr.arguments[0] &&
expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression
) )
.map(expr => expr.arguments[0] as ts.ObjectLiteralExpression); .map((expr) => expr.arguments[0] as ts.ObjectLiteralExpression);
} }
function _addSymbolToNgModuleMetadata( function _addSymbolToNgModuleMetadata(
@ -154,7 +154,7 @@ function _addSymbolToNgModuleMetadata(
} }
// Get all the children property assignment of object literals. // Get all the children property assignment of object literals.
const matchingProperties: ts.ObjectLiteralElement[] = (node as ts.ObjectLiteralExpression).properties const matchingProperties: ts.ObjectLiteralElement[] = (node as ts.ObjectLiteralExpression).properties
.filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment) .filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals // Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions). // (but not expressions).
.filter((prop: ts.PropertyAssignment) => { .filter((prop: ts.PropertyAssignment) => {
@ -228,7 +228,7 @@ function _addSymbolToNgModuleMetadata(
const isArray = Array.isArray(node); const isArray = Array.isArray(node);
if (isArray) { if (isArray) {
const nodeArray = (node as {}) as Array<ts.Node>; const nodeArray = (node as {}) as Array<ts.Node>;
const symbolsArray = nodeArray.map(node => node.getText()); const symbolsArray = nodeArray.map((node) => node.getText());
if (symbolsArray.includes(expression)) { if (symbolsArray.includes(expression)) {
return []; return [];
} }
@ -301,7 +301,7 @@ export function removeFromNgModule(
modulePath, modulePath,
matchingProperty.getStart(source), matchingProperty.getStart(source),
matchingProperty.getFullText(source) matchingProperty.getFullText(source)
) ),
]; ];
} else { } else {
return []; return [];
@ -331,11 +331,11 @@ export function addImportToTestBed(
); );
const configureTestingModuleObjectLiterals = allCalls const configureTestingModuleObjectLiterals = allCalls
.filter(c => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression) .filter((c) => c.expression.kind === ts.SyntaxKind.PropertyAccessExpression)
.filter( .filter(
(c: any) => c.expression.name.getText(source) === 'configureTestingModule' (c: any) => c.expression.name.getText(source) === 'configureTestingModule'
) )
.map(c => .map((c) =>
c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression c.arguments[0].kind === ts.SyntaxKind.ObjectLiteralExpression
? c.arguments[0] ? c.arguments[0]
: null : null
@ -346,7 +346,7 @@ export function addImportToTestBed(
.getFirstToken(source) .getFirstToken(source)
.getEnd(); .getEnd();
return [ return [
new InsertChange(specPath, startPosition, `imports: [${symbolName}], `) new InsertChange(specPath, startPosition, `imports: [${symbolName}], `),
]; ];
} else { } else {
return []; return [];
@ -439,7 +439,7 @@ function getListOfRoutes(
ts.SyntaxKind.VariableDeclaration ts.SyntaxKind.VariableDeclaration
) as ts.VariableDeclaration[]; ) as ts.VariableDeclaration[];
const routesDeclaration = variableDeclarations.find(x => { const routesDeclaration = variableDeclarations.find((x) => {
return x.name.getText() === routes.getText(); return x.name.getText() === routes.getText();
}); });
@ -534,7 +534,7 @@ export function readBootstrapInfo(
throw new Error(`main.ts can only import a single module`); throw new Error(`main.ts can only import a single module`);
} }
const moduleImport = moduleImports[0]; const moduleImport = moduleImports[0];
const moduleClassName = moduleImport.bindings.filter(b => const moduleClassName = moduleImport.bindings.filter((b) =>
b.endsWith('Module') b.endsWith('Module')
)[0]; )[0];
@ -575,7 +575,7 @@ export function readBootstrapInfo(
moduleSource, moduleSource,
moduleClassName, moduleClassName,
bootstrapComponentClassName, bootstrapComponentClassName,
bootstrapComponentFileName bootstrapComponentFileName,
}; };
} }
@ -610,7 +610,7 @@ function getMatchingObjectLiteralElement(
) { ) {
return ( return (
(node as ts.ObjectLiteralExpression).properties (node as ts.ObjectLiteralExpression).properties
.filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment) .filter((prop) => prop.kind == ts.SyntaxKind.PropertyAssignment)
// Filter out every fields that's not "metadataField". Also handles string literals // Filter out every fields that's not "metadataField". Also handles string literals
// (but not expressions). // (but not expressions).
.filter((prop: ts.PropertyAssignment) => { .filter((prop: ts.PropertyAssignment) => {

View File

@ -1,10 +1,10 @@
export const enum UnitTestRunner { export const enum UnitTestRunner {
Karma = 'karma', Karma = 'karma',
Jest = 'jest', Jest = 'jest',
None = 'none' None = 'none',
} }
export const enum E2eTestRunner { export const enum E2eTestRunner {
Protractor = 'protractor', Protractor = 'protractor',
Cypress = 'cypress', Cypress = 'cypress',
None = 'none' None = 'none',
} }

View File

@ -4,7 +4,7 @@ import { Tree, Rule, externalSchematic } from '@angular-devkit/schematics';
import { names, toFileName } from '@nrwl/workspace/src/utils/name-utils'; import { names, toFileName } from '@nrwl/workspace/src/utils/name-utils';
import { import {
createEmptyWorkspace, createEmptyWorkspace,
MockBuilderContext MockBuilderContext,
} from '@nrwl/workspace/testing'; } from '@nrwl/workspace/testing';
import { TestingArchitectHost } from '@angular-devkit/architect/testing'; import { TestingArchitectHost } from '@angular-devkit/architect/testing';
import { schema } from '@angular-devkit/core'; import { schema } from '@angular-devkit/core';
@ -82,7 +82,7 @@ export function createApp(
// save for getAppDir() lookup by external *.spec.ts tests // save for getAppDir() lookup by external *.spec.ts tests
appConfig = { appConfig = {
appName, appName,
appModule: `/apps/${appName}/src/app/app.module.ts` appModule: `/apps/${appName}/src/app/app.module.ts`,
}; };
tree.create( tree.create(
@ -121,13 +121,13 @@ export function createApp(
tree.create( tree.create(
`/apps/${appName}/tsconfig.app.json`, `/apps/${appName}/tsconfig.app.json`,
JSON.stringify({ JSON.stringify({
include: ['**/*.ts'] include: ['**/*.ts'],
}) })
); );
tree.create( tree.create(
`/apps/${appName}-e2e/tsconfig.e2e.json`, `/apps/${appName}-e2e/tsconfig.e2e.json`,
JSON.stringify({ JSON.stringify({
include: ['../**/*.ts'] include: ['../**/*.ts'],
}) })
); );
tree.overwrite( tree.overwrite(
@ -142,15 +142,15 @@ export function createApp(
architect: { architect: {
build: { build: {
options: { options: {
main: `apps/${appName}/src/main.ts` main: `apps/${appName}/src/main.ts`,
} },
}, },
serve: { serve: {
options: {} options: {},
} },
} },
} },
} },
}) })
); );
return tree; return tree;
@ -162,7 +162,7 @@ export function createLib(tree: Tree, libName: string): Tree {
libConfig = { libConfig = {
name, name,
module: `/libs/${propertyName}/src/lib/${fileName}.module.ts`, module: `/libs/${propertyName}/src/lib/${fileName}.module.ts`,
barrel: `/libs/${propertyName}/src/index.ts` barrel: `/libs/${propertyName}/src/index.ts`,
}; };
tree.create( tree.create(

View File

@ -3,7 +3,7 @@ import { angularJsVersion } from './versions';
import { updateJsonInTree } from '@nrwl/workspace'; import { updateJsonInTree } from '@nrwl/workspace';
export function addUpgradeToPackageJson(): Rule { export function addUpgradeToPackageJson(): Rule {
return updateJsonInTree('package.json', packageJson => { return updateJsonInTree('package.json', (packageJson) => {
if (!packageJson['dependencies']) { if (!packageJson['dependencies']) {
packageJson['dependencies'] = {}; packageJson['dependencies'] = {};
} }

View File

@ -4,7 +4,7 @@ import {
mergeWith, mergeWith,
Rule, Rule,
template, template,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { addDepsToPackageJson, readJsonInTree } from '@nrwl/workspace'; import { addDepsToPackageJson, readJsonInTree } from '@nrwl/workspace';
import ignore from 'ignore'; import ignore from 'ignore';
@ -12,7 +12,7 @@ import { bazelVersion, iBazelVersion } from '../utils/versions';
import { noop } from 'rxjs'; import { noop } from 'rxjs';
function updateGitIgnore(): Rule { function updateGitIgnore(): Rule {
return host => { return (host) => {
if (!host.exists('.gitignore')) { if (!host.exists('.gitignore')) {
return; return;
} }
@ -34,33 +34,33 @@ const updateDependencies = addDepsToPackageJson(
{}, {},
{ {
'@bazel/bazel': bazelVersion, '@bazel/bazel': bazelVersion,
'@bazel/ibazel': iBazelVersion '@bazel/ibazel': iBazelVersion,
}, },
true true
); );
function addFiles() { function addFiles() {
return host => { return (host) => {
if (host.exists('/.bazelrc')) { if (host.exists('/.bazelrc')) {
return noop; return noop;
} }
return mergeWith( return mergeWith(
apply(url('./files/root'), [ apply(url('./files/root'), [
template({ template({
tmpl: '' tmpl: '',
}) }),
]) ])
); );
}; };
} }
export default (): Rule => { export default (): Rule => {
return host => { return (host) => {
const packageJson = readJsonInTree(host, 'package.json'); const packageJson = readJsonInTree(host, 'package.json');
return chain([ return chain([
updateGitIgnore(), updateGitIgnore(),
!packageJson.devDependencies['@bazel/bazel'] ? updateDependencies : noop, !packageJson.devDependencies['@bazel/bazel'] ? updateDependencies : noop,
addFiles() addFiles(),
]); ]);
}; };
}; };

View File

@ -102,7 +102,7 @@ describe('@nrwl/bazel:sync', () => {
beforeEach(async () => { beforeEach(async () => {
tree = await callRule( tree = await callRule(
chain([ chain([
updateWorkspace(workspace => { updateWorkspace((workspace) => {
workspace.projects.add({ workspace.projects.add({
name: 'proj', name: 'proj',
root: 'proj', root: 'proj',
@ -111,21 +111,21 @@ describe('@nrwl/bazel:sync', () => {
builder: '@nrwl/web:build', builder: '@nrwl/web:build',
options: {}, options: {},
configurations: { configurations: {
production: {} production: {},
} },
}, },
serve: { serve: {
builder: '@nrwl/web:dev-server', builder: '@nrwl/web:dev-server',
options: {}, options: {},
configurations: { configurations: {
production: {} production: {},
} },
}, },
test: { test: {
builder: '@nrwl/jest:jest', builder: '@nrwl/jest:jest',
options: {} options: {},
} },
} },
}); });
workspace.projects.add({ workspace.projects.add({
name: 'proj2', name: 'proj2',
@ -135,28 +135,28 @@ describe('@nrwl/bazel:sync', () => {
builder: '@angular-devkit/build-angular:browser', builder: '@angular-devkit/build-angular:browser',
options: {}, options: {},
configurations: { configurations: {
production: {} production: {},
} },
}, },
serve: { serve: {
builder: '@angular-devkit/build-angular:dev-server', builder: '@angular-devkit/build-angular:dev-server',
options: {}, options: {},
configurations: { configurations: {
production: {} production: {},
} },
}, },
test: { test: {
builder: '@angular-devkit/build-angular:karma', builder: '@angular-devkit/build-angular:karma',
options: {} options: {},
} },
} },
}); });
}), }),
updateJsonInTree<NxJson>('nx.json', json => { updateJsonInTree<NxJson>('nx.json', (json) => {
json.projects['proj'] = {}; json.projects['proj'] = {};
json.projects['proj2'] = {}; json.projects['proj2'] = {};
return json; return json;
}) }),
]), ]),
tree tree
); );

View File

@ -9,18 +9,18 @@ import {
Source, Source,
template, template,
Tree, Tree,
url url,
} from '@angular-devkit/schematics'; } from '@angular-devkit/schematics';
import { import {
getProjectGraphFromHost, getProjectGraphFromHost,
getWorkspace, getWorkspace,
readJsonInTree, readJsonInTree,
readWorkspace readWorkspace,
} from '@nrwl/workspace'; } from '@nrwl/workspace';
import { join, normalize } from '@angular-devkit/core'; import { join, normalize } from '@angular-devkit/core';
import { import {
ProjectGraph, ProjectGraph,
ProjectGraphNode ProjectGraphNode,
} from '@nrwl/workspace/src/core/project-graph'; } from '@nrwl/workspace/src/core/project-graph';
import { rulesNodeJSSha, rulesNodeJSVersion } from '../utils/versions'; import { rulesNodeJSSha, rulesNodeJSVersion } from '../utils/versions';
import { TargetDefinition } from '@angular-devkit/core/src/workspace'; import { TargetDefinition } from '@angular-devkit/core/src/workspace';
@ -30,7 +30,7 @@ const buildBuilders = {
'@angular-devkit/build-angular:server': 'outputPath', '@angular-devkit/build-angular:server': 'outputPath',
'@angular-devkit/build-angular:ng-packagr': 'outputPath', '@angular-devkit/build-angular:ng-packagr': 'outputPath',
'@angular-devkit/build-webpack:webpack': 'outputPath', '@angular-devkit/build-webpack:webpack': 'outputPath',
'@nrwl/web:build': 'outputPath' '@nrwl/web:build': 'outputPath',
}; };
const testBuilders = new Set([ const testBuilders = new Set([
@ -39,7 +39,7 @@ const testBuilders = new Set([
'@angular-devkit/build-angular:tslint', '@angular-devkit/build-angular:tslint',
'@nrwl/jest:jest', '@nrwl/jest:jest',
'@nrwl/cypress:cypress', '@nrwl/cypress:cypress',
'@nrwl/linter:lint' '@nrwl/linter:lint',
]); ]);
function createBuildFile( function createBuildFile(
@ -58,8 +58,8 @@ function createBuildFile(
outputArgument: string; outputArgument: string;
}[] = []; }[] = [];
labelsMetadata labelsMetadata
.map(metadata => .map((metadata) =>
metadata.configurations.map(config => { metadata.configurations.map((config) => {
const isTestTarget = testBuilders.has(metadata.target.builder); const isTestTarget = testBuilders.has(metadata.target.builder);
const isBuildTarget = !!buildBuilders[metadata.target.builder]; const isBuildTarget = !!buildBuilders[metadata.target.builder];
const outputArgument = buildBuilders[metadata.target.builder]; const outputArgument = buildBuilders[metadata.target.builder];
@ -72,12 +72,12 @@ function createBuildFile(
config === '__nx_default__' ? '' : `__${config}` config === '__nx_default__' ? '' : `__${config}`
}`, }`,
isBuildTarget, isBuildTarget,
outputArgument outputArgument,
}; };
}) })
) )
.forEach(arr => { .forEach((arr) => {
arr.forEach(label => labels.push(label)); arr.forEach((label) => labels.push(label));
}); });
return apply(url('./files/build-file'), [ return apply(url('./files/build-file'), [
@ -87,14 +87,14 @@ function createBuildFile(
projectGraph, projectGraph,
dependencies: projectGraph.dependencies[project.name] dependencies: projectGraph.dependencies[project.name]
? projectGraph.dependencies[project.name].map( ? projectGraph.dependencies[project.name].map(
dep => (dep) =>
`//${normalize(projectGraph.nodes[dep.target].data.root)}:${ `//${normalize(projectGraph.nodes[dep.target].data.root)}:${
dep.target dep.target
}` }`
) )
: [], : [],
labels labels,
}) }),
]); ]);
} }
@ -111,15 +111,15 @@ function updateBuildFile(
target, target,
configurations: [ configurations: [
'__nx_default__', '__nx_default__',
...Object.keys(target.configurations || {}) ...Object.keys(target.configurations || {}),
] ],
})); }));
const buildFile = createBuildFile(project, projectGraph, labelsMetadata); const buildFile = createBuildFile(project, projectGraph, labelsMetadata);
const buildFilePath = join(normalize(project.data.root), 'BUILD.bazel'); const buildFilePath = join(normalize(project.data.root), 'BUILD.bazel');
return mergeWith( return mergeWith(
apply(buildFile, [ apply(buildFile, [
sourceHost => { (sourceHost) => {
if (host.exists(buildFilePath)) { if (host.exists(buildFilePath)) {
const contents = sourceHost.read('BUILD.bazel').toString(); const contents = sourceHost.read('BUILD.bazel').toString();
const customPart = host const customPart = host
@ -130,7 +130,7 @@ function updateBuildFile(
sourceHost.overwrite('BUILD.bazel', customPart + contents); sourceHost.overwrite('BUILD.bazel', customPart + contents);
} }
}, },
move(project.data.root) move(project.data.root),
]), ]),
MergeStrategy.Overwrite MergeStrategy.Overwrite
); );
@ -138,20 +138,20 @@ function updateBuildFile(
} }
function createWorkspaceFile() { function createWorkspaceFile() {
return host => { return (host) => {
return mergeWith( return mergeWith(
apply(url('./files/workspace-file'), [ apply(url('./files/workspace-file'), [
template({ template({
tmpl: '', tmpl: '',
name: readJsonInTree(host, '/package.json').name.replace('-', '_'), name: readJsonInTree(host, '/package.json').name.replace('-', '_'),
rulesNodeJSVersion, rulesNodeJSVersion,
rulesNodeJSSha rulesNodeJSSha,
}), }),
() => { () => {
if (host.exists('WORKSPACE')) { if (host.exists('WORKSPACE')) {
host.delete('WORKSPACE'); host.delete('WORKSPACE');
} }
} },
]), ]),
MergeStrategy.Overwrite MergeStrategy.Overwrite
); );
@ -161,20 +161,20 @@ function createWorkspaceFile() {
const ignoredFromRootBuildFile = ['WORKSPACE', '.bazelrc', 'BUILD.bazel']; const ignoredFromRootBuildFile = ['WORKSPACE', '.bazelrc', 'BUILD.bazel'];
function createRootBuildFile() { function createRootBuildFile() {
return host => { return (host) => {
return mergeWith( return mergeWith(
apply(url('./files/root-build-file'), [ apply(url('./files/root-build-file'), [
template({ template({
tmpl: '', tmpl: '',
rootFiles: host rootFiles: host
.getDir('/') .getDir('/')
.subfiles.filter(f => !ignoredFromRootBuildFile.includes(f)) .subfiles.filter((f) => !ignoredFromRootBuildFile.includes(f)),
}), }),
() => { () => {
if (host.exists('BUILD.bazel')) { if (host.exists('BUILD.bazel')) {
host.delete('BUILD.bazel'); host.delete('BUILD.bazel');
} }
} },
]), ]),
MergeStrategy.Overwrite MergeStrategy.Overwrite
); );
@ -191,9 +191,9 @@ export default (): Rule => {
runInit, runInit,
createWorkspaceFile(), createWorkspaceFile(),
createRootBuildFile(), createRootBuildFile(),
...Object.values(projectGraph.nodes).map(project => ...Object.values(projectGraph.nodes).map((project) =>
updateBuildFile(project, projectGraph) updateBuildFile(project, projectGraph)
) ),
]); ]);
}; };
}; };

View File

@ -24,12 +24,12 @@ export function initGlobal() {
title: `The current directory isn't part of an Nx workspace.`, title: `The current directory isn't part of an Nx workspace.`,
bodyLines: [ bodyLines: [
`To create a workspace run:`, `To create a workspace run:`,
chalk.bold.white(`npx create-nx-workspace@latest <workspace name>`) chalk.bold.white(`npx create-nx-workspace@latest <workspace name>`),
] ],
}); });
output.note({ output.note({
title: `For more information please visit https://nx.dev/` title: `For more information please visit https://nx.dev/`,
}); });
process.exit(0); process.exit(0);
} }

View File

@ -55,7 +55,7 @@ class CLIOutput {
* implementation. * implementation.
*/ */
colors = { colors = {
gray: chalk.gray gray: chalk.gray,
}; };
bold = chalk.bold; bold = chalk.bold;
underline = chalk.underline; underline = chalk.underline;
@ -66,7 +66,7 @@ class CLIOutput {
private writeOutputTitle({ private writeOutputTitle({
label, label,
title title,
}: { }: {
label?: string; label?: string;
title: string; title: string;
@ -85,7 +85,7 @@ class CLIOutput {
return; return;
} }
this.addNewline(); this.addNewline();
bodyLines.forEach(bodyLine => this.writeToStdOut(' ' + bodyLine + '\n')); bodyLines.forEach((bodyLine) => this.writeToStdOut(' ' + bodyLine + '\n'));
} }
addNewline() { addNewline() {
@ -101,7 +101,7 @@ class CLIOutput {
this.writeOutputTitle({ this.writeOutputTitle({
label: chalk.reset.inverse.bold.red(' ERROR '), label: chalk.reset.inverse.bold.red(' ERROR '),
title: chalk.bold.red(title) title: chalk.bold.red(title),
}); });
this.writeOptionalOutputBody(bodyLines); this.writeOptionalOutputBody(bodyLines);
@ -127,7 +127,7 @@ class CLIOutput {
this.writeOutputTitle({ this.writeOutputTitle({
label: chalk.reset.inverse.bold.yellow(' WARNING '), label: chalk.reset.inverse.bold.yellow(' WARNING '),
title: chalk.bold.yellow(title) title: chalk.bold.yellow(title),
}); });
this.writeOptionalOutputBody(bodyLines); this.writeOptionalOutputBody(bodyLines);
@ -153,7 +153,7 @@ class CLIOutput {
this.writeOutputTitle({ this.writeOutputTitle({
label: chalk.reset.inverse.bold.keyword('orange')(' NOTE '), label: chalk.reset.inverse.bold.keyword('orange')(' NOTE '),
title: chalk.bold.keyword('orange')(title) title: chalk.bold.keyword('orange')(title),
}); });
this.writeOptionalOutputBody(bodyLines); this.writeOptionalOutputBody(bodyLines);
@ -166,7 +166,7 @@ class CLIOutput {
this.writeOutputTitle({ this.writeOutputTitle({
label: chalk.reset.inverse.bold.green(' SUCCESS '), label: chalk.reset.inverse.bold.green(' SUCCESS '),
title: chalk.bold.green(title) title: chalk.bold.green(title),
}); });
this.addNewline(); this.addNewline();
@ -176,7 +176,7 @@ class CLIOutput {
this.addNewline(); this.addNewline();
this.writeOutputTitle({ this.writeOutputTitle({
title: message title: message,
}); });
this.addNewline(); this.addNewline();
@ -186,7 +186,7 @@ class CLIOutput {
this.addNewline(); this.addNewline();
this.writeOutputTitle({ this.writeOutputTitle({
title: chalk.white(title) title: chalk.white(title),
}); });
this.writeOptionalOutputBody(bodyLines); this.writeOptionalOutputBody(bodyLines);

View File

@ -10,7 +10,7 @@ describe('parseRunOneOptions', () => {
project: 'myproj', project: 'myproj',
target: 'build', target: 'build',
configuration: 'production', configuration: 'production',
overrides: { flag: 'true' } overrides: { flag: 'true' },
}); });
}); });
@ -19,13 +19,13 @@ describe('parseRunOneOptions', () => {
parseRunOneOptions(nxJson, workspaceJson, [ parseRunOneOptions(nxJson, workspaceJson, [
'run', 'run',
'myproj:build:production', 'myproj:build:production',
'--flag=true' '--flag=true',
]) ])
).toEqual({ ).toEqual({
project: 'myproj', project: 'myproj',
target: 'build', target: 'build',
configuration: 'production', configuration: 'production',
overrides: { flag: 'true' } overrides: { flag: 'true' },
}); });
}); });
@ -39,7 +39,7 @@ describe('parseRunOneOptions', () => {
).toEqual({ ).toEqual({
project: 'myproj', project: 'myproj',
target: 'build', target: 'build',
overrides: { flag: 'true' } overrides: { flag: 'true' },
}); });
}); });

Some files were not shown because too many files have changed in this diff Show More