Giter Club home page Giter Club logo

devkit's Introduction

This repository has been moved to Angular CLI repo

You can find the CLI repo here.

devkit's People

Contributors

alan-agius4 avatar alexeagle avatar alxhub avatar amitport avatar beeman avatar brocco avatar caroso1222 avatar cexbrayat avatar chrste90 avatar clydin avatar cyrilletuzi avatar delasteve avatar dherges avatar filipesilva avatar frozenpandaz avatar hansl avatar jialipassion avatar jlhwung avatar jschwarty avatar kara avatar lacolaco avatar markgoho avatar nlm-pro avatar rkirov avatar sis0k0 avatar teamop avatar theefer avatar vikerman avatar webmaxru avatar wkoza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

devkit's Issues

Expose all the internal classes in build-optimizer

Currently the index.ts file doesn't expose enough of the internals of build optimizer. The build-optimizer.ts file has the following imports:

import { TransformJavascriptOutput, transformJavascript } from '../helpers/transform-javascript';
import { getFoldFileTransformer } from '../transforms/class-fold';
import { getImportTslibTransformer, testImportTslib } from '../transforms/import-tslib';
import { getPrefixClassesTransformer, testPrefixClasses } from '../transforms/prefix-classes';
import { getPrefixFunctionsTransformer } from '../transforms/prefix-functions';
import { getScrubFileTransformer, testScrubFile } from '../transforms/scrub-file';
import { getWrapEnumsTransformer, testWrapEnums } from '../transforms/wrap-enums';

The index.ts file re-exports:

export { transformJavascript } from './helpers/transform-javascript';

export { getFoldFileTransformer } from './transforms/class-fold';
export { getPrefixFunctionsTransformer } from './transforms/prefix-functions';
export { getScrubFileTransformer } from './transforms/scrub-file';
export { getImportTslibTransformer } from './transforms/import-tslib';

I would like to have all the internal transforms re-exported so other projects can import them through @angular-devkit/build-optimizer rather than needing to deep import them.

Offer a schematics API for doing npm/yarn installs

Bug Report or Feature Request (mark with an x)

- [x] feature request

Area

- [x] schematics

I would like to be able to call a function within schematics, and have schematics install via my chosen package manager. This would also allow tools like StackBlitz to override / patch these methods and perform their own package installation / setup.

Collection Extension / Merging

Sometimes you want to reuse schematics from another collection as is. For example, someone could want to implement a collection that is the exact same as the angular one (same schematics), but changes only 1 schematic. All the others should be the same. Or maybe a company wants to have a default collection on their CLI but have that collection include schematics from a number of other collections.

A proper system should allow merging of collections, with some resolution if there's a collusion, and a list of schematics that it implements itself (might be empty). As an example (the schema is just an example):

{
  "$schema": "http://schema.angular.io/schematics/collection/2",
  "name": "my-com",
  "description": "My Company default collection, containing all schematics that are used normally",
  "extends": [
    "@schematics/angular",
    "@my-company/schematics-base",
    "@my-company/schematics-pages"
  ],
  "schematics": {
  }
}

This would include the base angular schematics, the base my-company schematics and the pages schematics. This helps with separating development of each of those, while the end user can just install and use one collection. The schematics are merged, with names being overridden by pages, then base, then angular.

Exported downleveled classes don't get picked up by the pure class transform regex

Source code such as:

export class OuterSubscriber<T, R> extends Subscriber<T> {}

Will get downleveled as:

export var OuterSubscriber = (function (_super) {
    __extends(OuterSubscriber, _super);
    function OuterSubscriber() {
        _super.apply(this, arguments);
    }
    return OuterSubscriber;
}

Our regex testing whether or not to apply the /** __PURE__ */ annotation doesn't take into account the export var prefix on this line.

Developer Documentation

I’m trying to debug and work with schematics in angular/devkit, especially after yesterday's merges, I wasn’t able to find any developer docs for devkit. Just running the builds in package.json is giving me errors. Here's the output from npm run build:

rror: Circular dependency detected between the following packages: rxjs
    at _getHashOf (/Users/splaktar/Git/angular/devkit/lib/packages.ts:37:15)
    at pkg.dependencies.forEach.depName (/Users/splaktar/Git/angular/devkit/lib/packages.ts:29:46)
    at Array.forEach (native)
    at _getHashOf (/Users/splaktar/Git/angular/devkit/lib/packages.ts:28:26)
    at Object.<anonymous> (/Users/splaktar/Git/angular/devkit/lib/packages.ts:155:38)
    at Module._compile (module.js:570:32)
    at Object.require.extensions..ts (/Users/splaktar/Git/angular/devkit/lib/bootstrap-local.js:79:14)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/splaktar/Git/angular/devkit/lib/bootstrap-local.js:99:41)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/splaktar/Git/angular/devkit/bin/devkit-admin:16:1)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:504:3

Do I need to have Bazel installed as well as the npm dependencies?
Are there Bazel build commands that I need to run?

Do I need to be on NPM 5? I'm currently running Node 6.11.0 and NPM 3.10.10.

ngo is removing non-angular decorators

Versions

@angular/cli: 1.3.0-rc.3
node: 8.2.1
os: linux x64
@angular/animations: 4.3.0
@angular/cdk: 2.0.0-beta.8
@angular/common: 4.3.0
@angular/compiler: 4.3.0
@angular/compiler-cli: 4.3.0
@angular/core: 4.3.0
@angular/flex-layout: 2.0.0-beta.8
@angular/forms: 4.3.0
@angular/http: 4.3.0
@angular/material: 2.0.0-beta.8
@angular/platform-browser: 4.3.0
@angular/platform-browser-dynamic: 4.3.0
@angular/router: 4.3.0

Repro steps

  1. Use lodash-decorators or some custom decorators in components.
  2. Build app using ng build --prod --aot --no-sourcemap --build-optimizer.

Observed Behavior

After building app all decorators are removed.

Expected Behavior

Keep non-angular decorators.

No __PURE_ for component

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

node - v7.6.0
npm - 4.1.2
ts - 2.5.3
angular - 4.4.5
devkit - 0.0.27

Repro steps

I have a loader that uses build optimizer:

const BuildOptimizer = require('@angular-devkit/build-optimizer').buildOptimizer;

module.exports = function (source) {
    let result = BuildOptimizer({
        content: source,
        emitSourceMap: true,
    });

    return result.content || source;
};

and a simple component:

import {Component} from '@angular/core';

enum Modes { Option1, Option2 }

@Component({
               selector: 'app-root',
               templateUrl: './app.component.html',
           })
export class AppComponent  {
    title = 'app component!';
    mode: Modes;
}

When built it result in

