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',
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',
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: [
@ -28,13 +28,13 @@ module.exports = {
{ name: 'storybook', description: 'anything Storybook specific' },
{
name: 'testing',
description: 'anything testing specific (e.g., jest or cypress)'
description: 'anything testing specific (e.g., jest or cypress)',
},
{
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,
@ -66,7 +66,7 @@ module.exports = {
breaking: 'List any BREAKING CHANGES (optional):\n',
footer:
'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,
@ -75,7 +75,7 @@ module.exports = {
skipQuestions: ['ticketNumber'],
// limit subject length
subjectLimit: 100
subjectLimit: 100,
// breaklineChar: '|', // It is supported for fields body and footer.
// footerPrefix : 'ISSUES CLOSED:'
// 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
return {
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 client side
return this.backend.updateTodo(action.todo.id, action.todo).pipe(
map(updated => ({
map((updated) => ({
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 can dispatch an error, or simply log the error here and return `null`
return null;
}
},
})
)
);
@ -93,9 +93,9 @@ class TodoEffects {
// provides an action
run: (a: GetTodos) => {
return this.backend.getAll().pipe(
map(response => ({
map((response) => ({
type: 'TODOS',
todos: response.todos
todos: response.todos,
}))
);
},
@ -103,7 +103,7 @@ class TodoEffects {
onError: (action: GetTodos, error: any) => {
// dispatch an undo action to undo the changes in the client state
return null;
}
},
})
)
);
@ -130,16 +130,16 @@ class TodoEffects {
// provides an action
run: (todo: GetTodo) => {
return this.backend.getTodo(todo.id).map(response => ({
return this.backend.getTodo(todo.id).map((response) => ({
type: 'LOAD_TODO_SUCCESS',
todo: response.todo
todo: response.todo,
}));
},
onError: (action: GetTodo, error: any) => {
// dispatch an undo action to undo the changes in the client state
return null;
}
},
})
)
);
@ -170,9 +170,9 @@ class TodoEffects {
return this.backend
.fetchTodo(activatedRouteSnapshot.params['id'])
.pipe(
map(todo => ({
map((todo) => ({
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 also navigate back
return null;
}
},
})
)
);

View File

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

View File

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

View File

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

View File

@ -20,9 +20,9 @@ describe('TodoApps', () => {
beforeEach(() => cy.visit('/'));
it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2));
getTodos().should((t) => expect(t.length).equal(2));
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({
selector: 'myorg-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
styleUrls: ['./app.component.css'],
})
export class AppComponent {
todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];
@ -53,14 +53,14 @@ interface Todo {
@Component({
selector: 'myorg-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
styleUrls: ['./app.component.css'],
})
export class AppComponent {
todos: Todo[] = [{ title: 'Todo 1' }, { title: 'Todo 2' }];
addTodo() {
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],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
bootstrap: [AppComponent],
})
export class AppModule {}
```
@ -33,7 +33,7 @@ interface Todo {
@Component({
selector: 'myorg-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
styleUrls: ['./app.component.css'],
})
export class AppComponent {
todos: Todo[] = [];
@ -43,7 +43,7 @@ export class AppComponent {
}
fetch() {
this.http.get<Todo[]>('/api/todos').subscribe(t => (this.todos = t));
this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
}
addTodo() {

View File

@ -122,7 +122,7 @@ import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService]
providers: [AppService],
})
export class AppModule {}
```
@ -150,7 +150,7 @@ export class AppService {
addTodo() {
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() {
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({
selector: 'myorg-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
styleUrls: ['./app.component.css'],
})
export class AppComponent {
todos: Todo[] = [];
@ -93,7 +93,7 @@ export class AppComponent {
}
fetch() {
this.http.get<Todo[]>('/api/todos').subscribe(t => (this.todos = t));
this.http.get<Todo[]>('/api/todos').subscribe((t) => (this.todos = t));
}
addTodo() {

View File

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

View File

@ -20,9 +20,9 @@ describe('TodoApps', () => {
beforeEach(() => cy.visit('/'));
it('should display todos', () => {
getTodos().should(t => expect(t.length).equal(2));
getTodos().should((t) => expect(t.length).equal(2));
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 = () => {
const [todos, setTodos] = useState<Todo[]>([
{ title: 'Todo 1' },
{ title: 'Todo 2' }
{ title: 'Todo 2' },
]);
return (
<>
<h1>Todos</h1>
<ul>
{todos.map(t => (
{todos.map((t) => (
<li className={'todo'}>{t.title}</li>
))}
</ul>
@ -54,15 +54,15 @@ interface Todo {
export const App = () => {
const [todos, setTodos] = useState<Todo[]>([
{ title: 'Todo 1' },
{ title: 'Todo 2' }
{ title: 'Todo 2' },
]);
function addTodo() {
setTodos([
...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>
<ul>
{todos.map(t => (
{todos.map((t) => (
<li className={'todo'}>{t.title}</li>
))}
</ul>

View File

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

View File

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

View File

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

View File

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

View File

@ -139,7 +139,7 @@ console.log(
JSON.stringify({
...commands('lint'),
...commands('test'),
...commands('build')
...commands('build'),
})
);
@ -148,7 +148,7 @@ function commands(target) {
execSync(`npx nx print-affected --base=${baseSha} --target=${target}`)
.toString()
.trim()
).tasks.map(t => t.target.project);
).tasks.map((t) => t.target.project);
array.sort(() => 0.5 - Math.random());
const third = Math.floor(array.length / 3);
@ -158,7 +158,7 @@ function commands(target) {
return {
[target + '1']: a1,
[target + '2']: a2,
[target + '3']: a3
[target + '3']: a3,
};
}
```
@ -221,7 +221,7 @@ execSync(
','
)} --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:
```typescript
it('should create my-plugin', async done => {
it('should create my-plugin', async (done) => {
const plugin = uniq('my-plugin');
ensureNxProject('@my-org/my-plugin', 'dist/libs/my-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 {
return chain([
externalSchematic('@nrwl/workspace', 'lib', {
name: schema.name
})
name: schema.name,
}),
]);
}
```
@ -112,13 +112,13 @@ import {
SchematicContext,
Tree,
url,
externalSchematic
externalSchematic,
} from '@angular-devkit/schematics';
import { getProjectConfig } from '@nrwl/workspace';
function generateLibrary(schema: any): Rule {
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');
const templateSource = apply(url('./files'), [
move(getProjectConfig(tree, schema.name).root)
move(getProjectConfig(tree, schema.name).root),
]);
return chain([mergeWith(templateSource)])(tree, context);
@ -197,8 +197,8 @@ export default function(schema: SchematicOptions): Rule {
return chain([
externalSchematic('@nrwl/workspace', 'lib', {
name: `${schema.name}-${schema.type || ''}`,
unitTestRunner: 'none'
})
unitTestRunner: 'none',
}),
]);
}
```

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,12 +5,12 @@ import {
uniq,
forEachCli,
supportUi,
patchKarmaToWorkOnWSL
patchKarmaToWorkOnWSL,
} from './utils';
forEachCli(() => {
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();
const mylib = uniq('mylib');
@ -19,7 +19,7 @@ forEachCli(() => {
await Promise.all([
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}`);
@ -27,7 +27,7 @@ forEachCli(() => {
done();
}, 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();
const myapp = uniq('myapp');
runCLI(`generate @nrwl/angular:app ${myapp} --unit-test-runner karma`);
@ -35,7 +35,7 @@ forEachCli(() => {
await Promise.all([
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}`);
expect(karmaResult.stdout).toContain('5 SUCCESS');

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,10 +5,10 @@ import {
readJson,
runCLI,
uniq,
updateFile
updateFile,
} from './utils';
forEachCli('nx', cli => {
forEachCli('nx', (cli) => {
describe('Build React libraries and apps', () => {
/**
* Graph:
@ -50,7 +50,7 @@ forEachCli('nx', cli => {
updateFile(
`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
updateFile('tsconfig.json', c => {
updateFile('tsconfig.json', (c) => {
const json = JSON.parse(c);
json.compilerOptions.paths = {};
return JSON.stringify(json, null, 2);
@ -112,7 +112,7 @@ forEachCli('nx', cli => {
const jsonFile = readJson(`dist/libs/${parentLib}/package.json`);
expect(jsonFile.dependencies).toEqual({
[`@proj/${childLib}`]: '0.0.1',
[`@proj/${childLib2}`]: '0.0.1'
[`@proj/${childLib2}`]: '0.0.1',
});
});

View File

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

View File

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

View File

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

View File

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

View File

@ -8,10 +8,10 @@ import {
runCLIAsync,
supportUi,
uniq,
updateFile
updateFile,
} from './utils';
forEachCli(currentCLIName => {
forEachCli((currentCLIName) => {
describe('Web Components Applications', () => {
it('should be able to generate a web app', async () => {
ensureProject();
@ -137,7 +137,7 @@ forEachCli(currentCLIName => {
updateFile(main, `${newCode}\n${content}`);
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(
'var envVars = ["test", "52", "QA"];'

View File

@ -14,10 +14,10 @@ import {
tmpProjPath,
uniq,
updateFile,
workspaceConfigName
workspaceConfigName,
} from './utils';
forEachCli(cli => {
forEachCli((cli) => {
describe('lint', () => {
it('lint should ensure module boundaries', () => {
ensureProject();
@ -39,7 +39,7 @@ forEachCli(cli => {
const tslint = readJson('tslint.json');
tslint.rules['nx-enforce-module-boundaries'][1].depConstraints = [
{ 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));
@ -178,11 +178,11 @@ forEachCli(cli => {
const json = readJson(`tools/schematics/${custom}/schema.json`);
json.properties['directory'] = {
type: 'string',
description: 'lib directory'
description: 'lib directory',
};
json.properties['skipTsConfig'] = {
type: 'boolean',
description: 'skip changes to tsconfig'
description: 'skip changes to tsconfig',
};
updateFile(
`tools/schematics/${custom}/schema.json`,
@ -299,47 +299,47 @@ forEachCli(cli => {
{
source: 'myapp3-e2e',
target: 'myapp3',
type: 'implicit'
}
type: 'implicit',
},
],
myapp2: [
{
source: 'myapp2',
target: 'mylib',
type: 'static'
}
type: 'static',
},
],
'myapp2-e2e': [
{
source: 'myapp2-e2e',
target: 'myapp2',
type: 'implicit'
}
type: 'implicit',
},
],
mylib: [
{
source: 'mylib',
target: 'mylib2',
type: 'static'
}
type: 'static',
},
],
mylib2: [],
myapp: [
{
source: 'myapp',
target: 'mylib',
type: 'static'
type: 'static',
},
{ source: 'myapp', target: 'mylib2', type: 'dynamic' }
{ source: 'myapp', target: 'mylib2', type: 'dynamic' },
],
'myapp-e2e': [
{
source: 'myapp-e2e',
target: 'myapp',
type: 'implicit'
}
type: 'implicit',
},
],
myapp3: []
myapp3: [],
});
runCommand(
@ -592,7 +592,7 @@ forEachCli(cli => {
const nxJson = JSON.parse(readFile('nx.json')) as NxJson;
expect(nxJson.projects[`${lib1}-data-access`]).toBeUndefined();
expect(nxJson.projects[newName]).toEqual({
tags: []
tags: [],
});
expect(moveOutput).toContain('UPDATE tsconfig.json');
@ -613,7 +613,7 @@ forEachCli(cli => {
expect(project.sourceRoot).toBe(`${newPath}/src`);
expect(project.architect.lint.options.tsConfig).toEqual([
`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,
uniq,
updateFile,
workspaceConfigName
workspaceConfigName,
} from './utils';
let originalCIValue: any;
forEachCli(cliName => {
forEachCli((cliName) => {
const cliCommand = cliName === 'angular' ? 'ng' : 'nx';
/**
@ -269,8 +269,8 @@ forEachCli(cliName => {
results: {
[myapp]: false,
[mylib]: true,
[mypublishablelib]: true
}
[mypublishablelib]: true,
},
});
// Fix failing Unit Test
@ -429,11 +429,11 @@ forEachCli(cliName => {
overrides: {},
target: {
project: myapp,
target: 'test'
target: 'test',
},
command: `npm run ${cliCommand} -- test ${myapp}`,
outputs: []
}
outputs: [],
},
]);
compareTwoArrays(resWithTarget.projects, [`${myapp}-e2e`, myapp]);
@ -448,27 +448,27 @@ forEachCli(cliName => {
overrides: {},
target: {
project: mypublishablelib,
target: 'build'
target: 'build',
},
command: `npm run ${cliCommand} -- build ${mypublishablelib}`,
outputs: [`dist/libs/${mypublishablelib}`]
outputs: [`dist/libs/${mypublishablelib}`],
},
{
id: `${myapp}:build`,
overrides: {},
target: {
project: myapp,
target: 'build'
target: 'build',
},
command: `npm run ${cliCommand} -- build ${myapp}`,
outputs: [`dist/apps/${myapp}`]
}
outputs: [`dist/apps/${myapp}`],
},
]);
compareTwoArrays(resWithDeps.projects, [
mylib,
mypublishablelib,
myapp,
`${myapp}-e2e`
`${myapp}-e2e`,
]);
const resWithTargetWithSelect1 = runCommand(
@ -487,8 +487,8 @@ forEachCli(cliName => {
function compareTwoSerializedArrays(a: string, b: string) {
compareTwoArrays(
a.split(',').map(_ => _.trim()),
b.split(',').map(_ => _.trim())
a.split(',').map((_) => _.trim()),
b.split(',').map((_) => _.trim())
);
}
@ -543,7 +543,7 @@ forEachCli(cliName => {
// touch myapp1
// --------------------------------------------
updateFile(`apps/${myapp1}/src/main.ts`, c => {
updateFile(`apps/${myapp1}/src/main.ts`, (c) => {
return `${c}\n//some comment`;
});
const outputWithBuildApp2Cached = runCommand(
@ -554,7 +554,7 @@ forEachCli(cliName => {
// touch package.json
// --------------------------------------------
updateFile(`package.json`, c => {
updateFile(`package.json`, (c) => {
const r = JSON.parse(c);
r.description = 'different';
return JSON.stringify(r);
@ -597,7 +597,7 @@ forEachCli(cliName => {
myapp1,
myapp2,
`${myapp1}-e2e`,
`${myapp2}-e2e`
`${myapp2}-e2e`,
]);
// run without caching
@ -605,14 +605,14 @@ forEachCli(cliName => {
// disable caching
// --------------------------------------------
updateFile('nx.json', c => {
updateFile('nx.json', (c) => {
const nxJson = JSON.parse(c);
nxJson.tasksRunnerOptions = {
default: {
options: {
cacheableOperations: []
}
}
cacheableOperations: [],
},
},
};
return JSON.stringify(nxJson, null, 2);
});

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ import { readAll, readFirst } from '../testing/src/testing-utils';
describe('TestingUtils', () => {
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 result = await readAll(obs);
@ -14,7 +14,7 @@ describe('TestingUtils', () => {
});
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 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 {
ProjectGraph,
ProjectType
ProjectType,
} from '@nrwl/workspace/src/core/project-graph';
import * as fileUtils from '@nrwl/workspace/src/utils/fileutils';
@ -48,21 +48,21 @@ describe('AngularLibraryWebBuildBuilder', () => {
return {
options: {
paths: {
'@proj/buildable-child': []
}
}
'@proj/buildable-child': [],
},
},
};
});
spyOn(fileUtils, 'fileExists').and.returnValue(true);
context.target = {
project: 'buildable-parent',
target: 'build'
target: 'build',
};
testOptions = {
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': {
type: ProjectType.lib,
name: 'buildable-parent',
data: { files: [], root: 'libs/buildable-parent' }
}
data: { files: [], root: 'libs/buildable-parent' },
},
dependencies: {}
},
dependencies: {},
} as ProjectGraph;
});
@ -101,10 +101,10 @@ describe('AngularLibraryWebBuildBuilder', () => {
root: 'libs/buildable-parent',
architect: {
build: {
builder: 'any builder'
}
}
}
builder: 'any builder',
},
},
},
},
'buildable-child': {
type: ProjectType.lib,
@ -115,22 +115,22 @@ describe('AngularLibraryWebBuildBuilder', () => {
prefix: 'proj',
architect: {
build: {
builder: 'any builder'
}
}
}
}
builder: 'any builder',
},
},
},
},
},
dependencies: {
'buildable-parent': [
{
type: ProjectType.lib,
target: 'buildable-child',
source: null
}
source: null,
},
],
'buildable-child': []
}
'buildable-child': [],
},
} as ProjectGraph;
});
});
@ -138,7 +138,7 @@ describe('AngularLibraryWebBuildBuilder', () => {
it('should properly set the TSConfig paths', async () => {
spyOn(fileUtils, 'readJsonFile').and.returnValue({
name: '@proj/buildable-child',
version: '1.2.3'
version: '1.2.3',
});
// act
@ -149,8 +149,8 @@ describe('AngularLibraryWebBuildBuilder', () => {
expect(ngPackagrMock.withTsConfig).toHaveBeenCalledWith(
jasmine.objectContaining({
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')) {
return {
name: '@proj/buildable-parent',
version: '3.3.3'
version: '3.3.3',
};
} else {
return {
name: '@proj/buildable-child',
version: '1.2.3'
version: '1.2.3',
};
}
});
@ -179,8 +179,8 @@ describe('AngularLibraryWebBuildBuilder', () => {
'dist/libs/buildable-parent/package.json',
jasmine.objectContaining({
dependencies: {
'@proj/buildable-child': '1.2.3'
}
'@proj/buildable-child': '1.2.3',
},
})
);
});
@ -194,13 +194,13 @@ describe('AngularLibraryWebBuildBuilder', () => {
name: '@proj/buildable-parent',
version: '1.2.3',
[depConfigName]: {
'@proj/buildable-child': '1.1.1'
}
'@proj/buildable-child': '1.1.1',
},
};
} else {
return {
name: '@proj/buildable-child',
version: '1.2.3'
version: '1.2.3',
};
}
});

View File

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

View File

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

View File

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

View File

@ -5,14 +5,14 @@ import {
formatFiles,
updateJsonInTree,
checkAndCleanWithSemver,
addInstallTask
addInstallTask,
} from '@nrwl/workspace';
import { gt } from 'semver';
function updateCLI() {
const tasks: TaskId[] = [];
const rule = chain([
updateJsonInTree('package.json', json => {
updateJsonInTree('package.json', (json) => {
json.devDependencies = json.devDependencies || {};
const cliVersion = json.devDependencies['@angular/cli'];
const cleanCliVersion = checkAndCleanWithSemver(
@ -39,7 +39,7 @@ function updateCLI() {
return json;
}),
addInstallTask()
addInstallTask(),
]);
return { rule, tasks };
@ -52,7 +52,7 @@ function updateNgrx(updateDeps: TaskId[]) {
if (dependencies && dependencies['@ngrx/store']) {
return chain([
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 {
SchematicTestRunner,
UnitTestTree
UnitTestTree,
} from '@angular-devkit/schematics/testing';
import { serializeJson } from '@nrwl/workspace';
import { runMigration } from '../../utils/testing';
@ -21,8 +21,8 @@ describe('Update 8.5.0', () => {
'package.json',
serializeJson({
devDependencies: {
'@angular/cli': '8.0.0'
}
'@angular/cli': '8.0.0',
},
})
);
@ -38,8 +38,8 @@ describe('Update 8.5.0', () => {
'package.json',
serializeJson({
devDependencies: {
'@angular/cli': '^8.0.0'
}
'@angular/cli': '^8.0.0',
},
})
);
@ -55,8 +55,8 @@ describe('Update 8.5.0', () => {
'package.json',
serializeJson({
devDependencies: {
'@angular/cli': '~8.0.0'
}
'@angular/cli': '~8.0.0',
},
})
);
@ -74,8 +74,8 @@ describe('Update 8.5.0', () => {
'package.json',
serializeJson({
devDependencies: {
'@angular/cli': '>=8.0.0'
}
'@angular/cli': '>=8.0.0',
},
})
);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@ import { insert } from '@nrwl/workspace';
import { RequestContext } from './request-context';
import {
addImportToModule,
addProviderToModule
addProviderToModule,
} from '../../../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),
...(hasRouter
? addImportToModule(source, modulePath, storeRouterModule)
: [])
: []),
]);
} else {
let common = [
addImport.apply(this, storeModule),
addImport.apply(this, effectsModule),
addImport(reducerImports, reducerPath, true),
addImport(effectsName, effectsPath)
addImport(effectsName, effectsPath),
];
if (context.options.facade) {
common = [
...common,
addImport(facadeName, facadePath),
...addProviderToModule(source, modulePath, `${facadeName}`)
...addProviderToModule(source, modulePath, `${facadeName}`),
];
}
@ -118,13 +118,13 @@ export function addImportsToModule(context: RequestContext): Rule {
...(hasRouter
? addImportToModule(source, modulePath, storeRouterModule)
: []),
...addImportToModule(source, modulePath, storeForFeature)
...addImportToModule(source, modulePath, storeForFeature),
]);
} else {
insert(host, modulePath, [
...common,
...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/effects': ngrxVersion,
'@ngrx/entity': ngrxVersion,
'@ngrx/router-store': ngrxVersion
'@ngrx/router-store': ngrxVersion,
},
{
'@ngrx/schematics': ngrxVersion,
'@ngrx/store-devtools': ngrxVersion
'@ngrx/store-devtools': ngrxVersion,
}
);
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,10 +1,10 @@
export const enum UnitTestRunner {
Karma = 'karma',
Jest = 'jest',
None = 'none'
None = 'none',
}
export const enum E2eTestRunner {
Protractor = 'protractor',
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 {
createEmptyWorkspace,
MockBuilderContext
MockBuilderContext,
} from '@nrwl/workspace/testing';
import { TestingArchitectHost } from '@angular-devkit/architect/testing';
import { schema } from '@angular-devkit/core';
@ -82,7 +82,7 @@ export function createApp(
// save for getAppDir() lookup by external *.spec.ts tests
appConfig = {
appName,
appModule: `/apps/${appName}/src/app/app.module.ts`
appModule: `/apps/${appName}/src/app/app.module.ts`,
};
tree.create(
@ -121,13 +121,13 @@ export function createApp(
tree.create(
`/apps/${appName}/tsconfig.app.json`,
JSON.stringify({
include: ['**/*.ts']
include: ['**/*.ts'],
})
);
tree.create(
`/apps/${appName}-e2e/tsconfig.e2e.json`,
JSON.stringify({
include: ['../**/*.ts']
include: ['../**/*.ts'],
})
);
tree.overwrite(
@ -142,15 +142,15 @@ export function createApp(
architect: {
build: {
options: {
main: `apps/${appName}/src/main.ts`
}
main: `apps/${appName}/src/main.ts`,
},
},
serve: {
options: {}
}
}
}
}
options: {},
},
},
},
},
})
);
return tree;
@ -162,7 +162,7 @@ export function createLib(tree: Tree, libName: string): Tree {
libConfig = {
name,
module: `/libs/${propertyName}/src/lib/${fileName}.module.ts`,
barrel: `/libs/${propertyName}/src/index.ts`
barrel: `/libs/${propertyName}/src/index.ts`,
};
tree.create(

View File

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

View File

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

View File

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

View File

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

View File

@ -24,12 +24,12 @@ export function initGlobal() {
title: `The current directory isn't part of an Nx workspace.`,
bodyLines: [
`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({
title: `For more information please visit https://nx.dev/`
title: `For more information please visit https://nx.dev/`,
});
process.exit(0);
}

View File

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

View File

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

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