var __decorate = /*@__PURE__*/ __webpack_require__(0).__decorate;
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = __webpack_require__(2);
var Modes = /*@__PURE__*/ (function () {
    var Modes = {};
    Modes[Modes["Option1"] = 0] = "Option1";
    Modes[Modes["Option2"] = 1] = "Option2";
    return Modes;
})();
var AppComponent = (function () {
    function AppComponent() {
        this.title = 'app component!';
    }
    AppComponent = __decorate([
        core_1.Component({
            selector: 'app-root',
            template: __webpack_require__(47),
        })
    ], AppComponent);
    return AppComponent;
}());
exports.AppComponent = AppComponent;

Repo: https://github.com/WiseBird/ng_devkit_test

Desired functionality

If I understand correctly comopnent class should also be marked as pure: var AppComponent = /*@__PURE__*/ (function () {

ngo is removing console logs

Using:

@angular/cli: 1.3.0-rc.1
node: 8.1.3
os: linux x64
@angular/animations: 4.3.1
@angular/cli: 1.3.0-rc.1
@angular/common: 4.3.1
@angular/compiler: 4.3.1
@angular/compiler-cli: 4.3.1
@angular/core: 4.3.1
@angular/forms: 4.3.1
@angular/http: 4.3.1
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 4.3.1
@angular/platform-browser-dynamic: 4.3.1
@angular/router: 4.3.1
@angular/service-worker: 1.0.0-beta.16

I have console.log("Can anyone hear me?!");; at the top of my app.component.ts file, outside the scope of my component.

Expected Behavior:
When the application runs, the console.log message is printed.

Observed Behavior
The console log is not running

Other Background
In the source code generated with ng build -prod -bo, the import is being marked as pure.

 /*@__PURE__*/
        console.log("Can anyone hear me?!");

Add tests for @schematics/angular

The list of schematics that need tests

  • angular-app
  • class
  • directive
  • enum
  • guard
  • interface
  • module
  • pipe
  • service

This is dependent upon #31 being completed

Optimization fails when webpacks cache options is false

I use an emitted ng-cli config and tried to adapt it to use the build-optimizer.
While testing the build always failed until I found out that the build-optimizer only works when webpacks caching is enabled.

In build-optimizer/src/purify/webpack-plugin.js there's the following lines:

compilation.assets[fileName]._cachedSource = purifiedSource;
compilation.assets[fileName]._source.source = () => purifiedSource;

This code requires "cache: true" to be set in the webpack config as otherwise the assets are ConcatSource objects that don't have "_cachedSource" and "_source" properties resulting in the second line causing an error as "._source" is undefined.

For a fix see PR #135, it's a really simple change with which both caching and non-caching webpack configs are supported.

Purify doesn't work with NgModuleFactory in non-webpack environment

Relates to angular/components#4137 .

Currently purify plugin only supports hard-coded webpack regex in https://github.com/angular/devkit/blob/master/packages/angular_devkit/build_optimizer/src/purify/purify.ts#L52-L60, and it cannot work with any non-webpack tools.

Since it's too obvious I don't think there're any needs for a repo of reproduction.

Example input:

/**
 * @fileoverview This file is generated by the Angular template compiler.
 * Do not edit.
 * @suppress {suspiciousCode,uselessCode,missingProperties,missingOverride}
 */
/* tslint:disable */
import * as i0 from '@angular/core';
import * as i1 from '@angular/material';
import * as i2 from '@angular/cdk';
import * as i3 from '@angular/platform-browser';
import * as i4 from '@angular/common';
import * as i5 from '@angular/forms';
import * as i6 from '@angular/http';
export var MdCoreModuleNgFactory = i0.ɵcmf(i1.MdCoreModule, [], function (_l) {
    return i0.ɵmod([i0.ɵmpd(512, i0.ComponentFactoryResolver, i0.ɵCodegenComponentFactoryResolver, [[8, []], [3, i0.ComponentFactoryResolver], i0.NgModuleRef]), i0.ɵmpd(6144, i2.DIR_DOCUMENT, null, [i3.DOCUMENT]), i0.ɵmpd(4608, i2.Directionality, i2.Directionality, [[2, i2.DIR_DOCUMENT]]), i0.ɵmpd(4608, i2.Platform, i2.Platform, []), i0.ɵmpd(5120, i1.ScrollDispatcher, i1.ɵe, [[3, i1.ScrollDispatcher],
            i0.NgZone, i2.Platform]), i0.ɵmpd(5120, i1.ViewportRuler, i1.ɵc, [[3, i1.ViewportRuler],
            i1.ScrollDispatcher]), i0.ɵmpd(4608, i1.ScrollStrategyOptions, i1.ScrollStrategyOptions, [i1.ScrollDispatcher, i1.ViewportRuler]), i0.ɵmpd(4608, i2.MdMutationObserverFactory, i2.MdMutationObserverFactory, []), i0.ɵmpd(5120, i1.OverlayContainer, i1.ɵa, [[3, i1.OverlayContainer]]), i0.ɵmpd(4608, i1.ɵt, i1.ɵt, [i1.ViewportRuler]),
        i0.ɵmpd(4608, i1.Overlay, i1.Overlay, [i1.ScrollStrategyOptions, i1.OverlayContainer,
            i0.ComponentFactoryResolver, i1.ɵt, i0.ApplicationRef, i0.Injector, i0.NgZone]),
        i0.ɵmpd(4608, i4.NgLocalization, i4.NgLocaleLocalization, [i0.LOCALE_ID]), i0.ɵmpd(4608, i2.InteractivityChecker, i2.InteractivityChecker, [i2.Platform]), i0.ɵmpd(4608, i2.FocusTrapFactory, i2.FocusTrapFactory, [i2.InteractivityChecker, i2.Platform,
            i0.NgZone]), i0.ɵmpd(5120, i2.LiveAnnouncer, i2.LIVE_ANNOUNCER_PROVIDER_FACTORY, [[3, i2.LiveAnnouncer], [2, i2.LIVE_ANNOUNCER_ELEMENT_TOKEN], i2.Platform]),
        i0.ɵmpd(512, i1.CompatibilityModule, i1.CompatibilityModule, []),
        i0.ɵmpd(512, i2.BidiModule, i2.BidiModule, []), i0.ɵmpd(256, i1.MATERIAL_SANITY_CHECKS, true, []), i0.ɵmpd(512, i1.MdCommonModule, i1.MdCommonModule, [[2, i3.DOCUMENT], [2, i1.MATERIAL_SANITY_CHECKS]]), i0.ɵmpd(512, i1.MdLineModule, i1.MdLineModule, []), i0.ɵmpd(512, i2.PlatformModule, i2.PlatformModule, []), i0.ɵmpd(512, i1.ScrollDispatchModule, i1.ScrollDispatchModule, []), i0.ɵmpd(512, i1.MdRippleModule, i1.MdRippleModule, []),
        i0.ɵmpd(512, i2.ObserveContentModule, i2.ObserveContentModule, []),
        i0.ɵmpd(512, i2.PortalModule, i2.PortalModule, []), i0.ɵmpd(512, i1.OverlayModule, i1.OverlayModule, []), i0.ɵmpd(512, i4.CommonModule, i4.CommonModule, []), i0.ɵmpd(512, i2.A11yModule, i2.A11yModule, []),
        i0.ɵmpd(512, i1.MdSelectionModule, i1.MdSelectionModule, []), i0.ɵmpd(512, i1.MdOptionModule, i1.MdOptionModule, []), i0.ɵmpd(512, i1.MdCoreModule, i1.MdCoreModule, [])]);
});

build-optimizer: fails to remove design:paramtypes decorator

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting

Area

- [x] devkit
- [ ] schematics

Versions

Repro steps

app source:

export class GaService {
  // ms to wait before acquiring window.ga after analytics library loads
  // empirically determined to allow time for e2e test setup
  static initializeDelay = 1000;

  private previousUrl: string;
  private ga: (...rest: any[]) => void;

  constructor(private logger: Logger) {
    this.initializeGa();
    this.ga('create', environment['gaId'] , 'auto');
  }

  locationChanged(url: string) {
    this.sendPage(url);
  }

  sendPage(url: string) {
    // Won't re-send if the url hasn't changed.
    if (url === this.previousUrl) { return; }
    this.previousUrl = url;
    this.ga('set', 'page', '/' + url);
    this.ga('send', 'pageview');
  }

  // These gyrations are necessary to make the service e2e testable
  // and to disable ga tracking during e2e tests.
  private initializeGa() {
    const ga = window['ga'];
    if (ga) {
      // Queue commands until GA analytics script has loaded.
      const gaQueue: any[][] = [];
      this.ga = (...rest: any[]) => { gaQueue.push(rest); };

      // Then send queued commands to either real or e2e test ga();
      // after waiting to allow possible e2e test to replace global ga function
      ga(() => setTimeout(() => {
        // this.logger.log('GA fn:', window['ga'].toString());
        this.ga = window['ga'];
        gaQueue.forEach((command) => this.ga.apply(null, command));
      }, GaService.initializeDelay));

    } else {
      // delegate `ga` calls to the logger if no ga installed
      this.ga = (...rest: any[]) => { this.logger.log('ga:', rest); };
    }
  }

}

transpiles to:

var GaService = /** @class */ (function () {
    function GaService(logger) {
        this.logger = logger;
        this.initializeGa();
        this.ga('create', environment['gaId'], 'auto');
    }
    GaService_1 = GaService;
    GaService.prototype.locationChanged = function (url) {
        this.sendPage(url);
    };
    GaService.prototype.sendPage = function (url) {
        // Won't re-send if the url hasn't changed.
        if (url === this.previousUrl) {
            return;
        }
        this.previousUrl = url;
        this.ga('set', 'page', '/' + url);
        this.ga('send', 'pageview');
    };
    // These gyrations are necessary to make the service e2e testable
    // and to disable ga tracking during e2e tests.
    GaService.prototype.initializeGa = function () {
        var _this = this;
        var ga = window['ga'];
        if (ga) {
            // Queue commands until GA analytics script has loaded.
            var gaQueue_1 = [];
            this.ga = function () {
                var rest = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    rest[_i] = arguments[_i];
                }
                gaQueue_1.push(rest);
            };
            // Then send queued commands to either real or e2e test ga();
            // after waiting to allow possible e2e test to replace global ga function
            ga(function () { return setTimeout(function () {
                // this.logger.log('GA fn:', window['ga'].toString());
                _this.ga = window['ga'];
                gaQueue_1.forEach(function (command) { return _this.ga.apply(null, command); });
            }, GaService_1.initializeDelay); });
        }
        else {
            // delegate `ga` calls to the logger if no ga installed
            this.ga = function () {
                var rest = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    rest[_i] = arguments[_i];
                }
                _this.logger.log('ga:', rest);
            };
        }
    };
    // ms to wait before acquiring window.ga after analytics library loads
    // empirically determined to allow time for e2e test setup
    GaService.initializeDelay = 1000;
    GaService = GaService_1 = tslib_1.__decorate([
        Injectable()
        /**
         * Google Analytics Service - captures app behaviors and sends them to Google Analytics (GA).
         * Presupposes that GA script has been loaded from a script on the host web page.
         * Associates data with a GA "property" from the environment (`gaId`).
         */
        ,
        tslib_1.__metadata("design:paramtypes", [Logger])
    ], GaService);
    return GaService;
    var GaService_1;
}());
export { GaService };

after optimization:

var ga_service_GaService = /*@__PURE__*/ function() {
            function GaService(logger) {
                this.logger = logger;
                this.initializeGa();
                this.ga("create", environment.a.gaId, "auto");
            }
            GaService_1 = GaService;
            GaService.prototype.locationChanged = function(url) {
                this.sendPage(url);
            };
            GaService.prototype.sendPage = function(url) {
                // Won't re-send if the url hasn't changed.
                if (url !== this.previousUrl) {
                    this.previousUrl = url;
                    this.ga("set", "page", "/" + url);
                    this.ga("send", "pageview");
                }
            };
            // These gyrations are necessary to make the service e2e testable
            // and to disable ga tracking during e2e tests.
            GaService.prototype.initializeGa = function() {
                var _this = this, ga = window.ga;
                if (ga) {
                    // Queue commands until GA analytics script has loaded.
                    var gaQueue_1 = [];
                    this.ga = function() {
                        for (var rest = [], _i = 0; _i < arguments.length; _i++) rest[_i] = arguments[_i];
                        gaQueue_1.push(rest);
                    };
                    // Then send queued commands to either real or e2e test ga();
                    // after waiting to allow possible e2e test to replace global ga function
                    ga(function() {
                        return setTimeout(function() {
                            // this.logger.log('GA fn:', window['ga'].toString());
                            _this.ga = window.ga;
                            gaQueue_1.forEach(function(command) {
                                return _this.ga.apply(null, command);
                            });
                        }, GaService_1.initializeDelay);
                    });
                } else // delegate `ga` calls to the logger if no ga installed
                this.ga = function() {
                    for (var rest = [], _i = 0; _i < arguments.length; _i++) rest[_i] = arguments[_i];
                    _this.logger.log("ga:", rest);
                };
            };
            // ms to wait before acquiring window.ga after analytics library loads
            // empirically determined to allow time for e2e test setup
            GaService.initializeDelay = 1e3;
            GaService = GaService_1 = __decorate([ Injectable(), __metadata("design:paramtypes", [ logger_service_Logger ]) ], GaService);
            return GaService;
            var GaService_1;
        }()

Mention any other details that might be useful

I think the key difference that causes us to miss this might be the static initializer?

static initializeDelay = 1000;

Versions

Angular CLI: 1.5.0-rc.2
Node: 6.9.5
OS: darwin x64
Angular: 5.0.0-rc.2
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

@angular/cdk: 2.0.0-beta.12
@angular/cli: 1.5.0-rc.2
@angular/material: 2.0.0-beta.12
@angular/service-worker: 1.0.0-beta.16
@angular-devkit/build-optimizer: 0.0.29
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.34
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0-rc.2
@schematics/angular: 0.0.48
typescript: 2.5.3
webpack: 3.7.1

schematics: new schematic template does not compile

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [ ] devkit
- [x] schematics

Versions

macOS Sierra
node v8.6.0
npm v5.3.0
yarn v1.2.0

Repro steps

Generate a new schematic, and try to compile it (maybe I'm doing this wrong):

yarn init
yarn add @angular-devkit/schematics @schematics/schematics
$(yarn bin)/schematics @schematics/schematics:schematic --name ninjasquad
cd ninjasquad
yarn
yarn build

The log given by the failure

yarn run v1.2.0
$ tsc -p tsconfig.json
src/my-full-schematic/index_spec.ts(14,63): error TS2345: Argument of type 'Tree' is not assignable to parameter of type 'Tree | undefined'.
  Type 'Tree' is not assignable to type 'Tree'. Two different types with this name exist, but they are unrelated.
src/my-full-schematic/index_spec.ts(19,80): error TS2345: Argument of type 'Tree' is not assignable to parameter of type 'Tree | undefined'.
  Type 'Tree' is not assignable to type 'Tree'. Two different types with this name exist, but they are unrelated.
    Property 'root' is missing in type 'Tree'.
src/my-other-schematic/index_spec.ts(12,64): error TS2345: Argument of type 'Tree' is not assignable to parameter of type 'Tree | undefined'.
  Type 'Tree' is not assignable to type 'Tree'. Two different types with this name exist, but they are unrelated.
src/my-schematic/index_spec.ts(12,58): error TS2345: Argument of type 'Tree' is not assignable to parameter of type 'Tree | undefined'.
  Type 'Tree' is not assignable to type 'Tree'. Two different types with this name exist, but they are unrelated.
error Command failed with exit code 1.

Desired functionality

Compilation fails and probably should not

Purify should annotate the top level function call before parenthesis.

Consider this line

export const Injectable: InjectableDecorator = <InjectableDecorator>makeDecorator('Injectable');

The cast <InjectableDecorater> causes this code in tsickle

export const Injectable = (/**@type{InjectableDecortaro}*/makeDecorator('Injectable'));

This generates (notice the parenthesis)

var Injectable = (/*@__PURE__*/ makeDecorator('Injectable'));

Which than makes it retained as parenthesis defeats the @__PURE__. This than retains large portion of code.

Cannot use collection outside node_modules

Bug Report or Feature Request (mark with an x)

- [?] bug report -> please search issues before submitting
- [?] feature request

Cannot use collection outside node_modules.

Area

- [ ] devkit
- [x] schematics

Versions

Angular CLI: 1.5.0-rc.2
Node: 8.5.0
OS: win32 x64
Angular: 5.0.0-rc.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, platform-server
... platform-webworker, platform-webworker-dynamic, router
... service-worker

@angular/cli: 1.5.0-rc.2
@angular-devkit/build-optimizer: 0.0.29
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.34
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.8.0-rc.2
@schematics/angular: 0.0.48
@schematics/schematics: 0.0.3
typescript: 2.5.3
webpack: 3.8.1

Repro steps

I made <root>/.test/ folder and copied <root>/node_modules/@schematics/angular into it.
I get an error below when I run:

ng g e ooo --collection .test/angular -d

The log given by the failure

C:\dev\projects\sch-test>ng g e ooo --collection .test/angular -d
Could not find module ".test/angular" from "C:\\dev\\projects\\sch-test".
Error: Could not find module ".test/angular" from "C:\\dev\\projects\\sch-test".
    at Object.resolve (C:\dev\projects\sch-test\node_modules\@angular-devkit\core\node\resolve.js:140:11)
    at NodeModulesEngineHost._resolvePackageJson (C:\dev\projects\sch-test\node_modules\@angular-devkit\schematics\tools\node-module-engine-host.js:22:21)
    at NodeModulesEngineHost._resolveCollectionPath (C:\dev\projects\sch-test\node_modules\@angular-devkit\schematics\tools\node-module-engine-host.js:43:36)
    at NodeModulesEngineHost.createCollectionDescription (C:\dev\projects\sch-test\node_modules\@angular-devkit\schematics\tools\file-system-engine-host-base.js:94:27)
    at SchematicEngine.createCollection (C:\dev\projects\sch-test\node_modules\@angular-devkit\schematics\src\engine\engine.js:47:40)
    at Object.getCollection (C:\dev\projects\sch-test\node_modules\@angular\cli\utilities\schematics.js:37:31)
    at Class.run (C:\dev\projects\sch-test\node_modules\@angular\cli\tasks\schematic-get-options.js:11:41)
    at Class.beforeRun (C:\dev\projects\sch-test\node_modules\@angular\cli\commands\generate.js:90:31)
    at Promise.resolve.then (C:\dev\projects\sch-test\node_modules\@angular\cli\ember-cli\lib\cli\cli.js:138:24)
    at <anonymous>

Desired functionality

If I move schematics files to <root>/node_modules/.test/angular it works:

C:\dev\projects\sch-test>ng g e ooo --collection .test/angular -d
  create src/app/ooo.enum.ts (20 bytes)

NOTE: Run with "dry run" no changes were made.

Is it possible to use collections from outside node_modules ?

I'd like to keep my custom collections in my git repo, among other things.

Mention any other details that might be useful

I believe the problem is in angular_devkit/schematics/tools/node-module-engine-host.ts, but can't figure out exactly what it is...

__name@dasherize__.component.spec.ts don't use async in spec case

Build optimizer: removing BrowserAnimationsModule

"@angular/cli": "1.3.0-rc.5"
"typescript": "2.4.2" ( and 2.3.4)

Workaround: ng build --preserve-symlinks allows to work with npm linked modules,
and remove tsconfig path entries

Issue:
BrowserAnimationsModule is completely removed from main.js bundle
which leads to issue in _createProviderInstance
here: https://github.com/angular/angular/blob/39b92f7e546b8bdecc0e08c915d36717358c122b/packages/core/src/view/ng_module.ts#L110

because ctor will be undefined

How to reproduce

  1. ng new test-bob
  2. in app.module.ts add
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    and
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  1. in tsconfig.app.json add line to paths
"types": [],
    "paths": {
      "@angular/*": ["../node_modules/@angular/*"]
    }

Why add this kind of mapping?
It is needed for successful build when you work with linked angular modules

Build optimizer incorrect code for enum

(resubmitting from angular/angular#19137 by @achimha)

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[X] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

Using --build-optimizer on @angular/cli 1.4.1 generates incorrect code for a module of @ng-bootstrap

The enum ModalDismissReasons is not correctly referenced, it evaluates to undefined when accessed via o.ModalDismissReasons. Instead of referencing to it as a, it is still referenced as ModalDismissReasons. The source code is here

https://github.com/ng-bootstrap/ng-bootstrap/blob/0c03671c52500f13387deeaf31f815372d364c26/src/modal/modal-window.ts#L45

AVYa: function(t, e, n) {
        "use strict";
        n.d(e, "a", function() {
            return i
        });
        var r = n("/oeL")
          , o = n("zGKh")
          , i = (n.n(o),
        function() {
            function t(t, e) {
                this._elRef = t,
                this._renderer = e,
                this.backdrop = !0,
                this.keyboard = !0,
                this.dismissEvent = new r.EventEmitter
            }
            return t.prototype.backdropClick = function(t) {
                !0 === this.backdrop && this._elRef.nativeElement === t.target && this.dismiss(o.ModalDismissReasons.BACKDROP_CLICK)
            }
            ,
            t.prototype.escKey = function(t) {
                this.keyboard && !t.defaultPrevented && this.dismiss(o.ModalDismissReasons.ESC)
            }
            ,
            t.prototype.dismiss = function(t) {
                this.dismissEvent.emit(t)
            }
            ,
            t.prototype.ngOnInit = function() {
                this._elWithFocus = document.activeElement,
                this._renderer.addClass(document.body, "modal-open")
            }
            ,
            t.prototype.ngAfterViewInit = function() {
                this._elRef.nativeElement.contains(document.activeElement) || this._elRef.nativeElement.focus.apply(this._elRef.nativeElement, [])
            }
            ,
            t.prototype.ngOnDestroy = function() {
                var t, e = document.body, n = this._elWithFocus;
                t = n && n.focus && e.contains(n) ? n : e,
                t.focus.apply(t, []),
                this._elWithFocus = null,
                this._renderer.removeClass(e, "modal-open")
            }
            ,
            t
        }())
    },

Expected behavior

Without --build-optimizer, the generated code looks like this:

AVYa: function(t, e, n) {
        "use strict";
        n.d(e, "a", function() {
            return i
        });
        var r = n("/oeL")
          , o = n("zGKh")
          , i = function() {
            function t(t, e) {
                this._elRef = t,
                this._renderer = e,
                this.backdrop = !0,
                this.keyboard = !0,
                this.dismissEvent = new r.EventEmitter
            }
            return t.prototype.backdropClick = function(t) {
                !0 === this.backdrop && this._elRef.nativeElement === t.target && this.dismiss(o.a.BACKDROP_CLICK)
            }
            ,
            t.prototype.escKey = function(t) {
                this.keyboard && !t.defaultPrevented && this.dismiss(o.a.ESC)
            }
            ,
            t.prototype.dismiss = function(t) {
                this.dismissEvent.emit(t)
            }
            ,
            t.prototype.ngOnInit = function() {
                this._elWithFocus = document.activeElement,
                this._renderer.addClass(document.body, "modal-open")
            }
            ,
            t.prototype.ngAfterViewInit = function() {
                this._elRef.nativeElement.contains(document.activeElement) || this._elRef.nativeElement.focus.apply(this._elRef.nativeElement, [])
            }
            ,
            t.prototype.ngOnDestroy = function() {
                var t, e = document.body, n = this._elWithFocus;
                t = n && n.focus && e.contains(n) ? n : e,
                t.focus.apply(t, []),
                this._elWithFocus = null,
                this._renderer.removeClass(e, "modal-open")
            }
            ,
            t
        }();
        i.decorators = [{
            type: r.Component,
            args: [{
                selector: "ngb-modal-window",
                host: {
                    "[class]": '"modal fade show" + (windowClass ? " " + windowClass : "")',
                    role: "dialog",
                    tabindex: "-1",
                    style: "display: block;",
                    "(keyup.esc)": "escKey($event)",
                    "(click)": "backdropClick($event)"
                },
                template: "\n    <div [class]=\"'modal-dialog' + (size ? ' modal-' + size : '')\" role=\"document\">\n        <div class=\"modal-content\"><ng-content></ng-content></div>\n    </div>\n    "
            }]
        }],
        i.ctorParameters = function() {
            return [{
                type: r.ElementRef
            }, {
                type: r.Renderer2
            }]
        }
        ,
        i.propDecorators = {
            backdrop: [{
                type: r.Input
            }],
            keyboard: [{
                type: r.Input
            }],
            size: [{
                type: r.Input
            }],
            windowClass: [{
                type: r.Input
            }],
            dismissEvent: [{
                type: r.Output,
                args: ["dismiss"]
            }]
        }
    },

It seems that the build optimizer is responsible for the enum lookup using the original Typescript identifier instead of the generated enum function.

This could be a TS bug of course. Using Typescript 2.5.2.

Environment


Angular version: 4.3.6

Angular CLI 1.4.1
TypeScript 2.5.2
 

User errors shouldn't print stack traces

When the CLI is reporting an error that represents invalid options or inputs, it should not print a stack trace. It should still return a shell status code.

Some schematics are throwing an Error for these messages, but we need to differentiate between user errors and internal tool errors to hide diagnostic info in the first case (unless, perhaps, a --debug tool flag is included).

insertLeft/Right beyond boundary flips and binds to end?

In the text update recorder, insertLeft(length + 1, ...) returns an index error. It would be helpful and intuitive for some algorithms for this specific case to be interpreted as insertRight(length, ...). For example, if I'm scanning a string for a position to do an insertLeft and do not find a matching position prior to the end, I want to append to the end. As is, I have to make a special case and call insertRight directly.

The symmetric operation would be insertRight(-1, ...) -> insertLeft(0, ...).

I don't know if it needs to allow all indexes past the ends or just one past the end. And there may be reasons I'm not thinking of to not do this at all.

build-optimizer: size regression due to retention of decorators emitted via "emitDecoratorMetadata" tsconfig option

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

0.28.0

Repro steps

import { Component, ElementRef, EventEmitter, HostListener, Input, Output, OnInit } from '@angular/core';

export interface Option {
  title: string;
  value?: any;
}

@Component({
  selector: 'aio-select',
  templateUrl: 'select.component.html'
})
export class SelectComponent implements OnInit {
  @Input()
  selected: Option;

  @Input()
  options: Option[];

  @Output()
  change = new EventEmitter<{option: Option, index: number}>();

  @Input()
  showSymbol = false;

  @Input()
  label: string;

  showOptions = false;

  constructor(private hostElement: ElementRef) {}

  ngOnInit() {
    this.label = this.label || '';
  }

  toggleOptions() {
    this.showOptions = !this.showOptions;
  }

  hideOptions() {
    this.showOptions = false;
  }

  select(option: Option, index: number) {
    this.selected = option;
    this.change.emit({option, index});
    this.hideOptions();
  }

  @HostListener('document:click', ['$event.target'])
  onClick(eventTarget: HTMLElement) {
    // Hide the options if we clicked outside the component
    if (!this.hostElement.nativeElement.contains(eventTarget)) {
      this.hideOptions();
    }
  }

  @HostListener('document:keydown.escape')
  onKeyDown() {
    this.hideOptions();
  }
}

gets transpiled into:

import * as tslib_1 from "tslib";
import { Component, ElementRef, EventEmitter, HostListener, Input, Output } from '@angular/core';
var SelectComponent = /** @class */ (function () {
    function SelectComponent(hostElement) {
        this.hostElement = hostElement;
        this.change = new EventEmitter();
        this.showSymbol = false;
        this.showOptions = false;
    }
    SelectComponent.prototype.ngOnInit = function () {
        this.label = this.label || '';
    };
    SelectComponent.prototype.toggleOptions = function () {
        this.showOptions = !this.showOptions;
    };
    SelectComponent.prototype.hideOptions = function () {
        this.showOptions = false;
    };
    SelectComponent.prototype.select = function (option, index) {
        this.selected = option;
        this.change.emit({ option: option, index: index });
        this.hideOptions();
    };
    SelectComponent.prototype.onClick = function (eventTarget) {
        // Hide the options if we clicked outside the component
        if (!this.hostElement.nativeElement.contains(eventTarget)) {
            this.hideOptions();
        }
    };
    SelectComponent.prototype.onKeyDown = function () {
        this.hideOptions();
    };
    tslib_1.__decorate([
        Input(),
        tslib_1.__metadata("design:type", Object)
    ], SelectComponent.prototype, "selected", void 0);
    tslib_1.__decorate([
        Input(),
        tslib_1.__metadata("design:type", Array)
    ], SelectComponent.prototype, "options", void 0);
    tslib_1.__decorate([
        Output(),
        tslib_1.__metadata("design:type", Object)
    ], SelectComponent.prototype, "change", void 0);
    tslib_1.__decorate([
        Input(),
        tslib_1.__metadata("design:type", Object)
    ], SelectComponent.prototype, "showSymbol", void 0);
    tslib_1.__decorate([
        Input(),
        tslib_1.__metadata("design:type", String)
    ], SelectComponent.prototype, "label", void 0);
    tslib_1.__decorate([
        HostListener('document:click', ['$event.target']),
        tslib_1.__metadata("design:type", Function),
        tslib_1.__metadata("design:paramtypes", [HTMLElement]),
        tslib_1.__metadata("design:returntype", void 0)
    ], SelectComponent.prototype, "onClick", null);
    tslib_1.__decorate([
        HostListener('document:keydown.escape'),
        tslib_1.__metadata("design:type", Function),
        tslib_1.__metadata("design:paramtypes", []),
        tslib_1.__metadata("design:returntype", void 0)
    ], SelectComponent.prototype, "onKeyDown", null);
    SelectComponent = tslib_1.__decorate([
        Component({
            selector: 'aio-select',
            templateUrl: 'select.component.html'
        }),
        tslib_1.__metadata("design:paramtypes", [ElementRef])
    ], SelectComponent);
    return SelectComponent;
}());
export { SelectComponent };
//# sourceMappingURL=select.component.js.map

Desired functionality

all of the tslib_1.__metadata(...) decorators should be stripped.

An alternative solution could be to turn off the emitDecoratorMetadata compiler option, when build optimizer flag is turned on. This would be fine, because these decorators typically come only from the application code. Third party libraries (angular, material, etc) should downlevel these into .ctorParameters and friends and we already stip these in build-optimizer.

Mention any other details that might be useful

[angular/core] make DebugServices treeshakable (~10KB savings)

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search issues before submitting
- [x] feature request

Area

- [x] devkit
- [ ] schematics

Desired functionality

Uglify is not able to remove unused debug services bocause of condition: core.js#L13946 and replacing that condition with createProdServices() resulted in ~10KB savings

-- var /** @type {?} */ services = isDevMode() ? createDebugServices() : createProdServices();
++ var /** @type {?} */ services = createProdServices();

remove decorators if exist in reassign multiple variables

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

0.0.29

Repro steps

in somecases the class gets transpiled into:

import { Injectable } from '@angular/core';
import { Store as NgrxStore } from '@ngrx/store';
var Store = /** @class */ (function () {
    function Store(store) {
        this.store = store;
        Store_1.instance = store;
    }
    Store_1 = Store;
    Store.prototype.dispatch = function (action) {
        this.store.dispatch(action);
    };
    Store = Store_1 = __decorate([
        Injectable(),
        __metadata("design:paramtypes", [NgrxStore])
    ], Store);
    return Store;
    var Store_1;
}());

Desired functionality

The Store = Store_1 = __decorate should be stripped.

build-optimizer: high memory usage (node crash)

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

macOS 10.13 (High Sierra)
It affects Windows as well, but on mac it is higher (larger than 1.7 gigs, therefore causes crash with node by default)

Repro steps

The problem is happening with the build-optimizer version 0.0.31.

Using @angular/cli 1.5.0-rc.2 and building with
ng build --prod --aot --build-optimizer

The memory usage starts to grow radically at 95% emitting stage. On a semi-large project this reaches 1.7 gigs on mac, which in turn causes a crash. Increasing the memory limit on node solves the issue, but this seems rather high.

Running it without build-optimizer it builds fine without a crash.

The log given by the failure

$ ng build --prod --aot --build-optimizer
 95% emitting                                                                 s <--- Last few GCs --->

[10242:0x103000000]   191148 ms: Mark-sweep 1417.1 (2081.5) -> 1417.1 (2081.5) MB, 753.9 / 0.0 ms  allocation failure scavenge might not succeed
[10242:0x103000000]   191836 ms: Mark-sweep 1417.1 (2081.5) -> 1417.1 (2035.5) MB, 687.0 / 0.0 ms  last resort GC in old space requested
[10242:0x103000000]   192507 ms: Mark-sweep 1417.1 (2035.5) -> 1417.1 (2013.5) MB, 670.8 / 0.0 ms  last resort GC in old space requested


<--- JS stacktrace --->

==== JS stack trace =========================================

Security context: 0x31fd83fa5e91 <JSObject>
    1: DoJoin(aka DoJoin) [native array.js:~95] [pc=0x112d8f5ead39](this=0x31fd64e82311 <undefined>,p=0x31fdc377f859 <JSArray[432]>,q=432,E=0x31fd64e823b1 <true>,A=0x31fd83fef239 <String[1]:  >,z=0x31fd64e82421 <false>)
    2: Join(aka Join) [native array.js:~120] [pc=0x112d8ee542a9](this=0x31fd64e82311 <undefined>,p=0x31fdc377f859 <JSArray[432]>,q=432,A=0x31fd83fef239 <String[1]:  >,z=0x31fd64e...

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/Users/balazsrostas/.nvm/versions/node/v8.8.1/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/Users/balazsrostas/.nvm/versions/node/v8.8.1/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/Users/balazsrostas/.nvm/versions/node/v8.8.1/bin/node]
 4: v8::internal::Factory::NewRawTwoByteString(int, v8::internal::PretenureFlag) [/Users/balazsrostas/.nvm/versions/node/v8.8.1/bin/node]
 5: v8::internal::Runtime_StringBuilderJoin(int, v8::internal::Object**, v8::internal::Isolate*) [/Users/balazsrostas/.nvm/versions/node/v8.8.1/bin/node]
 6: 0x112d8ed0463d
error Command failed with signal "SIGABRT".

Desired functionality

Using the build-optimizer shouldn't exceed the default 1.7GB threshold on a semi-large project.

recognize tslib.__decorate as if it was __decorate

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

[email protected]

Repro steps

set importHelpers: true in tsconfig of an app then build with build optimizer

Desired functionality

Decorators should be stripped.

Mention any other details that might be useful

This is a follow up on #210 which implements this functionality for global __decorate calls.

build-optimizer: enum wrapping pass is unsafe in atypical use cases

Bug Report or Feature Request (mark with an x)

- [X] bug report -> please search issues before submitting
- [ ] feature request

Area

- [X] devkit
- [ ] schematics

Versions

Repro steps

An enum member can contain an initializer which may have side effects. Currently all enums are wrapping in an IIFE and annotated with PURE which will prevent the side effects from occurring if the enum is unused.

function getValue() {
  console.log('hi');
  return 6;
}

enum Test {
  ValueA,
  ValueB = getValue()
}

Desired functionality

As this will most likely be an extremely rare occurrence, a documentation note may suffice. Additionally a warning or informational message may also be useful when an enum is encountered with a member containing a non-constant expression.

Mention any other details that might be useful

build-optimizer over code that's already optimized fails

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

Repro steps

RxJS 5.5 was recently published. It uses the build-optimizer to produce code that's pre-optimized so it works with applications not running under the CLI. Testing for AIO showed that the build size was increasing using the new features of Rx. Digging in a little further, it appears that when we pull in rxjs and run it through build-optimizer, the existing PURE annotations are removed and not replaced.

You can reproduce this issue using this repo/branch. Look in main.ts. Note: actual user-land code will not import from _esm5 but will instead use mappings to point to it. There's a pending issue for CLI to make this change.

https://github.com/jasonaden/repro/tree/rxjs_build_optimizer

The log given by the failure

Desired functionality

Should treeshake

Mention any other details that might be useful

Interactive input dialog

The command line tool should have two running modes: an interactive mode and a batch mode. In batch mode, all inputs for the schematic are specified on the command line, and input validation errors terminate the tool with a message. In interactive mode, a schematic can be invoked with or without arguments on the command line, and the tool begins an interactive dialog describing the behavior of the schematic, and presents and prompts for values for some or all inputs. Inputs with defaults or whose values were provided by another source are presented for confirmation ("press enter to accept default"-style). After all prompts have been presented, show a confirmation screen with all inputs and accepted values, and allow selective adjustment of values.

Schematic properties will need short and long descriptions and a value type (string, boolean, maybe number).

The confirmation screen can come after all rules have been evaluated to report conflicts and errors and allow the user to adjust inputs interactively to resolve the conflicts. After confirmation, the schematic can execute side effects (FSSink, task execution).

(Ask me for a more detailed design or demo. I have a full implementation in a related tool.)

build-optimizer: enums are not being wrapped any more

Bug Report or Feature Request (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request

Area

- [x] devkit
- [ ] schematics

Versions

Repro steps

original TS:

export enum FormatWidth {
  Short,
  Medium,
  Long,
  Full
}

downleveled to js via tsickle:

/** @enum {number} */
const FormatWidth = {
    Short: 0,
    Medium: 1,
    Long: 2,
    Full: 3,
};
FormatWidth[FormatWidth.Short] = "Short";
FormatWidth[FormatWidth.Medium] = "Medium";
FormatWidth[FormatWidth.Long] = "Long";
FormatWidth[FormatWidth.Full] = "Full";

after build optimizer:

        /** @enum {number} */
        var FormatWidth = {
            Short: 0,
            Medium: 1,
            Long: 2,
            Full: 3
        };
        FormatWidth[FormatWidth.Short] = "Short";
        FormatWidth[FormatWidth.Medium] = "Medium";
        FormatWidth[FormatWidth.Long] = "Long";
        FormatWidth[FormatWidth.Full] = "Full";

Desired functionality

The enum should have been rewritten into:

var FormatWidth = /*@__PURE__*/ (function () {
        /** @enum {number} */
        var FormatWidth = {
            Short: 0,
            Medium: 1,
            Long: 2,
            Full: 3
        };
        FormatWidth[FormatWidth.Short] = "Short";
        FormatWidth[FormatWidth.Medium] = "Medium";
        FormatWidth[FormatWidth.Long] = "Long";
        FormatWidth[FormatWidth.Full] = "Full";
        return FormatWidth;
());

Mention any other details that might be useful

Angular CLI: 1.5.0-rc.2
Node: 6.9.5
OS: darwin x64
Angular: 5.0.0-rc.2
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

@angular/cdk: 2.0.0-beta.12
@angular/cli: 1.5.0-rc.2
@angular/material: 2.0.0-beta.12
@angular/service-worker: 1.0.0-beta.16
@angular-devkit/build-optimizer: 0.0.29
@angular-devkit/core: 0.0.20
@angular-devkit/schematics: 0.0.34
@ngtools/json-schema: 1.1.0
@schematics/angular: 0.0.48
typescript: 2.4.2
webpack: 3.7.1

Incorrect Implementations of Schematic interface

I get the below lint error in the SchematicImpl class in schematic.ts

  Types of property 'call' are incompatible.
    Type '<OptionT extends object>(options: OptionT, host: Observable<Tree>) => Observable<Tree>' is not assignable to type '<T>(options: T, host: Observable<Tree>) => Observable<Tree>'.
      Types of parameters 'options' and 'options' are incompatible.
        Type 'T' is not assignable to type 'object'.```

schematics: Cannot generate same element again

My use-case, I'd like to generate .spec.ts file only into already existing components/pipes generated by CLI.

src/app/core/components/
└── my-cmp
    ├── my-cmp.component.html
    ├── my-cmp.component.scss
    ├── (my-cmp.component.spec.ts) <-- I want to generate this later
    └── my-cmp.component.ts

Currently, I cannot generate spec without other files.

> ng g component core/components/my-cmp --spec
error! src/app/core/components/my-cmp/my-cmp.component.html already exists.
error! src/app/core/components/my-cmp/my-cmp.component.ts already exists.

--force option allows do that, but it will initialize existing code. I'd like to just append .spec.ts.

Refelect Polyfills for Angular no longer necessary

In the file https://github.com/angular/devkit/blob/master/packages/schematics/angular/application/files/__path__/polyfills.ts with the default Polyfills for Angular CLI you have this:

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';

According to http://kangax.github.io/compat-table/es6/#test-Reflect this seems no longer to be true. By removing these lines, an Angular app can spare some more kB.

ngo is removing rxjs add operators

Using:

@angular/cli: 1.3.0-rc.1
node: 8.1.3
os: linux x64
@angular/animations: 4.3.1
@angular/cli: 1.3.0-rc.1
@angular/common: 4.3.1
@angular/compiler: 4.3.1
@angular/compiler-cli: 4.3.1
@angular/core: 4.3.1
@angular/forms: 4.3.1
@angular/http: 4.3.1
@angular/material: 2.0.0-beta.2
@angular/platform-browser: 4.3.1
@angular/platform-browser-dynamic: 4.3.1
@angular/router: 4.3.1
@angular/service-worker: 1.0.0-beta.16

I have import 'rxjs/add/operator/filter'; at the top of my app.component.ts file.

Expected Behavior:
When I use .filter on an observable, I expect the call to succeed

Observed Behavior
The filter method is missing from the prototype of Observable.

Other Background
In the source code generated with ng build -prod -bo, the import is being marked as pure.

        /*@__PURE__*/
        __webpack_require__("gbhw");

Use "pure-module" flag from package.json to opt modules into the more aggressive build optimization process

build optimizer currently contains a whitelist for all packages that should be processed:

/(\\|\/)node_modules(\\|\/)@angular(\\|\/)animations(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)common(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)compiler(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)core(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)forms(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)http(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)platform-browser-dynamic(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)platform-browser(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)platform-webworker-dynamic(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)platform-webworker(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)router(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)upgrade(\\|\/)/,
/(\\|\/)node_modules(\\|\/)@angular(\\|\/)material(\\|\/)/,

This whitelist is for prefixing function calls with pure annotation for uglify.

Webpack is working on introducing pure module feature that npm packages opt-in to via "pure-module": true in package.json.

Since the meaning of this flag is the same as what we need for purification of top level function calls, we could get rid of the whitelist and use the same package.json metadata as webpack.

Since all of the modules in the whitelist will also want to benefit from the pure-modules feature in webpack, sharing the flag would allow us to get rid of the whitelist.

Post-processing tasks; task runner plugin arch

Schematics should be able to enqueue tasks of various types that are run after file contents have been evaluated and written to disk. There is no expectation that changes can be rolled back if there is an error executing a task, though it might make sense to abort execution of other tasks if any task returns an error.

Tasks could invoke other tasks. These could be enqueued in layers, and each layer sent to a runner for a task type as a batch for efficient execution.

We also need a mechanism to define task types (invocation inputs, runners) outside of the Schematics core code, such as for invoking external tools specific to a developer's environment.

Example use cases: committing to source control automatically, creating bugs in a bug tracker, invoking external text processing tools that cannot integrate with Schematics' staging area for some reason.

Should --open parameter be added to start script

In the Tour of Heros tutorial here and here it says:

$ npm start

This command runs the TypeScript compiler in "watch mode",
recompiling automatically when the code changes. The command
simultaneously launches the app in a browser and refreshes the
browser when the code changes.

But the start script in package is "start": "ng serve", and does not have the --open parameter needed to cause the launching of the app in the browser.

I've created PR #119 which adds the --open parameter and this corrects the problem for me.

How to install this?

Hey, i'd love to play around with this a bit but i can't get it to work. When trying to yarn link the CLI i always end up with

Error: Cannot find module '../src/cli'
    at Function.Module._resolveFilename (module.js:470:15)
    at Function.Module._load (module.js:418:25)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/usr/local/share/.config/yarn/global/node_modules/@_/schematics-cli/bin/schematics.js:9:1)

Changelog for official Angular schematics

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search issues before submitting
- [x] feature request

Area

- [ ] devkit
- [x] schematics

Desired functionality

To stay up to date, upgrading the CLI itself is not enough. We need to know the changes done in the official Angular schematics, for example to know when the dependencies are updated in package.json to know when it's safe to upgrade tools (like tslint, codelizer, etc.). There can also be changes in other files (for tests, polyfills and so on...).

And currently, we have to look at the git history of each file within this repo (which is now separate from the CLI, and some people may even not know about it).

So a CHANGELOG is really required, or at least, changes done here should be integrated in the CLI changelog.

Thanks.

ngtools/webpack does not emit ngmodule decorator information.

Resubmitting from angular/angular#18591:

I'm submitting a...


[ ] Regression (a behavior that used to work and stopped working in a new release)
[x] Bug report  
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior

I am trying to integrate AOT compilation into an existing Angular component library. This library has always been packaged using webpack, so I integrated ngtools/webpack into my configuration. After resolving the problem of ngtools/webpack not inlining / requireing external templates and styles, I was still not able to use the resulting JS module. Whenever I try to run an app using this, I would get an error stating that the module class is missing its NgModule decorator.

When examining the generated code, I noticed that ngtools/webpack has stripped all decorators from the code.

Expected behavior

ngtools/webpack should keep angular-specific decorators.

Minimal reproduction of the problem with instructions

What is the motivation / use case for changing the behavior?

Environment


Angular version: 4.3.3


Browser:
- [x] Chrome (desktop) version XX
- [ ] Chrome (Android) version XX
- [ ] Chrome (iOS) version XX
- [ ] Firefox version XX
- [ ] Safari (desktop) version XX
- [ ] Safari (iOS) version XX
- [ ] IE version XX
- [ ] Edge version XX
 
For Tooling issues:
- Node version: XX  
- Platform:  

Others:

Combine two schematics collections

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search issues before submitting
- [x] feature request

Area

@angular/schematics

Desired functionality

I would like to be able to combine two schematics. Is this possible?

I would like to build some schematics for code generation for my use cases that I plan to apply on top of another schematic. This way I can update each schematics code bases independently.

Example:
ng new --collection=nrwl/schematics+my/schematics

angular-cli blueprint fixes are missing

After I added a thirdparty module ng lint crashes, because some errors inside node_modules/. (Angular CLI 1.4.1)
This was working with Angular CLI 1.3.x. I think this commit solved the issue: angular/angular-cli@6ad27c5

I noticed the Angular CLI blueprints moved to this repository with 1.4.x.
For my concrete problem I found that the angular-cli.json file was added on May 24 in this repository. f4c7d57#diff-4b1a9b6e7d7776971a9cdcb8364ac67e
The fix in the Angular CLI blueprints was done later (14 Jul)

Are the blueprints different in this repository on purpose or is there a 'bug' that the blueprint fixes from the angular-cli repo (https://github.com/angular/angular-cli/commits/1.3.x/packages/%40angular/cli/blueprints) are not merged here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.