diff --git a/.dockerignore b/.dockerignore new file mode 100755 index 0000000000..24f1eaae6f --- /dev/null +++ b/.dockerignore @@ -0,0 +1,39 @@ +.git +.github +.vscode +coverage + +# OS generated files # +.DS_Store +ehthumbs.db +Icon? +Thumbs.db + +# Node Files # +node_modules +npm-debug.log +npm-debug.log.* + +# Typing # +src/typings/tsd +typings +tsd_typings + +# Dist # +dist +.awcache +.webpack.json +compiled +dll + +# IDE # +.idea +*.swp + + +# Angular # +*.ngfactory.ts +*.css.shim.ts +*.ngsummary.json +*.shim.ngstyle.ts + diff --git a/.editorconfig b/.editorconfig index 0284f828d0..57292716f7 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,4 @@ -# @AngularClass +# tipe.io # http://editorconfig.org root = true @@ -14,7 +14,3 @@ trim_trailing_whitespace = true [*.md] insert_final_newline = false trim_trailing_whitespace = false - -[*.json] -insert_final_newline = false -trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..70e53eefec --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +yarn.lock -diff diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000000..7e4625347f --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,11 @@ +## Read and contribute to the Wiki + +Make sure you read the [Wiki](https://github.com/gdi2290/angular-starter/wiki). + +## Submitting Pull Requests + +If you're changing the structure of the repository please create an issue first. + +## Submitting bug reports + +Make sure you are on latest changes and that you ran this command `npm run clean:install` after updating your local repository. If you can, please provide more information about your environment such as browser, operating system, node version, and npm version. diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000000..7691371586 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [PatrickJS] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..ba1a09ad84 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,34 @@ +* **I'm submitting a ...** +[ ] bug report +[ ] feature request +[ ] question about the decisions made in the repository + +* **Do you want to request a *feature* or report a *bug*?** + + + +* **What is the current behavior?** + + + +* **If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem** via +https://plnkr.co or similar (you can use this template as a starting point: http://plnkr.co/edit/tpl:AvJOMERrnz94ekVua0u5). + + + +* **What is the expected behavior?** + + + +* **What is the motivation / use case for changing the behavior?** + + + +* **Please tell us about your environment:** + +- Angular version: 4.x.x +- Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ] + + + +* **Other information** (e.g. detailed explanation, stacktraces, related issues, suggestions how to fix, links for us to have context, eg. stackoverflow, gitter, etc) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..caae6b13d2 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +* **What kind of change does this PR introduce?** (Bug fix, feature, docs update, ...) + + + +* **What is the current behavior?** (You can also link to an open issue here) + + + +* **What is the new behavior (if this is a feature change)?** + + + +* **Other information**: diff --git a/.gitignore b/.gitignore index fa9669f903..1a2a9656e7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -# @AngularClass +# tipe.io # Logs logs @@ -15,6 +15,9 @@ lib-cov # Coverage directory used by tools like istanbul coverage +# SonarQube sonar-scanner temp directory +.scannerwork + # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt @@ -31,8 +34,16 @@ Icon? Thumbs.db # Node Files # -/node_modules -/bower_components +/node_modules/ +/bower_components/ +npm-debug.log +/npm-debug.log.* + +# Coverage # +/coverage/ + +# Generic Unit Sonar Reports # +/reports/ # Typing # /src/typings/tsd/ @@ -43,12 +54,29 @@ Thumbs.db /dist /public/__build__/ /src/*/__build__/ -__build__/** +/__build__/** +/public/dist/ +/src/*/dist/ +/dist/** +/.awcache .webpack.json +/compiled/ +dll/ +temp +tmp +webpack-cache -#doc -/doc +# Doc # +/doc/ +/documentation/ # IDE # .idea/ *.swp + + +# Angular # +*.ngfactory.ts +*.css.shim.ts +*.ngsummary.json +*.shim.ngstyle.ts diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000000..b009dfb9d9 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +lts/* diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000..49c6a52523 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,30 @@ +sudo: false +dist: trusty +language: node_js + +cache: + directories: + - node_modules + +addons: + chrome: stable + +node_js: + - "6" + - "7" + - "8" + +matrix: + fast_finish: true + +before_install: + - npm install npm@5 -g + - npm cache verify + - npm prune + - npm update + +install: + - npm install + +script: + - npm run ci:travis diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000000..9fe889a529 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,27 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Chrome against localhost, with sourcemaps", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000/*", + "runtimeArgs": [ + "--disable-web-security", + "--user-data-dir", + "--remote-debugging-port=9222" + ], + "sourceMaps": true, + "webRoot": "${workspaceRoot}" + }, + { + "name": "Attach to Chrome, with sourcemaps", + "type": "chrome", + "request": "attach", + "url": "http://localhost:3000/*", + "port": 9222, + "sourceMaps": true, + "webRoot": "${workspaceRoot}" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..edce53674c --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "typescript.tsdk": "node_modules/typescript/lib/" +} diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..f74a52d27e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +# Usage: +# +# Build image: +# docker build -t angular-starter . +# +# Run image (on localhost:8080): +# docker run --name angular-starter -p 8080:80 angular-starter +# +# Run image as virtual host (read more: https://github.com/jwilder/nginx-proxy): +# docker run -e VIRTUAL_HOST=angular-starter.your-domain.com --name angular-starter angular-starter + +# Stage 1, based on Node.js, to build and compile Angular + +FROM node:8.9.4-alpine as builder + +COPY package.json ./ + +## Storing node modules on a separate layer will prevent unnecessary npm installs at each build +RUN npm i && mkdir /ng-app && mv ./node_modules ./ng-app + +WORKDIR /ng-app + +COPY . . + +RUN npm run build:aot:prod + +# Stage 2, based on Nginx, to have only the compiled app, ready for production with Nginx + +FROM nginx:1.13.9-alpine + +COPY ./config/nginx-custom.conf /etc/nginx/conf.d/default.conf + +## Remove default nginx website +RUN rm -rf /usr/share/nginx/html/* + +## From ‘builder’ stage copy over the artifacts in dist folder to default nginx public folder +COPY --from=builder /ng-app/dist /usr/share/nginx/html + +CMD ["nginx", "-g", "daemon off;"] diff --git a/Dockerfile-dev b/Dockerfile-dev new file mode 100644 index 0000000000..051ca9d399 --- /dev/null +++ b/Dockerfile-dev @@ -0,0 +1,21 @@ +# Usage: +# +# Build image: +# docker build -t angular-starter . +# +# Run image (on localhost:8080): +# docker run --name angular-starter -p 8080:80 angular-starter +# +# Run image as virtual host (read more: https://github.com/jwilder/nginx-proxy): +# docker run -e VIRTUAL_HOST=angular-starter.your-domain.com --name angular-starter angular-starter + +FROM node:8.9.4-alpine as builder + +COPY package.json ./ + +## Storing node modules on a separate layer will prevent unnecessary npm installs at each build +RUN npm i && mkdir /ng-app && mv ./node_modules ./ng-app + +WORKDIR /ng-app + +COPY . . diff --git a/LICENSE b/LICENSE index 41f55818a1..3c39f2bade 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 AngularClass LLC +Copyright (c) 2015-2018 PatrickJS, Tipe Inc Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -19,4 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/README.md b/README.md index a15298cab0..c14c84b6ad 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,69 @@ +# Please use the Angular CLI if you want an angular app + [![taylor swift](https://img.shields.io/badge/secured%20by-taylor%20swift-brightgreen.svg)](https://twitter.com/SwiftOnSecurity) -[![volkswagen status](https://auchenberg.github.io/volkswagen/volkswargen_ci.svg?v=1)](https://github.com/auchenberg/volkswagen) [![GitHub version](https://badge.fury.io/gh/angularclass%2Fangular2-webpack-starter.svg)](http://badge.fury.io/gh/angular-class%2Fangular2-webpack-starter) -[![Dependency Status](https://david-dm.org/angularclass/angular2-webpack-starter.svg)](https://david-dm.org/angularclass/angular2-webpack-starter) -[![Issue Stats](http://issuestats.com/github/angularclass/angular2-webpack-starter/badge/pr?style=flat)](http://issuestats.com/github/angularclass/angular2-webpack-starter) -[![Issue Stats](http://issuestats.com/github/angularclass/angular2-webpack-starter/badge/issue?style=flat)](http://issuestats.com/github/angularclass/angular2-webpack-starter) [![Stack Share](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](http://stackshare.io/angularclass/angular-2-webpack-starter) +[![volkswagen status](https://auchenberg.github.io/volkswagen/volkswargen_ci.svg?v=1)](https://github.com/auchenberg/volkswagen) +[![Build Status](https://travis-ci.org/gdi2290/angular-starter.svg?branch=master)](https://travis-ci.org/gdi2290/angular-starter) +[![GitHub version](https://badge.fury.io/gh/gdi2290%2Fangular-starter.svg)](https://badge.fury.io/gh/gdi2290%2Fangular-starter) +[![Dependency Status](https://david-dm.org/gdi2290/angular-starter.svg)](https://david-dm.org/gdi2290/angular-starter) +[![Stack Share](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](http://stackshare.io/gdi2290/angular-starter)

- - Webpack and Angular 2 + + Angular Starter

-# Angular2 Webpack Starter [![Join Slack](https://img.shields.io/badge/slack-join-brightgreen.svg)](https://angularclass.com/slack-join) [![Join the chat at https://gitter.im/angularclass/angular2-webpack-starter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angularclass/angular2-webpack-starter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# Angular Webpack Starter [![Join the chat at https://gitter.im/angularclass/angular2-webpack-starter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/angularclass/angular2-webpack-starter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) -> An Angular 2 starter kit featuring [Angular 2](https://angular.io) ([Router](https://angular.io/docs/js/latest/api/router/), [Forms](https://angular.io/docs/js/latest/api/forms/), -[Http](https://angular.io/docs/js/latest/api/http/), +> An Angular starter kit featuring [Angular 6](https://angular.io), [Ahead of Time Compile](https://angular.io/docs/ts/latest/cookbook/aot-compiler.html), [Router](https://angular.io/docs/ts/latest/guide/router.html), [Forms](https://angular.io/docs/ts/latest/guide/forms.html), +[Http](https://angular.io/docs/ts/latest/guide/server-communication.html), [Services](https://gist.github.com/gdi2290/634101fec1671ee12b3e#_follow_@AngularClass_on_twitter), -[Tests](https://angular.io/docs/js/latest/api/test/), [E2E](https://angular.github.io/protractor/#/faq#what-s-the-difference-between-karma-and-protractor-when-do-i-use-which-)), [Karma](https://karma-runner.github.io/), [Protractor](https://angular.github.io/protractor/), [Jasmine](https://github.com/jasmine/jasmine), [TypeScript](http://www.typescriptlang.org/), [Typings](https://github.com/typings/typings), and [Webpack](http://webpack.github.io/) by [AngularClass](https://angularclass.com). +[Tests](https://angular.io/docs/ts/latest/guide/testing.html), [E2E](https://angular.github.io/protractor/#/faq#what-s-the-difference-between-karma-and-protractor-when-do-i-use-which-)), [Karma](https://karma-runner.github.io/), [Protractor](https://angular.github.io/protractor/), [Jasmine](https://github.com/jasmine/jasmine), [Istanbul](https://github.com/gotwarlost/istanbul), [TypeScript](http://www.typescriptlang.org/), [@types](https://www.npmjs.com/~types), [TsLint](http://palantir.github.io/tslint/), [Codelyzer](https://github.com/mgechev/codelyzer), [Hot Module Replacement](https://webpack.github.io/docs/hot-module-replacement-with-webpack.html), and [Webpack](http://webpack.github.io/). -> If you're looking for Angular 1.x please use [NG6-starter](https://github.com/angularclass/NG6-starter) +> If you're looking for Angular 1.x please use [NG6-starter](https://github.com/gdi2290/NG6-starter) > If you're looking to learn about Webpack and ES6 Build Tools check out [ES6-build-tools](https://github.com/AngularClass/ES6-build-tools) +> If you're looking to learn TypeScript see [TypeStrong/learn-typescript](https://github.com/TypeStrong/learn-typescript) +> If you're looking for something easier to get started with then see the angular-seed that I also maintain [gdi2290/angular-seed](https://github.com/gdi2290/angular-seed) -This seed repo serves as an Angular 2 starter for anyone looking to get up and running with Angular 2 and TypeScript fast. Using a [Webpack](http://webpack.github.io/) for building our files and assisting with boilerplate. We're also using Protractor for our end-to-end story and Karma for our unit tests. -* Best practices in file and application organization for Angular 2. +This seed repo serves as an Angular starter for anyone looking to get up and running with Angular and TypeScript fast. Using a [Webpack 4](https://webpack.js.org) for building our files and assisting with boilerplate. We're also using Protractor for our end-to-end story and Karma for our unit tests. +* Best practices in file and application organization for Angular. * Ready to go build system using Webpack for working with TypeScript. -* Angular 2 examples that are ready to go when experimenting with Angular 2. -* A great Angular 2 seed repo for anyone who wants to start their project. -* Testing Angular 2 code with Jasmine and Karma. -* end-to-end Angular 2 code using Protractor. -* type manager with Typings - - -```coffeescript -Warning: Make sure you're using the latest version of Node.js and NPM -``` -[Is Angular 2 Ready Yet?](http://splintercode.github.io/is-angular-2-ready/) +* Angular examples that are ready to go when experimenting with Angular. +* A great Angular seed repo for anyone who wants to start their project. +* Ahead of Time (AoT) compile for rapid page loads of your production builds. +* Tree shaking to automatically remove unused code from your production bundle. +* Testing Angular code with Jasmine and Karma. +* Coverage with Istanbul and Karma +* End-to-end Angular app testing using Protractor. +* Type manager with @types +* Hot Module Replacement with Webpack and [@gdi2290/hmr](https://github.com/gdi2290/angular-hmr) and [@gdi2290/hmr-loader](https://github.com/PatrickJS/angular-hmr-loader) ### Quick start -> Clone/Download the repo then edit `app.ts` inside [`/src/app/app.ts`](/src/app/app.ts) +**Make sure you have Node version >= 8.0 and (NPM >= 5 or [Yarn](https://yarnpkg.com) )** +> Clone/Download the repo then edit `app.component.ts` inside [`/src/app/app.component.ts`](/src/app/app.component.ts) ```bash # clone our repo -git clone https://github.com/angularclass/angular2-webpack-starter.git +# --depth 1 removes all but one .git commit history +git clone --depth 1 https://github.com/gdi2290/angular-starter.git # change directory to our repo -cd angular2-webpack-starter +cd angular-starter # install the repo with npm npm install -# install typescript typings -typings install - # start the server npm start + +# use Hot Module Replacement +npm run server:dev:hmr + +# if you're in China use cnpm +# https://github.com/cnpm/cnpm ``` -go to [http://localhost:3000](http://localhost:3000) in your browser +go to [http://0.0.0.0:3000](http://0.0.0.0:3000) or [http://localhost:3000](http://localhost:3000) in your browser # Table of Contents * [File Structure](#file-structure) @@ -63,80 +71,116 @@ go to [http://localhost:3000](http://localhost:3000) in your browser * [Dependencies](#dependencies) * [Installing](#installing) * [Running the app](#running-the-app) +* [Configuration](#configuration) +* [AoT Don'ts](#aot-donts) +* [External Stylesheets](#external-stylesheets) * [Contributing](#contributing) * [TypeScript](#typescript) +* [@Types](#types) * [Frequently asked questions](#frequently-asked-questions) * [Support, Questions, or Feedback](#support-questions-or-feedback) +* [Deployment](#deployment) * [License](#license) ## File Structure We use the component approach in our starter. This is the new standard for developing Angular apps and a great way to ensure maintainable code by encapsulation of our behavior logic. A component is basically a self contained app usually in a single file or a folder with each concern as a file: style, template, specs, e2e, and component class. Here's how it looks: ``` -angular2-webpack-starter/ - ├──src/ * our source files that will be compiled to javascript - | ├──bootstrap.ts * our entry file for our browser environment +angular-starter/ + ├──config/ * our configuration + | ├──build-utils.js * common config and shared functions for prod and dev + | ├──config.common.json * config for both environments prod and dev such title and description of index.html + | ├──config.dev.json * config for development environment + | ├──config.prod.json * config for production environment + │ │ (note: you can load your own config file, just set the evn ANGULAR_CONF_FILE with the path of your own file) + | ├──helpers.js * helper functions for our configuration files + | ├──spec-bundle.js * ignore this magic that sets up our Angular testing environment + | ├──karma.conf.js * karma config for our unit tests + | ├──protractor.conf.js * protractor config for our end-to-end tests + │ ├──webpack.common.js * common tasks for webpack build process shared for dev and prod + │ ├──webpack.dev.js * our development webpack config + │ ├──webpack.prod.js * our production webpack config + │ └──webpack.test.js * our testing webpack config + │ + ├──src/ * our source files that will be compiled to javascript + | ├──main.browser.ts * our entry file for our browser environment + │ │ + | ├──index.html * Index.html: where we generate our index page │ │ - | ├──vendor.ts * our vendor file + | ├──polyfills.ts * our polyfills file │ │ - │ ├──app/ * WebApp: folder - │ │ ├──app.spec.ts * a simple test of components in app.ts - │ │ ├──app.ts * App.ts: a simple version of our App component components - │ │ └──bootstrap.ts * entry file for app + │ ├──app/ * WebApp: folder + │ │ ├──app.component.spec.ts * a simple test of components in app.component.ts + │ │ ├──app.e2e.ts * a simple end-to-end test for / + │ │ └──app.component.ts * a simple version of our App component components │ │ - │ └──public/ * static assets are served here - │ ├──favicon.ico * replace me with your own favicon.ico - │ ├──service-worker.js * ignore this. Web App service worker that's not complete yet - │ ├──robots.txt * for search engines to crawl your website - │ ├──human.txt * for humans to know who the developers are - │ │ - │ └──index.html * Index.html: where we place our script tags + │ └──assets/ * static assets are served here + │ ├──icon/ * our list of icons from www.favicon-generator.org + │ ├──service-worker.js * ignore this. Web App service worker that's not complete yet + │ ├──robots.txt * for search engines to crawl your website + │ └──humans.txt * for humans to know who the developers are │ - ├──test/ * this is our global unit tests and end-to-end tests │ - ├──spec-bundle.js * ignore this magic that sets up our angular 2 testing environment - ├──karma.config.js * karma config for our unit tests - ├──protractor.config.js * protractor config for our end-to-end tests - ├──tsconfig.json * config that webpack uses for typescript - ├──typings.json * our typings manager - ├──package.json * what npm uses to manage it's dependencies - └──webpack.config.js * our webpack config + ├──tslint.json * typescript lint config + ├──typedoc.json * typescript documentation generator + ├──tsconfig.json * typescript config used outside webpack + ├──tsconfig.webpack.json * config that webpack uses for typescript + ├──package.json * what npm uses to manage its dependencies + └──webpack.config.js * webpack main configuration file + ``` # Getting Started ## Dependencies What you need to run this app: * `node` and `npm` (`brew install node`) -* Ensure you're running the latest versions Node `v4.1.x`+ and NPM `2.14.x`+ +* Ensure you're running the latest versions Node `v8.x.x`+ (or `v9.x.x`) and NPM `5.x.x`+ + +> If you have `nvm` installed, which is highly recommended (`brew install nvm`) you can do a `nvm install --lts && nvm use` in `$` to run with the latest Node LTS. You can also have this `zsh` done for you [automatically](https://github.com/creationix/nvm#calling-nvm-use-automatically-in-a-directory-with-a-nvmrc-file) Once you have those, you should install these globals with `npm install --global`: * `webpack` (`npm install --global webpack`) * `webpack-dev-server` (`npm install --global webpack-dev-server`) * `karma` (`npm install --global karma-cli`) * `protractor` (`npm install --global protractor`) -* `typings` (`npm install --global typings`) * `typescript` (`npm install --global typescript`) +* `tslint` (`npm install --global tslint@4.5.1`) ## Installing * `fork` this repo * `clone` your fork -* `npm install` to install all dependencies -* `typings install` to install necessary typings +* `npm install webpack-dev-server rimraf webpack -g` to install required global dependencies +* `npm install` to install all dependencies or `yarn` * `npm run server` to start the dev server in another tab ## Running the app -After you have installed all dependencies you can now run the app. Run `npm run server` to start a local server using `webpack-dev-server` which will watch, build (in-memory), and reload for you. The port will be displayed to you as `http://localhost:3000` (or if you prefer IPv6, if you're using `express` server, then it's `http://[::1]:3000/`). +After you have installed all dependencies you can now run the app. Run `npm run server` to start a local server using `webpack-dev-server` which will watch, build (in-memory), and reload for you. The port will be displayed to you as `http://0.0.0.0:3000` (or if you prefer IPv6, if you're using `express` server, then it's `http://[::1]:3000/`). ### server ```bash -npm run server # or either webpack-dev-server +# development +npm run server +# production +npm run build:prod +npm run server:prod ``` ## Other commands +## the following commands with npm can be used with yarn as well ### build files ```bash -npm run build +# development +npm run build:dev +# production (jit) +npm run build:prod +# AoT +npm run build:aot +``` + +### hot module replacement +```bash +npm run server:dev:hmr ``` ### watch and build files @@ -144,22 +188,64 @@ npm run build npm run watch ``` -### run tests +### run unit tests ```bash npm run test ``` -### run webdriver (for end-to-end) +### watch and run our tests ```bash -npm run webdriver-start +npm run watch:test ``` ### run end-to-end tests ```bash -# make sure you have webdriver running and a sever for the client app +# update Webdriver (optional, done automatically by postinstall script) +npm run webdriver:update +# this will start a test server and launch Protractor npm run e2e ``` +### continuous integration (run unit tests and e2e tests together) +```bash +# this will test both your JIT and AoT builds +npm run ci +``` + +### run Protractor's elementExplorer (for end-to-end) +```bash +npm run e2e:live +``` + +### build Docker +```bash +npm run build:docker +``` + +# Configuration +Configuration files live in `config/` we are currently using webpack, karma, and protractor for different stages of your application + +# AoT Don'ts +The following are some things that will make AoT compile fail. + +- Don’t use require statements for your templates or styles, use styleUrls and templateUrls, the angular2-template-loader plugin will change it to require at build time. +- Don’t use default exports. +- Don’t use `form.controls.controlName`, use `form.get(‘controlName’)` +- Don’t use `control.errors?.someError`, use `control.hasError(‘someError’)` +- Don’t use functions in your providers, routes or declarations, export a function and then reference that function name +- @Inputs, @Outputs, View or Content Child(ren), Hostbindings, and any field you use from the template or annotate for Angular should be public + +For more detailed guide on AoT's Do's and Don'ts refer to https://github.com/rangle/angular-2-aot-sandbox + +# External Stylesheets +Any stylesheets (Sass or CSS) placed in the `src/styles` directory and imported into your project will automatically be compiled into an external `.css` and embedded in your production builds. + +For example to use Bootstrap as an external stylesheet: +1) Create a `styles.scss` file (name doesn't matter) in the `src/styles` directory. +2) `npm install` the version of Bootstrap you want. +3) In `styles.scss` add `@import '~bootstrap/scss/bootstrap.scss';` +4) In `src/app/app.module.ts` add underneath the other import statements: `import '../styles/styles.scss';` + # Contributing You can include more examples as components but they must introduce a new concept such as `Home` component (separate folders), and Todo (services). I'll accept pretty much everything so feel free to open a Pull-Request @@ -167,7 +253,7 @@ You can include more examples as components but they must introduce a new concep > To take full advantage of TypeScript with autocomplete you would have to install it globally and use an editor with the correct TypeScript plugins. ## Use latest TypeScript compiler -TypeScript 1.7.x includes everything you need. Make sure to upgrade, even if you installed TypeScript previously. +TypeScript 2.7.x includes everything you need. Make sure to upgrade, even if you installed TypeScript previously. ``` npm install --global typescript @@ -177,57 +263,245 @@ npm install --global typescript We have good experience using these editors: * [Visual Studio Code](https://code.visualstudio.com/) -* [Webstorm 10](https://www.jetbrains.com/webstorm/download/) +* [Webstorm 2018.1](https://www.jetbrains.com/webstorm/download/) * [Atom](https://atom.io/) with [TypeScript plugin](https://atom.io/packages/atom-typescript) * [Sublime Text](http://www.sublimetext.com/3) with [Typescript-Sublime-Plugin](https://github.com/Microsoft/Typescript-Sublime-plugin#installation) +### Visual Studio Code + Debugger for Chrome +> Install [Debugger for Chrome](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) and see docs for instructions to launch Chrome + +The included `.vscode` automatically connects to the webpack development server on port `3000`. + +# Types +> When you include a module that doesn't include Type Definitions inside of the module you can include external Type Definitions with @types + +i.e, to have youtube api support, run this command in terminal: +```shell +npm i @types/youtube @types/gapi @types/gapi.youtube +``` +In some cases where your code editor doesn't support Typescript 2 yet or these types weren't listed in ```tsconfig.json```, add these to **"src/custom-typings.d.ts"** to make peace with the compile check: +```es6 +import '@types/gapi.youtube'; +import '@types/gapi'; +import '@types/youtube'; +``` + +## Custom Type Definitions +When including 3rd party modules you also need to include the type definition for the module +if they don't provide one within the module. You can try to install it with @types + +``` +npm install @types/node +npm install @types/lodash +``` + +If you can't find the type definition in the registry we can make an ambient definition in +this file for now. For example + +```typescript +declare module "my-module" { + export function doesSomething(value: string): string; +} +``` + + +If you're prototyping and you will fix the types later you can also declare it as type any + +```typescript +declare var assert: any; +declare var _: any; +declare var $: any; +``` + +If you're importing a module that uses Node.js modules which are CommonJS you need to import as + +```typescript +import * as _ from 'lodash'; +``` + + # Frequently asked questions -* What's the current browser support for Angular 2 Alpha? - * Please view the updated list of [browser support for Angular 2](https://github.com/angularclass/awesome-angular2#current-browser-support-for-angular-2) +* What's the current browser support for Angular? + * Please view the updated list of [browser support for Angular](https://github.com/gdi2290/awesome-angular#current-browser-support-for-angular) * Why is my service, aka provider, is not injecting parameter correctly? - * Please use `@Injectable()` for your service for typescript to correctly attach the metadata (this is a typescript beta problem) -* How do I run protractor with node 0.12.x? - * please check out this repo to use the old version of protractor https://github.com/AngularClass/angular2-webpack-starter/pull/146/files + * Please use `@Injectable()` for your service for typescript to correctly attach the metadata (this is a TypeScript problem) * Where do I write my tests? - * You can write your tests anywhere you like in the `/src` directory next to your components or in the `test/` folder -* Is Angular 2 production ready yet? - * No, please visit [Is Angular 2 Ready Yet?](http://splintercode.github.io/is-angular-2-ready/) website. + * You can write your tests next to your component files. See [`/src/app/home/home.component.spec.ts`](/src/app/home/home.component.spec.ts) * How do I start the app when I get `EACCES` and `EADDRINUSE` errors? - * The `EADDRINUSE` error means the port `3000` is currently being used and `EACCES` is lack of permission for webpack to build files to `./__build__/` - + * The `EADDRINUSE` error means the port `3000` is currently being used and `EACCES` is lack of permission for webpack to build files to `./dist/` +* How to use `sass` for css? + * * `loaders: ['raw-loader','sass-loader']` and `@Component({ styleUrls: ['./filename.scss'] })` see Wiki page [How to include SCSS in components](https://github.com/gdi2290/angular-starter/wiki/How-to-include-SCSS-in-components), or issue [#136](https://github.com/gdi2290/angular-starter/issues/136) for more information. +* How do I test a Service? + * See issue [#130](https://github.com/gdi2290/angular-starter/issues/130#issuecomment-158872648) +* How do I add `vscode-chrome-debug` support? + * The VS Code chrome debug extension support can be done via `launch.json` see issue [#144](https://github.com/gdi2290/angular-starter/issues/144#issuecomment-164063790) +* How do I make the repo work in a virtual machine? + * You need to use `0.0.0.0` so revert these changes [#205](https://github.com/gdi2290/angular-starter/pull/205/files) +* What are the naming conventions for Angular? + * please see issue [#185](https://github.com/gdi2290/angular-starter/issues/185) and PR [196](https://github.com/gdi2290/angular-starter/pull/196) +* How do I include bootstrap or jQuery? + * please see issue [#215](https://github.com/gdi2290/angular-starter/issues/215) and [#214](https://github.com/gdi2290/angular-starter/issues/214#event-511768416) +* How do I async load a component? + * see wiki [How-do-I-async-load-a-component-with-AsyncRoute](https://github.com/gdi2290/angular-starter/wiki/How-do-I-async-load-a-component-with-AsyncRoute) +* Error: Cannot find module 'tapable' + * Remove `node_modules/` and run `npm cache clean` then `npm install` +* How do I turn on Hot Module Replacement + * Run `npm run server:dev:hmr` +* `RangeError: Maximum call stack size exceeded` + * This is a problem with minifying Angular and it's recent JIT templates. If you set `mangle` to `false` then you should be good. +* Why is the size of my app larger in development? + * We are using inline source-maps and hot module replacement which will increase the bundle size. +* If you're in China + * check out https://github.com/cnpm/cnpm +* node-pre-gyp ERR in npm install (Windows) + * often happens when you're behind proxy and proxy wasn't configured in the npm as it tries to download binary package from the github and if it fails to do so, it will try to compile node-sass from the source codes + * install Python3 x86 +* `Error:Error: Parse tsconfig error [{"messageText":"Unknown compiler option 'lib'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'strictNullChecks'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'baseUrl'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'paths'.","category":1,"code":5023},{"messageText":"Unknown compiler option 'types'.","category":1,"code":5023}]` + * remove `node_modules/typescript` and run `npm install typescript@beta`. This repo now uses ts 2.0 +* "There are multiple modules with names that only differ in casing" + * change `c:\[path to angular-starter]` to `C:\[path to angular-starter]` see [926#issuecomment-245223547](https://github.com/gdi2290/angular-starter/issues/926#issuecomment-245223547) # Support, Questions, or Feedback -> Contact us anytime for anything about this repo or Angular 2 - -* [Chat: AngularClass.slack](http://angularclass.com/member-join/) -* [Twitter: @AngularClass](https://twitter.com/AngularClass) -* [Gitter: AngularClass/angular2-webpack-starter](https://gitter.im/angularclass/angular2-webpack-starter) - - -# Other Seed/Starter/Example Repos -* [angular2-webpack-starter (AngularClass)](https://github.com/angularclass/angular2-webpack-starter) - * Client/Server, Webpack, TypeScript, TSD, Protractor, Karma, Jasmine -* [ng2-play (Pawel Kozlowski)](https://github.com/pkozlowski-opensource/ng2-play) - * Client only, Minimalist, SystemJS, Gulp, TypeScript -* [angular2-seed (Minko Gechev)](https://github.com/mgechev/angular2-seed) - * Client only, SystemJS, Gulp, TypeScript, TSD, Versioned, Env Dev/Prod -* [ng2-lab (Roland Groza)](https://github.com/rolandjitsu/ng2-lab) - * Client only, ES6, TypeScript, Firebase, Gulp, Ci, TSD, TSLint -* [ng2-jspm-seed (Rob Wormald)](https://github.com/robwormald/ng2-jspm-seed) - * Client only, TypeScript, TSD, Gulp, JSPM, Minimalist -* [babel-angular2-app (Shuhei Kagawa)](https://github.com/shuhei/babel-angular2-app) - * Client only, Minimalist, Babel, ES6+, browserify +> Contact us anytime for anything about this repo or Angular -___ +`@PatrickJS__` on twitter + +# Deployment -enjoy — **AngularClass** +## Docker -

+To run project you only need host machine with **operating system** with installed **git** (to clone this repo) +and [docker](https://www.docker.com/) and thats all - any other software is not needed +(other software like node.js etc. will be automatically downloaded and installed inside docker container during build step based on dockerfile). -[![AngularClass](https://cloud.githubusercontent.com/assets/1016365/9863770/cb0620fc-5af7-11e5-89df-d4b0b2cdfc43.png "Angular Class")](https://angularclass.com) -##[AngularClass](https://angularclass.com) -> Learn AngularJS, Angular 2, and Modern Web Development from the best. -> Looking for corporate Angular training, want to host us, or Angular consulting? patrick@angularclass.com +### Install docker + +#### MacOS: + +`brew cask install docker` + +And run docker by Mac bottom menu> launchpad > docker (on first run docker will ask you about password) + +#### Ubuntu: + +``` +sudo apt-get update +sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D +sudo apt-add-repository 'deb https://apt.dockerproject.org/repo ubuntu-xenial main' +sudo apt-get update +apt-cache policy docker-engine +sudo apt-get install -y docker-engine +sudo systemctl status docker # test: should be ‘active’ +``` +And add your user to docker group (to avoid `sudo` before using `docker` command in future): +``` +sudo usermod -aG docker $(whoami) +``` +and logout and login again. + +### Build image + +Because *node.js* is big memory consumer you need 1-2GB RAM or virtual memory to build docker image +(it was successfully tested on machine with 512MB RAM + 2GB virtual memory - building process take 7min) + +Go to main project folder. To build image type: + +`docker build -t angular-starter .` + +The **angular-starter** name used in above commands is only example image name. +To remove intermediate images created by docker on build process, type: + +`docker rmi -f $(docker images -f "dangling=true" -q)` + +### Run image + +To run created docker image on [localhost:8080](localhost:8080) type (parameter `-p 8080:80` is host:container port mapping) + +`docker run --name angular-starter -p 8080:80 angular-starter &` + +And that's all, you can open browser and go to [localhost:8080](localhost:8080). + +### Build and Run image using docker-compose + +To create and run docker image on [localhost:8080](localhost:8080) as part of large project you may use **docker-compose**. Type + +`docker-compose up` + +And that's all, you can open browser and go to [localhost:8080](localhost:8080). + + +### Run image on sub-domain + +If you want to run image as virtual-host on sub-domain you must setup [proxy](https://github.com/jwilder/nginx-proxy). You should install proxy and set sub-domain in this way: + + ``` + docker run -d -p 80:80 --name nginx-proxy -v /var/run/docker.sock:/tmp/docker.sock:ro jwilder/nginx-proxy:alpine + ``` + + And in your `/etc/hosts` file (linux) add line: `127.0.0.1 angular-starter.your-domain.com` or in yor hosting add + following DNS record (wildchar `*` is handy because when you add new sub-domain in future, you don't need to touch/add any DNS record) + + ``` + Type: CNAME + Hostname: *.your-domain.com + Direct to: your-domain.com + TTL(sec): 43200 + ``` + +And now you are ready to run image on subdomain by: + +``` +docker run -e VIRTUAL_HOST=angular-starter.your-domain.com --name angular-starter angular-starter & +``` + +### Login into docker container + +`docker exec -t -i angular-starter /bin/bash` + +## Netlify + +You can quickly create a free site to get started using this +starter kit in production on [Netlify](https://www.netlify.com/): + +[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/AngularClass/angular-starter) + +### Optional Integration with SonarQube (for continous code quality) +Assuming you have SonarQube 5.5.6 (LTS) installed +* Setup SonarQube with the [Sonar Typescript plugin](https://github.com/Pablissimo/SonarTsPlugin#installation) and the Generic Test Coverage plugin https://docs.sonarqube.org/display/PLUG/Generic+Test+Coverage +* Install sonar-scanner globally +```bash +npm install --global sonar-scanner +``` +* Install the [Karma plugin for sonarqube](https://www.npmjs.com/package/karma-sonarqube-unit-reporter) as a dev dependency +```bash +npm install karma-sonarqube-unit-reporter --save-dev +``` +* Sonar Host URL configuration: +Update [`sonar-project.properties`](sonar-project.properties) file for the property `sonar.host.url` to point to your SonarQube server. By default this assumes that the SonarQube server is running locally using the default port +``` +sonar.host.url= +``` +* Run the unit tests with sonar reporter enabled +```bash +npm run test:sonar +``` +* The test results collected in the results folder in the sonar compatible format +* Push results to SonarCube +```bash +sonar-scanner +``` +* If working with SonarQube 6.x it supports [Generic Test Data](https://docs.sonarqube.org/display/SONAR/Generic+Test+Data) +* Modify the [karma.conf.js](config/karma.config.js) to set the appropriate version of the sonarQube +```es6 +sonarQubeUnitReporter: { + sonarQubeVersion: '6.x', +} +``` +___ + +enjoy — [**PatrickJS**](https://patrickjs.com) + +___ # License [MIT](/LICENSE) diff --git a/config/build-utils.js b/config/build-utils.js new file mode 100644 index 0000000000..6e94e92ff9 --- /dev/null +++ b/config/build-utils.js @@ -0,0 +1,131 @@ +const ts = require('typescript'); +const path = require('path'); +const fs = require('fs'); +const helpers = require('./helpers'); + +const APP_COMMON_CONFIG = require('./config.common.json'); + +const DEFAULT_METADATA = { + title: APP_COMMON_CONFIG.title, + description: APP_COMMON_CONFIG.description, + baseUrl: '/', + isDevServer: helpers.isWebpackDevServer(), + HMR: helpers.hasProcessFlag('hot'), + AOT: process.env.BUILD_AOT || helpers.hasNpmFlag('aot'), + E2E: !!process.env.BUILD_E2E, + WATCH: helpers.hasProcessFlag('watch'), + tsConfigPath: 'tsconfig.webpack.json', + + /** + * This suffix is added to the environment.ts file, if not set the default environment file is loaded (development) + * To disable environment files set this to null + */ + envFileSuffix: '' +}; + +function supportES2015(tsConfigPath) { + if (!supportES2015.hasOwnProperty('supportES2015')) { + const tsTarget = readTsConfig(tsConfigPath).options.target; + supportES2015['supportES2015'] = tsTarget !== ts.ScriptTarget.ES3 && tsTarget !== ts.ScriptTarget.ES5; + } + return supportES2015['supportES2015']; +} + +function readTsConfig(tsConfigPath) { + const configResult = ts.readConfigFile(tsConfigPath, ts.sys.readFile); + return ts.parseJsonConfigFileContent(configResult.config, ts.sys, + path.dirname(tsConfigPath), undefined, tsConfigPath); +} + +function getEnvFile(suffix) { + if (suffix && suffix[0] !== '.') { + suffix = '.' + suffix; + } + + if (suffix === null) { + return; + } + + let fileName = helpers.root(`src/environments/environment${suffix}.ts`); + if (fs.existsSync(fileName)) { + return fileName; + } else if (fs.existsSync(fileName = helpers.root('src/environments/environment.ts'))) { + console.warn(`Could not find environment file with suffix ${suffix}, loading default environment file`); + return fileName; + } else { + throw new Error('Environment file not found.') + } +} + +/** + * Read the tsconfig to determine if we should prefer ES2015 modules. + * Load rxjs path aliases. + * https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#build-and-treeshaking + * @param supportES2015 Set to true when the output of typescript is >= ES6 + */ +function rxjsAlias(supportES2015) { + try { + const rxjsPathMappingImport = supportES2015 ? 'rxjs/_esm2015/path-mapping' : 'rxjs/_esm5/path-mapping'; + const rxPaths = require(rxjsPathMappingImport); + return rxPaths(helpers.root('node_modules')); + } catch (e) { + return {}; + } +} + +function ngcWebpackSetup(prod, metadata) { + if (!metadata) { + metadata = DEFAULT_METADATA; + } + + const buildOptimizer = prod && metadata.AOT; + const sourceMap = true; // TODO: apply based on tsconfig value? + const ngcWebpackPluginOptions = { + skipCodeGeneration: !metadata.AOT, + sourceMap + }; + + const environment = getEnvFile(metadata.envFileSuffix); + if (environment) { + ngcWebpackPluginOptions.hostReplacementPaths = { + [helpers.root('src/environments/environment.ts')]: environment + } + } + + if (!prod && metadata.WATCH) { + // Force commonjs module format for TS on dev watch builds. + ngcWebpackPluginOptions.compilerOptions = { + module: 'commonjs' + }; + } + + const buildOptimizerLoader = { + loader: '@angular-devkit/build-optimizer/webpack-loader', + options: { + sourceMap + } + }; + + const loaders = [ + { + test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, + use: buildOptimizer ? [ buildOptimizerLoader, '@ngtools/webpack' ] : [ '@ngtools/webpack' ] + }, + ...buildOptimizer + ? [ { test: /\.js$/, use: [ buildOptimizerLoader ] } ] + : [] + ]; + + return { + loaders, + plugin: ngcWebpackPluginOptions + }; +} + + +exports.DEFAULT_METADATA = DEFAULT_METADATA; +exports.supportES2015 = supportES2015; +exports.readTsConfig = readTsConfig; +exports.getEnvFile = getEnvFile; +exports.rxjsAlias = rxjsAlias; +exports.ngcWebpackSetup = ngcWebpackSetup; diff --git a/config/config.common.json b/config/config.common.json new file mode 100644 index 0000000000..5ab0d19606 --- /dev/null +++ b/config/config.common.json @@ -0,0 +1,4 @@ +{ + "title": "Angular Starter by @gdi2290 from @TipeIO", + "description": "An Angular starter kit featuring Angular 5, Ahead of Time Compile, Router, Forms, Http, Services, Tests, E2E), Karma, Protractor, Jasmine, Istanbul, TypeScript, @types, TsLint, Codelyzer, Hot Module Replacement, and Webpack by Tipe.io" +} diff --git a/config/config.dev.json b/config/config.dev.json new file mode 100644 index 0000000000..2f8218edd0 --- /dev/null +++ b/config/config.dev.json @@ -0,0 +1,10 @@ +{ + "firebase": { + "apiKey": "", + "authDomain": "XXXXXX.firebaseapp.com", + "databaseURL": "https://XXXXXX.firebaseio.com", + "projectId": "XXXXXX", + "storageBucket": "XXXXXX.appspot.com", + "messagingSenderId": "000000000000" + } +} diff --git a/config/config.prod.json b/config/config.prod.json new file mode 100644 index 0000000000..1ac6fc2768 --- /dev/null +++ b/config/config.prod.json @@ -0,0 +1,11 @@ +{ + "firebase": { + "apiKey": "", + "authDomain": "XXXXXX.firebaseapp.com", + "databaseURL": "https://XXXXXX.firebaseio.com", + "projectId": "XXXXXX", + "storageBucket": "XXXXXX.appspot.com", + "messagingSenderId": "000000000000" + }, + "gtmKey" : "GTM-XXXXXXX" +} diff --git a/config/empty.js b/config/empty.js new file mode 100644 index 0000000000..6bc5423e97 --- /dev/null +++ b/config/empty.js @@ -0,0 +1,11 @@ +module.exports = { + hmrModule: function(ngmodule) { + return ngmodule; + }, + NgProbeToken: {}, + HmrState: function() {}, + _createConditionalRootRenderer: function(rootRenderer, extraTokens, coreTokens) { + return rootRenderer; + }, + __platform_browser_private__: {} +}; diff --git a/config/github-deploy/index.js b/config/github-deploy/index.js new file mode 100644 index 0000000000..0367f712d6 --- /dev/null +++ b/config/github-deploy/index.js @@ -0,0 +1,95 @@ +const execSync = require('child_process').execSync; +/** + * Used to merge webpack configs. + */ +const webpackMerge = require('webpack-merge'); // used to merge webpack configs +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const helpers = require('../helpers'); + +const REPO_NAME_RE = /Push {2}URL: ((git@github\.com:)|(https:\/\/github\.com\/)).+\/(.+)\.git/; + +function getWebpackConfigModule(options) { + if (options.githubDev) { + return require('../webpack.dev.js'); + } else if (options.githubProd) { + return require('../webpack.prod.js'); + } else { + throw new Error('Invalid compile option.'); + } +} + +function getRepoName(remoteName) { + remoteName = remoteName || 'origin'; + + var stdout = execSync('git remote show ' + remoteName), + match = REPO_NAME_RE.exec(stdout); + + if (!match) { + throw new Error('Could not find a repository on remote ' + remoteName); + } else { + return match[4]; + } +} + +function stripTrailing(str, char) { + + if (str[0] === char) { + str = str.substr(1); + } + + if (str.substr(-1) === char) { + str = str.substr(0, str.length - 1); + } + + return str; +} + +/** + * Given a string remove trailing slashes and adds 1 slash at the end of the string. + * + * Example: + * safeUrl('/value/') + * // 'value/' + * + * @param url + * @returns {string} + */ +function safeUrl(url) { + const stripped = stripTrailing(url || '', '/'); + return stripped ? stripped + '/' : ''; +} + +function replaceHtmlWebpackPlugin(plugins, ghRepoName) { + for (var i=0; i tags for 'apple-touch-icon' (AKA Web Clips). + */ + { rel: 'apple-touch-icon', sizes: '57x57', href: '/assets/icon/apple-icon-57x57.png' }, + { rel: 'apple-touch-icon', sizes: '60x60', href: '/assets/icon/apple-icon-60x60.png' }, + { rel: 'apple-touch-icon', sizes: '72x72', href: '/assets/icon/apple-icon-72x72.png' }, + { rel: 'apple-touch-icon', sizes: '76x76', href: '/assets/icon/apple-icon-76x76.png' }, + { rel: 'apple-touch-icon', sizes: '114x114', href: '/assets/icon/apple-icon-114x114.png' }, + { rel: 'apple-touch-icon', sizes: '120x120', href: '/assets/icon/apple-icon-120x120.png' }, + { rel: 'apple-touch-icon', sizes: '144x144', href: '/assets/icon/apple-icon-144x144.png' }, + { rel: 'apple-touch-icon', sizes: '152x152', href: '/assets/icon/apple-icon-152x152.png' }, + { rel: 'apple-touch-icon', sizes: '180x180', href: '/assets/icon/apple-icon-180x180.png' }, + + /** + * tags for android web app icons + */ + { rel: 'icon', type: 'image/png', sizes: '192x192', href: '/assets/icon/android-icon-192x192.png' }, + + /** + * tags for favicons + */ + { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/assets/icon/favicon-32x32.png' }, + { rel: 'icon', type: 'image/png', sizes: '96x96', href: '/assets/icon/favicon-96x96.png' }, + { rel: 'icon', type: 'image/png', sizes: '16x16', href: '/assets/icon/favicon-16x16.png' }, + + /** + * tags for a Web App Manifest + */ + { rel: 'manifest', href: '/assets/manifest.json' } + ], + meta: [ + { name: 'msapplication-TileColor', content: '#00bcd4' }, + { name: 'msapplication-TileImage', content: '/assets/icon/ms-icon-144x144.png', '=content': true }, + { name: 'theme-color', content: '#00bcd4' } + ] +}; diff --git a/config/helpers.js b/config/helpers.js new file mode 100644 index 0000000000..aae072eafc --- /dev/null +++ b/config/helpers.js @@ -0,0 +1,31 @@ +/** + * @author: tipe.io + */ +const path = require('path'); + +const EVENT = process.env.npm_lifecycle_event || ''; + +/** + * Helper functions. + */ +var ROOT = path.resolve(__dirname, '..'); + +function hasProcessFlag(flag) { + return process.argv.join('').indexOf(flag) > -1; +} + +function hasNpmFlag(flag) { + return EVENT.includes(flag); +} + +function isWebpackDevServer() { + return process.argv[1] && !! (/webpack-dev-server/.exec(process.argv[1])); +} + + +var root = path.join.bind(path, ROOT); + +exports.hasProcessFlag = hasProcessFlag; +exports.hasNpmFlag = hasNpmFlag; +exports.isWebpackDevServer = isWebpackDevServer; +exports.root = root; diff --git a/config/html-elements-plugin/index.js b/config/html-elements-plugin/index.js new file mode 100644 index 0000000000..c4be4909eb --- /dev/null +++ b/config/html-elements-plugin/index.js @@ -0,0 +1,122 @@ +const RE_ENDS_WITH_BS = /\/$/; + +/** + * Create an HTML tag with attributes from a map. + * + * Example: + * createTag('link', { rel: "manifest", href: "/assets/manifest.json" }) + * // + * @param tagName The name of the tag + * @param attrMap A Map of attribute names (keys) and their values. + * @param publicPath a path to add to eh start of static asset url + * @returns {string} + */ +function createTag(tagName, attrMap, publicPath) { + publicPath = publicPath || ''; + + /** + * Add trailing slash if we have a publicPath and it doesn't have one. + */ + if (publicPath && !RE_ENDS_WITH_BS.test(publicPath)) { + publicPath += '/'; + } + + const attributes = Object.getOwnPropertyNames(attrMap) + .filter(function (name) { + return name[0] !== '='; + }) + .map(function (name) { + var value = attrMap[name]; + + if (publicPath) { + /** + * Check if we have explicit instruction, use it if so (e.g: =herf: false) + * if no instruction, use public path if it's href attribute. + */ + const usePublicPath = attrMap.hasOwnProperty('=' + name) ? !!attrMap['=' + name] : name === 'href'; + + if (usePublicPath) { + /** + * Remove a starting trailing slash if the value has one so we wont have // + */ + value = publicPath + (value[0] === '/' ? value.substr(1) : value); + } + } + + return `${name}="${value}"`; + }); + + const closingTag = tagName === 'script' ? '' : ''; + + return `<${tagName} ${attributes.join(' ')}>${closingTag}`; +} + +/** + * Returns a string representing all html elements defined in a data source. + * + * Example: + * + * const ds = { + * link: [ + * { rel: "apple-touch-icon", sizes: "57x57", href: "/assets/icon/apple-icon-57x57.png" } + * ], + * meta: [ + * { name: "msapplication-TileColor", content: "#00bcd4" } + * ] + * } + * + * getHeadTags(ds); + * // "" + * "" + * + * @returns {string} + */ +function getHtmlElementString(dataSource, publicPath) { + return Object.getOwnPropertyNames(dataSource) + .map(function (name) { + if (Array.isArray(dataSource[name])) { + return dataSource[name].map(function (attrs) { + return createTag(name, attrs, publicPath); + }); + } else { + return [createTag(name, dataSource[name], publicPath)]; + } + }) + .reduce(function (arr, curr) { + return arr.concat(curr); + }, []) + .join('\n\t'); +} + +class HtmlElementsPlugin { + constructor(locations) { + this.locations = locations; + } + + /* istanbul ignore next: this would be integration tests */ + apply(compiler) { + compiler.hooks.compilation.tap('HtmlElementsPlugin', compilation => { + compilation.options.htmlElements = compilation.options.htmlElements || {}; + compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync('HtmlElementsPlugin', + (htmlPluginData, callback) => { + + const locations = this.locations; + if (locations) { + const publicPath = htmlPluginData.assets.publicPath; + + Object.getOwnPropertyNames(locations).forEach(function (loc) { + + compilation.options.htmlElements[loc] = getHtmlElementString(locations[loc], publicPath); + }); + } + + // return htmlPluginData; + callback(null, htmlPluginData); + } + ); + }); + } +} + +module.exports = HtmlElementsPlugin; + diff --git a/config/karma.conf.js b/config/karma.conf.js new file mode 100644 index 0000000000..f83c39b604 --- /dev/null +++ b/config/karma.conf.js @@ -0,0 +1,178 @@ +/** + * @author: tipe.io + */ + +module.exports = function (config) { + const testWebpackConfig = require('./webpack.test.js')({ env: 'test' }); + + const configuration = { + + /** + * Base path that will be used to resolve all patterns (e.g. files, exclude). + */ + basePath: '', + + /** + * Frameworks to use + * + * available frameworks: https://npmjs.org/browse/keyword/karma-adapter + */ + frameworks: ['jasmine'], + + /** + * List of files to exclude. + */ + exclude: [], + + client: { + captureConsole: false + }, + + /** + * List of files / patterns to load in the browser + * + * we are building the test environment in ./spec-bundle.js + */ + files: [ + { pattern: './config/spec-bundle.js', watched: false }, + { pattern: './src/assets/**/*', watched: false, included: false, served: true, nocache: false } + ], + + /** + * By default all assets are served at http://localhost:[PORT]/base/ + */ + proxies: { + "/assets/": "/base/src/assets/" + }, + + /** + * Preprocess matching files before serving them to the browser + * available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + */ + preprocessors: { './config/spec-bundle.js': ['coverage', 'webpack', 'sourcemap'] }, + + /** + * Webpack Config at ./webpack.test.js + */ + webpack: testWebpackConfig, + + coverageReporter: { + type: 'in-memory' + }, + + remapCoverageReporter: { + 'text-summary': null, + json: './coverage/coverage.json', + html: './coverage/html' + }, + + /** + * Webpack please don't spam the console when running in karma! + */ + webpackMiddleware: { + /** + * webpack-dev-middleware configuration + * i.e. + */ + logLevel: 'warn', + /** + * and use stats to turn off verbose output + */ + stats: { + /** + * options i.e. + */ + chunks: false + } + }, + + /** + * Test results reporter to use + * + * possible values: 'dots', 'progress' + * available reporters: https://npmjs.org/browse/keyword/karma-reporter + */ + reporters: ['mocha', 'coverage', 'remap-coverage'], + + /** + * Web server port. + */ + port: 9876, + + /** + * enable / disable colors in the output (reporters and logs) + */ + colors: true, + + /** + * Level of logging + * possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + */ + logLevel: config.LOG_WARN, + + /** + * enable / disable watching file and executing tests whenever any file changes + */ + autoWatch: true, + + /** + * start these browsers + * available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + */ + browsers: [ + 'ChromeTravisCi' + ], + + customLaunchers: { + ChromeTravisCi: { + base: 'ChromeHeadless', + flags: ['--no-sandbox', '--disable-gpu'] + } + }, + + /** + * Continuous Integration mode + * if true, Karma captures browsers, runs the tests and exits + */ + singleRun: false, + + client: { + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + + /** + * For slower machines you may need to have a longer browser + * wait time . Uncomment the line below if required. + */ + // browserNoActivityTimeout: 30000 + + }; + + // Optional Sonar Qube Reporter + if (process.env.SONAR_QUBE) { + + // SonarQube reporter plugin configuration + configuration.sonarQubeUnitReporter = { + sonarQubeVersion: '5.x', + outputFile: 'reports/ut_report.xml', + overrideTestDescription: true, + testPath: 'src/app', + testFilePattern: '.spec.ts', + useBrowserName: false + }; + + // Additional lcov format required for + // sonarqube + configuration.remapCoverageReporter.lcovonly = './coverage/coverage.lcov'; + + configuration.reporters.push('sonarqubeUnit'); + } + + if (process.env.TRAVIS) { + configuration.browsers = [ + 'ChromeTravisCi' + ]; + } + + config.set(configuration); +}; diff --git a/config/nginx-custom.conf b/config/nginx-custom.conf new file mode 100644 index 0000000000..8e1dbe59d9 --- /dev/null +++ b/config/nginx-custom.conf @@ -0,0 +1,19 @@ +server { + listen 80; + + gzip on; + gzip_http_version 1.1; + gzip_disable "MSIE [1-6]\."; + gzip_min_length 1100; + gzip_vary on; + gzip_proxied expired no-cache no-store private auth; + gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript; + gzip_comp_level 5; + + root /usr/share/nginx/html; + + location / { + index index.html index.htm; + try_files $uri $uri/ /index.html =404; + } +} diff --git a/config/protractor.conf.js b/config/protractor.conf.js new file mode 100644 index 0000000000..e3cf3f9d03 --- /dev/null +++ b/config/protractor.conf.js @@ -0,0 +1,53 @@ +/** + * @author: tipe.io + */ + +require('ts-node/register'); +var helpers = require('./helpers'); + +exports.config = { + baseUrl: 'http://localhost:3000/', + + /** + * Use `npm run e2e` + */ + specs: [ + helpers.root('src/**/**.e2e.ts'), + helpers.root('src/**/*.e2e.ts') + ], + exclude: [], + + framework: 'jasmine', + + allScriptsTimeout: 11000, + + jasmineNodeOpts: { + showTiming: true, + showColors: true, + isVerbose: false, + includeStackTrace: false, + defaultTimeoutInterval: 40000 + }, + + directConnect: true, + capabilities: { + browserName: 'chrome', + chromeOptions: { + args: [ "--headless", "--disable-gpu", "--window-size=800x600", "--no-sandbox" ] + } + }, + + onPrepare: function() { + browser.ignoreSynchronization = true; + }, + + /** + * Angular 2 configuration + * + * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching + * `rootEl` + */ + useAllAngular2AppRoots: true, + + SELENIUM_PROMISE_MANAGER: false, +}; diff --git a/src/app/home/home.css b/config/resource-override.js similarity index 100% rename from src/app/home/home.css rename to config/resource-override.js diff --git a/config/spec-bundle.js b/config/spec-bundle.js new file mode 100644 index 0000000000..9906c2179e --- /dev/null +++ b/config/spec-bundle.js @@ -0,0 +1,58 @@ +/** + * @author: tipe.io + */ + +/** + * When testing with webpack and ES6, we have to do some extra + * things to get testing to work right. Because we are gonna write tests + * in ES6 too, we have to compile those as well. That's handled in + * karma.conf.js with the karma-webpack plugin. This is the entry + * file for webpack test. Just like webpack will create a bundle.js + * file for our client, when we run test, it will compile and bundle them + * all here! Crazy huh. So we need to do some setup + */ +Error.stackTraceLimit = Infinity; + +require('core-js/es6'); +require('core-js/es7/reflect'); + +require('zone.js/dist/zone'); +require('zone.js/dist/long-stack-trace-zone'); +require('zone.js/dist/proxy'); // since zone.js 0.6.15 +require('zone.js/dist/sync-test'); +require('zone.js/dist/jasmine-patch'); // put here since zone.js 0.6.14 +require('zone.js/dist/async-test'); +require('zone.js/dist/fake-async-test'); + +var testing = require('@angular/core/testing'); +var browser = require('@angular/platform-browser-dynamic/testing'); + +testing.TestBed.initTestEnvironment( + browser.BrowserDynamicTestingModule, + browser.platformBrowserDynamicTesting() +); + +/** + * Ok, this is kinda crazy. We can use the context method on + * require that webpack created in order to tell webpack + * what files we actually want to require or import. + * Below, context will be a function/object with file names as keys. + * Using that regex we are saying look in ../src then find + * any file that ends with spec.ts and get its path. By passing in true + * we say do this recursively + */ +var testContext = require.context('../src', true, /\.spec\.ts/); + +/** + * Get all the files, for each file, call the context function + * that will require the file and load it up here. Context will + * loop and require those spec files here + */ +function requireAll(requireContext) { + return requireContext.keys().map(requireContext); +} + +/** + * Requires and returns all modules that match + */ +var modules = requireAll(testContext); diff --git a/config/webpack.common.js b/config/webpack.common.js new file mode 100644 index 0000000000..23d6648a0a --- /dev/null +++ b/config/webpack.common.js @@ -0,0 +1,291 @@ +/** + * @author: tipe.io + */ + +const helpers = require('./helpers'); + +/** + * Webpack Plugins + * + * problem with copy-webpack-plugin + */ +const DefinePlugin = require('webpack/lib/DefinePlugin'); +const CopyWebpackPlugin = require('copy-webpack-plugin'); +const HtmlElementsPlugin = require('./html-elements-plugin'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const WebpackInlineManifestPlugin = require('webpack-inline-manifest-plugin'); +const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); +const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin; + +const buildUtils = require('./build-utils'); + +/** + * Webpack configuration + * + * See: https://webpack.js.org/configuration/ + */ +module.exports = function(options) { + const isProd = options.env === 'production'; + const APP_CONFIG = require(process.env.ANGULAR_CONF_FILE || (isProd ? './config.prod.json' : './config.dev.json')); + + const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, options.metadata || {}); + const GTM_API_KEY = process.env.GTM_API_KEY || APP_CONFIG.gtmKey; + + const ngcWebpackConfig = buildUtils.ngcWebpackSetup(isProd, METADATA); + const supportES2015 = buildUtils.supportES2015(METADATA.tsConfigPath); + + const entry = { + polyfills: './src/polyfills.browser.ts', + main: './src/main.browser.ts' + }; + + Object.assign(ngcWebpackConfig.plugin, { + tsConfigPath: METADATA.tsConfigPath, + mainPath: entry.main + }); + + return { + /** + * The entry point for the bundle + * Our Angular.js app + * + * See: https://webpack.js.org/configuration/entry-context/#entry + */ + entry: entry, + + /** + * Options affecting the resolving of modules. + * + * See: https://webpack.js.org/configuration/resolve/ + */ + resolve: { + mainFields: [...(supportES2015 ? ['es2015'] : []), 'browser', 'module', 'main'], + + /** + * An array of extensions that should be used to resolve modules. + * + * See: https://webpack.js.org/configuration/resolve/#resolve-extensions + */ + extensions: ['.ts', '.js', '.json'], + + /** + * An array of directory names to be resolved to the current directory + */ + modules: [helpers.root('src'), helpers.root('node_modules')], + + /** + * Add support for lettable operators. + * + * For existing codebase a refactor is required. + * All rxjs operator imports (e.g. `import 'rxjs/add/operator/map'` or `import { map } from `rxjs/operator/map'` + * must change to `import { map } from 'rxjs/operators'` (note that all operators are now under that import. + * Additionally some operators have changed to to JS keyword constraints (do => tap, catch => catchError) + * + * Remember to use the `pipe()` method to chain operators, this functinoally makes lettable operators similar to + * the old operators usage paradigm. + * + * For more details see: + * https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#build-and-treeshaking + * + * If you are not planning on refactoring your codebase (or not planning on using imports from `rxjs/operators` + * comment out this line. + * + * BE AWARE that not using lettable operators will probably result in significant payload added to your bundle. + */ + alias: buildUtils.rxjsAlias(supportES2015) + }, + + /** + * Options affecting the normal modules. + * + * See: https://webpack.js.org/configuration/module/ + */ + module: { + rules: [ + ...ngcWebpackConfig.loaders, + + /** + * To string and css loader support for *.css files (from Angular components) + * Returns file content as string + * + */ + { + test: /\.css$/, + use: ['to-string-loader', 'css-loader'], + exclude: [helpers.root('src', 'styles')] + }, + + /** + * To string and sass loader support for *.scss files (from Angular components) + * Returns compiled css content as string + * + */ + { + test: /\.scss$/, + use: ['to-string-loader', 'css-loader', 'sass-loader'], + exclude: [helpers.root('src', 'styles')] + }, + + /** + * Raw loader support for *.html + * Returns file content as string + * + * See: https://github.com/webpack/raw-loader + */ + { + test: /\.html$/, + use: 'raw-loader', + exclude: [helpers.root('src/index.html')] + }, + + /** + * File loader for supporting images, for example, in CSS files. + */ + { + test: /\.(jpg|png|gif)$/, + use: 'file-loader' + }, + + /* File loader for supporting fonts, for example, in CSS files. + */ + { + test: /\.(eot|woff2?|svg|ttf)([\?]?.*)$/, + use: 'file-loader' + } + ] + }, + + /** + * Add additional plugins to the compiler. + * + * See: https://webpack.js.org/configuration/plugins/ + */ + plugins: [ + /** + * Plugin: DefinePlugin + * Description: Define free variables. + * Useful for having development builds with debug logging or adding global constants. + * + * Environment helpers + * + * See: https://webpack.js.org/plugins/define-plugin/ + */ + // NOTE: when adding more properties make sure you include them in custom-typings.d.ts + new DefinePlugin({ + ENV: JSON.stringify(METADATA.ENV), + HMR: METADATA.HMR, + AOT: METADATA.AOT, + 'process.env.ENV': JSON.stringify(METADATA.ENV), + 'process.env.NODE_ENV': JSON.stringify(METADATA.ENV), + 'process.env.HMR': METADATA.HMR + // 'FIREBASE_CONFIG': JSON.stringify(APP_CONFIG.firebase), + }), + + /** + * Plugin: CopyWebpackPlugin + * Description: Copy files and directories in webpack. + * + * Copies project static assets. + * + * See: https://www.npmjs.com/package/copy-webpack-plugin + */ + new CopyWebpackPlugin( + [{ from: 'src/assets', to: 'assets' }, { from: 'src/meta' }], + isProd ? { ignore: ['mock-data/**/*'] } : undefined + ), + + /* + * Plugin: HtmlWebpackPlugin + * Description: Simplifies creation of HTML files to serve your webpack bundles. + * This is especially useful for webpack bundles that include a hash in the filename + * which changes every compilation. + * + * See: https://github.com/ampedandwired/html-webpack-plugin + */ + new HtmlWebpackPlugin({ + template: 'src/index.html', + title: METADATA.title, + chunksSortMode: function(a, b) { + const entryPoints = ['inline', 'polyfills', 'sw-register', 'styles', 'vendor', 'main']; + return entryPoints.indexOf(a.names[0]) - entryPoints.indexOf(b.names[0]); + }, + metadata: METADATA, + gtmKey: GTM_API_KEY, + inject: 'body', + xhtml: true, + minify: isProd + ? { + caseSensitive: true, + collapseWhitespace: true, + keepClosingSlash: true + } + : false + }), + + /** + * Plugin: ScriptExtHtmlWebpackPlugin + * Description: Enhances html-webpack-plugin functionality + * with different deployment options for your scripts including: + * + * See: https://github.com/numical/script-ext-html-webpack-plugin + */ + new ScriptExtHtmlWebpackPlugin({ + sync: /inline|polyfills|vendor/, + defaultAttribute: 'async', + preload: [/polyfills|vendor|main/], + prefetch: [/chunk/] + }), + + /** + * Plugin: HtmlElementsPlugin + * Description: Generate html tags based on javascript maps. + * + * If a publicPath is set in the webpack output configuration, it will be automatically added to + * href attributes, you can disable that by adding a "=href": false property. + * You can also enable it to other attribute by settings "=attName": true. + * + * The configuration supplied is map between a location (key) and an element definition object (value) + * The location (key) is then exported to the template under then htmlElements property in webpack configuration. + * + * Example: + * Adding this plugin configuration + * new HtmlElementsPlugin({ + * headTags: { ... } + * }) + * + * Means we can use it in the template like this: + * <%= webpackConfig.htmlElements.headTags %> + * + * Dependencies: HtmlWebpackPlugin + */ + new HtmlElementsPlugin({ + headTags: require('./head-config.common') + }), + + new AngularCompilerPlugin(ngcWebpackConfig.plugin), + + /** + * Plugin: WebpackInlineManifestPlugin + * Inline Webpack's manifest.js in index.html + * + * https://github.com/almothafar/webpack-inline-manifest-plugin + */ + new WebpackInlineManifestPlugin() + ], + + /** + * Include polyfills or mocks for various node stuff + * Description: Node configuration + * + * See: https://webpack.js.org/configuration/node/ + */ + node: { + global: true, + crypto: 'empty', + process: true, + module: false, + clearImmediate: false, + setImmediate: false + } + }; +}; diff --git a/config/webpack.dev.js b/config/webpack.dev.js new file mode 100755 index 0000000000..ecabb3a16f --- /dev/null +++ b/config/webpack.dev.js @@ -0,0 +1,164 @@ +/** + * @author: tipe.io + */ + +const helpers = require('./helpers'); +const buildUtils = require('./build-utils'); +const webpackMerge = require('webpack-merge'); // used to merge webpack configs +const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev + +/** + * Webpack Plugins + */ +const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); + +/** + * Webpack configuration + * + * See: https://webpack.js.org/configuration/ + */ +module.exports = function(options) { + const ENV = (process.env.ENV = process.env.NODE_ENV = 'development'); + const HOST = process.env.HOST || 'localhost'; + const PORT = process.env.PORT || 3000; + + const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, { + host: HOST, + port: PORT, + ENV: ENV, + HMR: helpers.hasProcessFlag('hot'), + PUBLIC: process.env.PUBLIC_DEV || HOST + ':' + PORT + }); + + return webpackMerge(commonConfig({ env: ENV, metadata: METADATA }), { + mode: 'development', + devtool: 'inline-source-map', + + /** + * Options affecting the output of the compilation. + * + * See: https://webpack.js.org/configuration/output/ + */ + output: { + /** + * The output directory as absolute path (required). + * + * See: https://webpack.js.org/configuration/output/#output-path + */ + path: helpers.root('dist'), + + /** + * Specifies the name of each output file on disk. + * IMPORTANT: You must not specify an absolute path here! + * + * See: https://webpack.js.org/configuration/output/#output-filename + */ + filename: '[name].bundle.js', + + /** + * The filename of the SourceMaps for the JavaScript files. + * They are inside the output.path directory. + * + * See: https://webpack.js.org/configuration/output/#output-sourcemapfilename + */ + sourceMapFilename: '[file].map', + + /** The filename of non-entry chunks as relative path + * inside the output.path directory. + * + * See: https://webpack.js.org/configuration/output/#output-chunkfilename + */ + chunkFilename: '[id].chunk.js', + + library: 'ac_[name]', + libraryTarget: 'var' + }, + + module: { + rules: [ + /** + * Css loader support for *.css files (styles directory only) + * Loads external css styles into the DOM, supports HMR + * + */ + { + test: /\.css$/, + use: ['style-loader', 'css-loader'], + include: [helpers.root('src', 'styles')] + }, + + /** + * Sass loader support for *.scss files (styles directory only) + * Loads external sass styles into the DOM, supports HMR + * + */ + { + test: /\.scss$/, + use: ['style-loader', 'css-loader', 'sass-loader'], + include: [helpers.root('src', 'styles')] + } + ] + }, + + plugins: [ + /** + * Plugin LoaderOptionsPlugin (experimental) + * + * See: https://gist.github.com/sokra/27b24881210b56bbaff7 + */ + new LoaderOptionsPlugin({ + debug: true, + options: {} + }) + ], + + /** + * Webpack Development Server configuration + * Description: The webpack-dev-server is a little node.js Express server. + * The server emits information about the compilation state to the client, + * which reacts to those events. + * + * See: https://webpack.js.org/configuration/dev-server/ + */ + devServer: { + port: METADATA.port, + host: METADATA.host, + hot: METADATA.HMR, + public: METADATA.PUBLIC, + historyApiFallback: true, + watchOptions: { + // if you're using Docker you may need this + // aggregateTimeout: 300, + // poll: 1000, + ignored: /node_modules/ + }, + /** + * Here you can access the Express app object and add your own custom middleware to it. + * + * See: https://webpack.js.org/configuration/dev-server/ + */ + setup: function(app) { + // For example, to define custom handlers for some paths: + // app.get('/some/path', function(req, res) { + // res.json({ custom: 'response' }); + // }); + } + }, + + /** + * Include polyfills or mocks for various node stuff + * Description: Node configuration + * + * See: https://webpack.js.org/configuration/node/ + */ + node: { + global: true, + crypto: 'empty', + process: true, + module: false, + clearImmediate: false, + setImmediate: false, + fs: 'empty' + } + }); +}; diff --git a/config/webpack.github-deploy.js b/config/webpack.github-deploy.js new file mode 100644 index 0000000000..7211e2b866 --- /dev/null +++ b/config/webpack.github-deploy.js @@ -0,0 +1,81 @@ +/** + * @author: tipe.io + */ +const fs = require('fs'); +const path = require('path'); +const helpers = require('./helpers'); +const ghDeploy = require('./github-deploy'); +const webpackMerge = require('webpack-merge'); // used to merge webpack configs + +/** + * Webpack Constants + */ +const GIT_REMOTE_NAME = 'origin'; +const COMMIT_MESSAGE = 'Updates'; +const GH_REPO_NAME = ghDeploy.getRepoName(GIT_REMOTE_NAME); + +module.exports = function(options) { + const webpackConfigFactory = ghDeploy.getWebpackConfigModule(options); // the settings that are common to prod and dev + const webpackConfig = webpackConfigFactory(options); + + /** + * Replace the instance of HtmlWebpackPlugin with an updated one. + */ + ghDeploy.replaceHtmlWebpackPlugin(webpackConfig.plugins, GH_REPO_NAME); + + return webpackMerge(webpackConfig, { + + output: { + /** + * The public path is set to the REPO name. + * + * `HtmlElementsPlugin` will add it to all resources url's created by it. + * `HtmlWebpackPlugin` will add it to all webpack bundels/chunks. + * + * In theory publicPath shouldn't be used since the browser should automatically prefix the + * `baseUrl` into all URLs, however this is not the case when the URL is absolute (start with /) + * + * It's important to prefix & suffix the repo name with a slash (/). + * Prefixing so every resource will be absolute (otherwise it will be url.com/repoName/repoName... + * Suffixing since chunks will not do it automatically (testes against about page) + */ + publicPath: '/' + GH_REPO_NAME + '/' + ghDeploy.safeUrl(webpackConfig.output.publicPath) + }, + + plugins: [ + function() { + this.plugin('done', function(stats) { + console.log('Starting deployment to GitHub.'); + + const logger = function(msg) { + console.log(msg); + }; + + const options = { + logger: logger, + remote: GIT_REMOTE_NAME, + message: COMMIT_MESSAGE, + dotfiles: true // for .nojekyll + }; + /** + * Since GitHub moved to Jekyll 3.3, their server ignores the "node_modules" and "vendors" folder by default. + * but, as of now, it also ignores "vendors*" files. + * This means vendor.bundle.js or vendor.[chunk].bundle.js will return 404. + * this is the fix for now. + */ + fs.writeFileSync(path.join(webpackConfig.output.path, '.nojekyll'), ''); + + const ghpages = require('gh-pages'); + ghpages.publish(webpackConfig.output.path, options, function(err) { + if (err) { + console.log('GitHub deployment done. STATUS: ERROR.'); + throw err; + } else { + console.log('GitHub deployment done. STATUS: SUCCESS.'); + } + }); + }); + } + ] + }); +}; diff --git a/config/webpack.prod.js b/config/webpack.prod.js new file mode 100644 index 0000000000..99c4cc947b --- /dev/null +++ b/config/webpack.prod.js @@ -0,0 +1,180 @@ +/** + * @author: tipe.io + */ +const helpers = require('./helpers'); +const buildUtils = require('./build-utils'); + +/** + * Used to merge webpack configs + */ +const webpackMerge = require('webpack-merge'); + +/** + * The settings that are common to prod and dev + */ +const commonConfig = require('./webpack.common.js'); + +/** + * Webpack Plugins + */ + +const MiniCssExtractPlugin = require('mini-css-extract-plugin'); +const HashedModuleIdsPlugin = require('webpack/lib/HashedModuleIdsPlugin'); +const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); + +/*** + * Ref: https://github.com/mishoo/UglifyJS2/tree/harmony#minify-options + * @param supportES2015 + * @param enableCompress disabling compress could improve the performance, see https://github.com/webpack/webpack/issues/4558#issuecomment-352255789 + * @returns {{ecma: number, warnings: boolean, ie8: boolean, mangle: boolean, compress: {pure_getters: boolean, passes: number}, output: {ascii_only: boolean, comments: boolean}}} + */ +function getUglifyOptions(supportES2015, enableCompress) { + const uglifyCompressOptions = { + pure_getters: true /* buildOptimizer */, + // PURE comments work best with 3 passes. + // See https://github.com/webpack/webpack/issues/2899#issuecomment-317425926. + passes: 2 /* buildOptimizer */ + }; + + return { + ecma: supportES2015 ? 6 : 5, + warnings: false, // TODO verbose based on option? + ie8: false, + mangle: true, + compress: enableCompress ? uglifyCompressOptions : false, + output: { + ascii_only: true, + comments: false + } + }; +} + +module.exports = function(env) { + const ENV = (process.env.NODE_ENV = process.env.ENV = 'production'); + const supportES2015 = buildUtils.supportES2015(buildUtils.DEFAULT_METADATA.tsConfigPath); + const sourceMapEnabled = process.env.SOURCE_MAP === '1'; + const METADATA = Object.assign({}, buildUtils.DEFAULT_METADATA, { + host: process.env.HOST || 'localhost', + port: process.env.PORT || 8080, + ENV: ENV, + HMR: false + }); + + // set environment suffix so these environments are loaded. + METADATA.envFileSuffix = METADATA.E2E ? 'e2e.prod' : 'prod'; + + return webpackMerge(commonConfig({ env: ENV, metadata: METADATA }), { + mode: 'production', + + devtool: 'source-map', + + /** + * Options affecting the output of the compilation. + * + * See: https://webpack.js.org/configuration/output/ + */ + output: { + /** + * The output directory as absolute path (required). + * + * See: https://webpack.js.org/configuration/output/#output-path + */ + path: helpers.root('dist'), + + /** + * Specifies the name of each output file on disk. + * IMPORTANT: You must not specify an absolute path here! + * + * See: https://webpack.js.org/configuration/output/#output-filename + */ + filename: '[name].[chunkhash].bundle.js', + + /** + * The filename of the SourceMaps for the JavaScript files. + * They are inside the output.path directory. + * + * See: https://webpack.js.org/configuration/output/#output-sourcemapfilename + */ + sourceMapFilename: '[file].map', + + /** + * The filename of non-entry chunks as relative path + * inside the output.path directory. + * + * See: https://webpack.js.org/configuration/output/#output-chunkfilename + */ + chunkFilename: '[name].[chunkhash].chunk.js' + }, + + module: { + rules: [ + /** + * Extract CSS files from .src/styles directory to external CSS file + */ + { + test: /\.css$/, + use: [MiniCssExtractPlugin.loader, 'css-loader'], + include: [helpers.root('src', 'styles')] + }, + + /** + * Extract and compile SCSS files from .src/styles directory to external CSS file + */ + { + test: /\.scss$/, + use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'], + include: [helpers.root('src', 'styles')] + } + ] + }, + + optimization: { + minimizer: [ + /** + * Plugin: UglifyJsPlugin + * Description: Minimize all JavaScript output of chunks. + * Loaders are switched into minimizing mode. + * + * See: https://webpack.js.org/plugins/uglifyjs-webpack-plugin/ + * + * NOTE: To debug prod builds uncomment //debug lines and comment //prod lines + */ + new UglifyJsPlugin({ + sourceMap: sourceMapEnabled, + parallel: true, + cache: helpers.root('webpack-cache/uglify-cache'), + uglifyOptions: getUglifyOptions(supportES2015, true) + }) + ], + splitChunks: { + chunks: 'all' + } + }, + + /** + * Add additional plugins to the compiler. + * + * See: https://webpack.js.org/configuration/plugins/ + */ + plugins: [ + new MiniCssExtractPlugin({ filename: '[name]-[hash].css', chunkFilename: '[name]-[chunkhash].css' }), + new HashedModuleIdsPlugin() + ], + + /** + * Include polyfills or mocks for various node stuff + * Description: Node configuration + * + * See: https://webpack.js.org/configuration/node/ + */ + node: { + global: true, + crypto: 'empty', + process: false, + module: false, + clearImmediate: false, + setImmediate: false, + fs: 'empty' + } + }); +}; diff --git a/config/webpack.test.js b/config/webpack.test.js new file mode 100644 index 0000000000..6d08c7fd3d --- /dev/null +++ b/config/webpack.test.js @@ -0,0 +1,251 @@ +/** + * @author: tipe.io + */ + +const helpers = require('./helpers'); + +/** + * Webpack Plugins + */ +const ProvidePlugin = require('webpack/lib/ProvidePlugin'); +const DefinePlugin = require('webpack/lib/DefinePlugin'); +const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); +const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin'); + +/** + * Webpack Constants + */ +const ENV = (process.env.ENV = process.env.NODE_ENV = 'test'); + +/** + * Webpack configuration + * + * See: https://webpack.js.org/configuration/ + */ +module.exports = function(options) { + return { + mode: 'development', + /** + * Source map for Karma from the help of karma-sourcemap-loader & karma-webpack + * + * Do not change, leave as is or it wont work. + * See: https://github.com/webpack/karma-webpack#source-maps + */ + devtool: 'inline-source-map', + + /** + * Options affecting the resolving of modules. + * + * See: https://webpack.js.org/configuration/resolve/ + */ + resolve: { + /** + * An array of extensions that should be used to resolve modules. + * + * See: https://webpack.js.org/configuration/resolve/#resolve-extensions + */ + extensions: ['.ts', '.js'], + + /** + * Make sure root is src + */ + modules: [helpers.root('src'), 'node_modules'] + }, + + /** + * Options affecting the normal modules. + * + * See: https://webpack.js.org/configuration/module/ + * + * 'use:' revered back to 'loader:' as a temp. workaround for #1188 + * See: https://github.com/gdi2290/angular-starter/issues/1188#issuecomment-262872034 + */ + module: { + rules: [ + /** + * Source map loader support for *.js files + * Extracts SourceMaps for source files that as added as sourceMappingURL comment. + * + * See: https://github.com/webpack/source-map-loader + */ + { + enforce: 'pre', + test: /\.js$/, + loader: 'source-map-loader', + exclude: [ + /** + * These packages have problems with their sourcemaps + */ + helpers.root('node_modules/@angular') + ] + }, + + /** + * Typescript loader support for .ts and Angular 2 async routes via .async.ts + * + * See: https://github.com/s-panferov/awesome-typescript-loader + */ + { + test: /\.ts$/, + use: [ + { + loader: 'awesome-typescript-loader', + query: { + /** + * Use inline sourcemaps for "karma-remap-coverage" reporter + */ + sourceMap: false, + inlineSourceMap: true, + compilerOptions: { + /** + * Remove TypeScript helpers to be injected + * below by DefinePlugin + */ + removeComments: true + } + } + }, + 'angular2-template-loader' + ], + exclude: [/\.e2e\.ts$/] + }, + + /** + * Raw loader support for *.css files + * Returns file content as string + * + * See: https://github.com/webpack/raw-loader + */ + { + test: /\.css$/, + loader: ['to-string-loader', { loader: 'css-loader', options: { url: false } }], + exclude: [helpers.root('src/index.html')] + }, + + /** + * Raw loader support for *.scss files + * + * See: https://github.com/webpack/raw-loader + */ + { + test: /\.scss$/, + loader: ['raw-loader', 'sass-loader'], + exclude: [helpers.root('src/index.html')] + }, + + /** + * Raw loader support for *.html + * Returns file content as string + * + * See: https://github.com/webpack/raw-loader + */ + { + test: /\.html$/, + loader: 'raw-loader', + exclude: [helpers.root('src/index.html')] + }, + + /** + * Instruments JS files with Istanbul for subsequent code coverage reporting. + * Instrument only testing sources. + * + * See: https://github.com/deepsweet/istanbul-instrumenter-loader + */ + { + enforce: 'post', + test: /\.(js|ts)$/, + loader: 'istanbul-instrumenter-loader', + include: helpers.root('src'), + exclude: [/\.(e2e|spec)\.ts$/, /node_modules/] + } + ] + }, + + /** + * Add additional plugins to the compiler. + * + * See: https://webpack.js.org/configuration/plugins/ + */ + plugins: [ + /** + * Plugin: DefinePlugin + * Description: Define free variables. + * Useful for having development builds with debug logging or adding global constants. + * + * Environment helpers + * + * See: https://webpack.js.org/plugins/define-plugin/ + * + * NOTE: when adding more properties make sure you include them in custom-typings.d.ts + */ + new DefinePlugin({ + ENV: JSON.stringify(ENV), + HMR: false, + 'process.env': { + ENV: JSON.stringify(ENV), + NODE_ENV: JSON.stringify(ENV), + HMR: false + } + }), + + /** + * Plugin: ContextReplacementPlugin + * Description: Provides context to Angular's use of System.import + * + * See: https://webpack.js.org/plugins/context-replacement-plugin/ + * See: https://github.com/angular/angular/issues/11580 + */ + new ContextReplacementPlugin( + /** + * The (\\|\/) piece accounts for path separators in *nix and Windows + */ + /\@angular(\\|\/)core(\\|\/)esm5/, + helpers.root('src'), // location of your src + { + /** + * your Angular Async Route paths relative to this root directory + */ + } + ), + + /** + * Plugin LoaderOptionsPlugin (experimental) + * + * See: https://gist.github.com/sokra/27b24881210b56bbaff7 + */ + new LoaderOptionsPlugin({ + debug: false, + options: { + /** + * legacy options go here + */ + } + }) + ], + + /** + * Disable performance hints + * + * See: https://github.com/a-tarasyuk/rr-boilerplate/blob/master/webpack/dev.config.babel.js#L41 + */ + performance: { + hints: false + }, + + /** + * Include polyfills or mocks for various node stuff + * Description: Node configuration + * + * See: https://webpack.js.org/configuration/node/ + */ + node: { + global: true, + crypto: 'empty', + process: false, + module: false, + clearImmediate: false, + setImmediate: false, + fs: 'empty' + } + }; +}; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000000..7f61f3725c --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,17 @@ +version: '3' +services: + angular-starter: + build: + context: . + dockerfile: Dockerfile-dev + container_name: angular-starter + networks: + - angular-starter + ports: + - '3000:3000' + environment: + - HOST=0.0.0.0 + command: npm run start +networks: + angular-starter: + driver: bridge diff --git a/firebase.json b/firebase.json new file mode 100644 index 0000000000..80e83f98d9 --- /dev/null +++ b/firebase.json @@ -0,0 +1,16 @@ +{ + "hosting": { + "public": "dist", + "rewrites": [ + { + "source": "**", + "destination": "/index.html" + } + ], + "ignore": [ + "firebase.json", + "**/.*", + "**/node_modules/**" + ] + } +} \ No newline at end of file diff --git a/karma.conf.js b/karma.conf.js index d02820b5f6..79ce74d23a 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,113 +1,8 @@ -// @AngularClass - -module.exports = function(config) { - var _config = { - - // base path that will be used to resolve all patterns (eg. files, exclude) - basePath: '', - - - // frameworks to use - // available frameworks: https://npmjs.org/browse/keyword/karma-adapter - frameworks: ['jasmine'], - - - // list of files / patterns to load in the browser - files: [ - // we are building the test environment in ./spec-bundle.js - { pattern: 'spec-bundle.js', watched: false } - ], - - - // list of files to exclude - exclude: [ - ], - - - // preprocess matching files before serving them to the browser - // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor - preprocessors: { - 'spec-bundle.js': ['webpack', 'sourcemap'] - // 'test/**/*.spec.ts': ['webpack', 'sourcemap'] - }, - - webpack: { - - resolve: { - cache: false, - root: __dirname, - extensions: ['','.ts','.js','.json', '.css', '.html'], - alias: { - 'app': 'src/app', - 'common': 'src/common' - } - }, - devtool: 'inline-source-map', - module: { - loaders: [ - { - test: /\.ts$/, - loader: 'ts-loader', - query: { - 'ignoreDiagnostics': [ - 2403, // 2403 -> Subsequent variable declarations - 2300, // 2300 Duplicate identifier - 2374, // 2374 -> Duplicate number index signature - 2375 // 2375 -> Duplicate string index signature - ] - }, - exclude: [ /\.e2e\.ts$/, /node_modules/ ] - }, - { test: /\.json$/, loader: 'json-loader' }, - { test: /\.html$/, loader: 'raw-loader' }, - { test: /\.css$/, loader: 'raw-loader' } - ] - }, - stats: { colors: true, reasons: true }, - debug: false, - noParse: [ - /zone\.js\/dist\/zone-microtask\.js/, - /zone\.js\/dist\/long-stack-trace-zone\.js/, - /zone\.js\/dist\/jasmine-patch\.js/ - ] - }, - - webpackServer: { - noInfo: true //please don't spam the console when running in karma! - }, - - - // test results reporter to use - // possible values: 'dots', 'progress' - // available reporters: https://npmjs.org/browse/keyword/karma-reporter - reporters: ['progress'], - - - // web server port - port: 9876, - - - // enable / disable colors in the output (reporters and logs) - colors: true, - - - // level of logging - // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG - logLevel: config.LOG_INFO, - - - // enable / disable watching file and executing tests whenever any file changes - autoWatch: false, - - - // start these browsers - // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher - browsers: ['PhantomJS'], - - - // Continuous Integration mode - // if true, Karma captures browsers, runs the tests and exits - singleRun: true - }; - config.set(_config); -}; +/** + * @author: tipe.io + */ + +/** + * Look in ./config for karma.conf.js + */ +module.exports = require('./config/karma.conf.js'); diff --git a/netlify.toml b/netlify.toml new file mode 100644 index 0000000000..dc8e367d34 --- /dev/null +++ b/netlify.toml @@ -0,0 +1,3 @@ +[build] + command = "npm run build:prod" + publish = "dist" diff --git a/package.json b/package.json index dbd86f4827..40135678b8 100644 --- a/package.json +++ b/package.json @@ -1,78 +1,183 @@ { - "name": "angular2-webpack-starter", - "version": "0.0.0", - "description": "An Angular 2 Webpack Starter kit featuring Angular 2 (Router, Http, Forms, Services, Tests, E2E), Karma, Protractor, Jasmine, TypeScript, and Webpack by AngularClass", - "author": "Patrick Stapleton ", - "homepage": "https://github.com/angularclass/angular2-webpack-starter", - "repository": { - "type": "git", - "url": "https://github.com/angularclass/angular2-webpack-starter.git" - }, - "bugs": { - "url": "https://github.com/angularclass/angular2-webpack-starter/issues" - }, + "name": "angular-starter", + "version": "7.5.0", + "description": "An Angular Webpack Starter kit featuring Angular (Router, Http, Forms, Services, Tests, E2E, Coverage), Karma, Protractor, Jasmine, Istanbul, TypeScript, and Webpack by Tipe.io", + "keywords": [ + "angular", + "angular2", + "angular4", + "angular5", + "webpack", + "typescript", + "tipe", + "tipe.io" + ], + "author": "Patrick Stapleton ", + "homepage": "https://github.com/gdi2290/angular-starter", "license": "MIT", - "main": "", - "engines": { - "node": ">= 4.2.1 <= 5", - "npm" : ">= 3" - }, "scripts": { - "clean": "rimraf node_modules doc typings && npm cache clean", - "clean-install": "npm run clean && npm install", - "clean-start": "npm run clean && npm start", - "watch": "webpack --watch --progress --profile --colors --display-error-details --display-cached", - "build": "webpack --progress --profile --colors --display-error-details --display-cached", - "build:prod": "webpack --progress --profile --colors --display-error-details --display-cached --optimize-occurence-order --optimize-minimize --optimize-dedupe", - "server": "webpack-dev-server --inline --progress --profile --colors --display-error-details --display-cached --port 3000", - "webdriver-update": "webdriver-manager update", - "webdriver-start": "webdriver-manager start", - "lint": "tsconfig-lint", - "e2e": "protractor", + "build:aot:prod": "rimraf dist compiled && cross-env BUILD_AOT=1 SOURCE_MAP=0 npm run webpack -- --config config/webpack.prod.js --progress --profile --bail", + "build:aot": "npm run build:aot:prod", + "build:aot:dev": "cross-env BUILD_AOT=1 npm run build:dev", + "build:dev": "rimraf dist && npm run webpack -- --config config/webpack.dev.js --mode development --progress --profile --trace-deprecation", + "build:docker": "npm run build:prod && docker build -t angular-webpack-starter:latest .", + "build:prod": "rimraf dist && npm run webpack -- --config config/webpack.prod.js --progress --profile --bail", + "build": "npm run build:dev", + "ci:aot": "cross-env BUILD_E2E=1 npm run lint && npm run test:ci && npm run build:aot && npm run e2e", + "ci:jit": "cross-env BUILD_E2E=1 npm run lint && npm run test:ci && npm run build:prod && npm run e2e", + "ci:nobuild": "npm run lint && npm test:ci && npm run e2e", + "ci:testall": "cross-env BUILD_E2E=1 npm run lint && npm run test:ci && npm run build:prod && npm run e2e && npm run build:aot && npm run e2e", + "ci:travis": "cross-env BUILD_E2E=1 npm run lint && npm run test:ci && npm run build:aot && npm run e2e:travis", + "ci": "npm run ci:testall", + "clean:all": "npm run rimraf -- doc coverage dist compiled webpack-cache", + "clean:cache": "npm run rimraf -- webpack-cache", + "clean:aot": "npm run rimraf -- compiled", + "clean:dist": "npm run rimraf -- dist", + "clean:install": "npm set progress=false && npm install", + "clean": "npm cache verify && npm run rimraf -- node_modules doc coverage dist compiled webpack-cache", + "docker": "docker", + "docs": "npm run typedoc -- --options typedoc.json --exclude '**/*.spec.ts' ./src/", + "docs:compodoc": "compodoc -p tsconfig.json", + "docs:compodoc:serve": "compodoc -p tsconfig.json -s", + "docs:compodoc:serve:watch": "compodoc -p tsconfig.json -s -w", + "e2e:live": "npm-run-all -p -r server:prod:ci protractor:live", + "e2e:travis": "npm-run-all -p -r server:prod:ci protractor:delay", + "e2e": "npm-run-all -p -r server:prod:ci protractor", + "github-deploy:dev": "npm run webpack -- --config config/webpack.github-deploy.js --mode development --progress --profile --env.githubDev", + "github-deploy:prod": "npm run webpack -- --config config/webpack.github-deploy.js --mode production --progress --profile --env.githubProd", + "github-deploy": "npm run github-deploy:dev", + "lint": "npm run tslint \"src/**/*.ts\"", + "node": "node", + "postinstall": "npm run webdriver:update", + "postversion": "git push && git push --tags", + "preclean:install": "npm run clean", + "preversion": "npm test", + "protractor": "protractor", + "protractor:delay": "sleep 3 && npm run protractor", + "protractor:live": "protractor --elementExplorer", + "rimraf": "rimraf", + "server:dev:hmr": "npm run server:dev -- --hot --hotOnly", + "server:aot:dev": "cross-env BUILD_AOT=1 npm run server:dev", + "server:dev": "npm run webpack-dev-server -- --config config/webpack.dev.js --open --progress --profile --watch --content-base src/", + "server:prod": "http-server dist -c-1 --cors", + "server:prod:ci": "http-server dist -p 3000 -c-1 --cors", + "server": "npm run server:dev", + "start:prod:hmr": "cross-env ANGULAR_CONF_FILE=./config.prod.json npm run server:dev:hmr", + "start:hmr": "npm run server:dev:hmr", + "start": "npm run server:dev", + "start:aot": "npm run server:aot:dev", "test": "karma start", - "ci": "npm run e2e && npm run test", - "docs": "typedoc --options typedoc.json src/**/*.ts", - "start": "npm run server", - "postinstall": "typings install" + "test:sonar": "npm run lint && cross-env SONAR_QUBE=1 karma start", + "test:ci": "karma start --single-run --browsers ChromeTravisCi", + "tslint": "tslint \"src/**/*.ts\" --project tsconfig.json", + "typedoc": "typedoc", + "version": "npm run build", + "watch:dev:hmr": "npm run watch:dev -- --hot", + "watch:dev": "npm run build:dev -- --watch", + "watch:aot:dev": "npm run build:aot:dev -- --watch", + "watch:prod": "npm run build:prod -- --watch", + "watch:aot:prod": "npm run build:aot:prod -- --watch", + "watch:test": "npm run test -- --auto-watch --no-single-run", + "watch": "npm run watch:dev", + "webdriver-manager": "node ./node_modules/protractor/bin/webdriver-manager", + "webdriver:start": "node ./node_modules/protractor/bin/webdriver-manager start", + "webdriver:update": "node ./node_modules/protractor/bin/webdriver-manager update", + "webpack-dev-server": "node --max_old_space_size=4096 node_modules/webpack-dev-server/bin/webpack-dev-server.js", + "webpack": "node --max_old_space_size=4096 node_modules/webpack/bin/webpack.js" }, "dependencies": { - "angular2": "2.0.0-beta.0", - "es6-promise": "^3.0.2", - "es6-shim": "^0.33.3", - "es7-reflect-metadata": "^1.2.0", - "rxjs": "5.0.0-beta.0", - "zone.js": "0.5.10" + "@angular/animations": "^6.0.6", + "@angular/common": "^6.0.6", + "@angular/compiler": "^6.0.6", + "@angular/core": "^6.0.6", + "@angular/forms": "^6.0.6", + "@angular/platform-browser": "^6.0.6", + "@angular/platform-browser-dynamic": "^6.0.6", + "@angular/platform-server": "^6.0.6", + "@angular/router": "^6.0.6", + "core-js": "^2.5.7", + "http-server": "^0.11.1", + "ie-shim": "^0.1.0", + "reflect-metadata": "^0.1.12", + "rxjs": "^6.2.1", + "zone.js": "^0.8.26" }, "devDependencies": { - "reflect-metadata": "0.1.2", - "css-loader": "^0.23.0", - "exports-loader": "0.6.2", - "expose-loader": "^0.7.1", - "file-loader": "^0.8.4", - "imports-loader": "^0.6.4", - "json-loader": "^0.5.3", - "karma": "^0.13.11", - "karma-chrome-launcher": "^0.2.1", - "karma-coverage": "^0.5.2", - "karma-jasmine": "^0.3.6", - "karma-phantomjs-launcher": "^0.2.1", - "karma-sourcemap-loader": "^0.3.6", - "karma-webpack": "1.7.0", - "phantomjs": "^1.9.18", - "phantomjs-polyfill": "0.0.1", - "protractor": "^3.0.0", - "raw-loader": "0.5.1", - "rimraf": "^2.4.4", - "style-loader": "^0.13.0", - "ts-loader": "^0.7.2", - "tsconfig-lint": "^0.2.0", - "tslint": "^3.2.0", - "tslint-loader": "^2.1.0", - "typedoc": "^0.3.12", - "typescript": "^1.7.3", - "typings": "^0.3.1", - "url-loader": "^0.5.6", - "webpack": "^1.12.9", - "webpack-dev-server": "^1.12.1" + "@angular-devkit/build-optimizer": "^0.6.8", + "@angular/cli": "^6.0.8", + "@angular/compiler-cli": "^6.0.6", + "@angular/language-service": "^6.0.6", + "@compodoc/compodoc": "^1.1.3", + "@ngtools/webpack": "^6.0.8", + "@types/hammerjs": "^2.0.35", + "@types/jasmine": "^2.8.8", + "@types/node": "^10.3.5", + "@types/uglify-js": "^3.0.2", + "@types/webpack": "^4.4.2", + "add-asset-html-webpack-plugin": "^2.1.3", + "angular2-template-loader": "^0.6.2", + "assets-webpack-plugin": "^3.8.4", + "awesome-typescript-loader": "^5.2.0", + "codelyzer": "^4.3.0", + "copy-webpack-plugin": "^4.5.1", + "cross-env": "^5.2.0", + "css-loader": "^0.28.11", + "exports-loader": "^0.7.0", + "expose-loader": "^0.7.5", + "file-loader": "^1.1.11", + "find-root": "^1.1.0", + "gh-pages": "^1.2.0", + "html-webpack-plugin": "^3.2.0", + "imports-loader": "^0.8.0", + "istanbul-instrumenter-loader": "^3.0.1", + "jasmine-core": "^3.1.0", + "karma": "^2.0.4", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "^1.1.2", + "karma-jasmine": "^1.1.2", + "karma-mocha-reporter": "^2.2.5", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^3.0.0", + "mini-css-extract-plugin": "^0.4.0", + "node-sass": "^4.9.0", + "npm-run-all": "^4.1.3", + "optimize-js-plugin": "^0.0.4", + "parse5": "^5.0.0", + "protractor": "^5.3.2", + "raw-loader": "^0.5.1", + "rimraf": "^2.6.2", + "rxjs-tslint": "^0.1.5", + "sass-loader": "^7.0.3", + "script-ext-html-webpack-plugin": "^2.0.1", + "source-map-loader": "^0.2.3", + "string-replace-loader": "^2.1.1", + "style-loader": "^0.21.0", + "to-string-loader": "^1.1.5", + "ts-node": "^7.0.0", + "tslib": "^1.9.3", + "tslint": "^5.10.0", + "tslint-loader": "^3.6.0", + "typedoc": "^0.11.1", + "typescript": "~2.7.2", + "uglifyjs-webpack-plugin": "^1.2.6", + "url-loader": "^1.0.1", + "webpack": "^4.12.0", + "webpack-cli": "^3.0.8", + "webpack-dev-middleware": "^3.1.3", + "webpack-dev-server": "^3.1.4", + "webpack-inline-manifest-plugin": "^4.0.1", + "webpack-merge": "^4.1.3" + }, + "repository": { + "type": "git", + "url": "https://github.com/gdi2290/angular-starter.git" + }, + "bugs": { + "url": "https://github.com/gdi2290/angular-starter/issues" + }, + "engines": { + "node": ">= 8.0.0", + "npm": ">= 5" } } diff --git a/protractor.conf.js b/protractor.conf.js index c70f502edc..7e93e836e1 100644 --- a/protractor.conf.js +++ b/protractor.conf.js @@ -1,44 +1,8 @@ -// @AngularClass - -exports.config = { - baseUrl: 'http://localhost:3000/', - - specs: [ - 'test/**/*.e2e.js' - ], - exclude: [], - - framework: 'jasmine', - - allScriptsTimeout: 110000, - - jasmineNodeOpts: { - showTiming: true, - showColors: true, - isVerbose: false, - includeStackTrace: false, - defaultTimeoutInterval: 400000 - }, - directConnect: true, - - capabilities: { - 'browserName': 'chrome', - 'chromeOptions': { - 'args': ['show-fps-counter=true'] - } - }, - - onPrepare: function() { - browser.ignoreSynchronization = true; - }, - - - /** - * Angular 2 configuration - * - * useAllAngular2AppRoots: tells Protractor to wait for any angular2 apps on the page instead of just the one matching - * `rootEl` - * - */ - useAllAngular2AppRoots: true -}; +/** + * @author: tipe.io + */ + +/** + * look in ./config for protractor.conf.js + */ +exports.config = require('./config/protractor.conf.js').config; diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000000..6dbf1798c3 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,18 @@ +sonar.projectKey=angular:angular-starter +sonar.projectName=angular-starter +sonar.projectVersion=6.0.0 +sonar.sourceEncoding=UTF-8 +sonar.sources=src +sonar.exclusions=**/node_modules/**,**/*.spec.ts +sonar.tests=src/app +sonar.test.inclusions=**/*.spec.ts + +sonar.ts.tslint.configPath=tslint.json +sonar.ts.coverage.lcovReportPath=coverage/coverage.lcov +# if using local tslint then enable the line below +# sonar.ts.tslint.outputPath=reports/lint_issues.json +sonar.genericcoverage.unitTestReportPaths=reports/ut_report.xml + +# Change the host.url to point to the +# sonarcube server (default localhost) +sonar.host.url=http://localhost:9000 \ No newline at end of file diff --git a/spec-bundle.js b/spec-bundle.js deleted file mode 100644 index ce26d9d617..0000000000 --- a/spec-bundle.js +++ /dev/null @@ -1,42 +0,0 @@ -// @AngularClass -/* - * When testing with webpack and ES6, we have to do some extra - * things get testing to work right. Because we are gonna write test - * in ES6 to, we have to compile those as well. That's handled in - * karma.conf.js with the karma-webpack plugin. This is the entry - * file for webpack test. Just like webpack will create a bundle.js - * file for our client, when we run test, it well compile and bundle them - * all here! Crazy huh. So we need to do some setup -*/ -Error.stackTraceLimit = Infinity; -require('phantomjs-polyfill'); -require('es6-promise'); -require('es6-shim'); -require('es7-reflect-metadata/dist/browser'); -require('zone.js/lib/browser/zone-microtask.js'); -require('zone.js/lib/browser/long-stack-trace-zone.js'); -require('zone.js/lib/browser/jasmine-patch.js'); -require('angular2/testing'); - -/* - Ok, this is kinda crazy. We can use the the context method on - require that webpack created in order to tell webpack - what files we actually want to require or import. - Below, context will be an function/object with file names as keys. - using that regex we are saying look in client/app and find - any file that ends with spec.js and get its path. By passing in true - we say do this recursively -*/ -var testContext = require.context('./test', true, /\.spec\.ts/); -var appContext = require.context('./src', true, /\.spec\.ts/); - -// get all the files, for each file, call the context function -// that will require the file and load it up here. Context will -// loop and require those spec files here -appContext.keys().forEach(appContext); -testContext.keys().forEach(testContext); - -// Select BrowserDomAdapter. -// see https://github.com/AngularClass/angular2-webpack-starter/issues/124 -var domAdapter = require('angular2/src/platform/browser/browser_adapter'); -domAdapter.BrowserDomAdapter.makeCurrent(); diff --git a/src/app/+barrel/+child-barrel/child-barrel.component.ts b/src/app/+barrel/+child-barrel/child-barrel.component.ts new file mode 100644 index 0000000000..ad41402046 --- /dev/null +++ b/src/app/+barrel/+child-barrel/child-barrel.component.ts @@ -0,0 +1,25 @@ +import { + Component, + OnInit, +} from '@angular/core'; +/** + * We're loading this component asynchronously + * We are using some magic with es6-promise-loader that will wrap the module with a Promise + * see https://github.com/gdi2290/es6-promise-loader for more info + */ + +console.log('`ChildBarrel` component loaded asynchronously'); + +@Component({ + selector: 'child-barrel', + template: ` +

Hello from Child Barrel

+ `, +}) +export class ChildBarrelComponent implements OnInit { + + public ngOnInit() { + console.log('hello `ChildBarrel` component'); + } + +} diff --git a/src/app/+barrel/+child-barrel/child-barrel.module.ts b/src/app/+barrel/+child-barrel/child-barrel.module.ts new file mode 100644 index 0000000000..afefb5720d --- /dev/null +++ b/src/app/+barrel/+child-barrel/child-barrel.module.ts @@ -0,0 +1,26 @@ +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { routes } from './child-barrel.routes'; +import { ChildBarrelComponent } from './child-barrel.component'; + +console.log('`ChildBarrel` bundle loaded asynchronously'); + +@NgModule({ + declarations: [ + /** + * Components / Directives/ Pipes + */ + ChildBarrelComponent, + ], + imports: [ + CommonModule, + FormsModule, + RouterModule.forChild(routes), + ], +}) +export class ChildBarrelModule { + public static routes = routes; +} diff --git a/src/app/+barrel/+child-barrel/child-barrel.routes.ts b/src/app/+barrel/+child-barrel/child-barrel.routes.ts new file mode 100644 index 0000000000..43e250dbd4 --- /dev/null +++ b/src/app/+barrel/+child-barrel/child-barrel.routes.ts @@ -0,0 +1,5 @@ +import { ChildBarrelComponent } from './child-barrel.component'; + +export const routes = [ + { path: '', component: ChildBarrelComponent, pathMatch: 'full' }, +]; diff --git a/src/app/+barrel/+child-barrel/index.ts b/src/app/+barrel/+child-barrel/index.ts new file mode 100644 index 0000000000..8621b2f988 --- /dev/null +++ b/src/app/+barrel/+child-barrel/index.ts @@ -0,0 +1 @@ +export { ChildBarrelModule } from './child-barrel.module'; diff --git a/src/app/+barrel/barrel.component.ts b/src/app/+barrel/barrel.component.ts new file mode 100644 index 0000000000..5fa3983996 --- /dev/null +++ b/src/app/+barrel/barrel.component.ts @@ -0,0 +1,31 @@ +import { + Component, + OnInit, +} from '@angular/core'; +/** + * We're loading this component asynchronously + * We are using some magic with es6-promise-loader that will wrap the module with a Promise + * see https://github.com/gdi2290/es6-promise-loader for more info + */ + +console.log('`Barrel` component loaded asynchronously'); + +@Component({ + selector: 'barrel', + template: ` +

Hello from Barrel

+ + + Child Barrel + + + + `, +}) +export class BarrelComponent implements OnInit { + + public ngOnInit() { + console.log('hello `Barrel` component'); + } + +} diff --git a/src/app/+barrel/barrel.module.ts b/src/app/+barrel/barrel.module.ts new file mode 100644 index 0000000000..c4e917d0e6 --- /dev/null +++ b/src/app/+barrel/barrel.module.ts @@ -0,0 +1,26 @@ +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { routes } from './barrel.routes'; +import { BarrelComponent } from './barrel.component'; + +console.log('`Barrel` bundle loaded asynchronously'); + +@NgModule({ + declarations: [ + /** + * Components / Directives/ Pipes + */ + BarrelComponent, + ], + imports: [ + CommonModule, + FormsModule, + RouterModule.forChild(routes), + ], +}) +export class BarrelModule { + public static routes = routes; +} diff --git a/src/app/+barrel/barrel.routes.ts b/src/app/+barrel/barrel.routes.ts new file mode 100644 index 0000000000..8c937065fb --- /dev/null +++ b/src/app/+barrel/barrel.routes.ts @@ -0,0 +1,8 @@ +import { BarrelComponent } from './barrel.component'; + +export const routes = [ + { path: '', children: [ + { path: '', component: BarrelComponent }, + { path: 'child-barrel', loadChildren: './+child-barrel#ChildBarrelModule' } + ]}, +]; diff --git a/src/app/+barrel/index.ts b/src/app/+barrel/index.ts new file mode 100644 index 0000000000..3f87dff82d --- /dev/null +++ b/src/app/+barrel/index.ts @@ -0,0 +1 @@ +export { BarrelModule } from './barrel.module'; diff --git a/src/app/+detail/+child-detail/child-detail.component.ts b/src/app/+detail/+child-detail/child-detail.component.ts new file mode 100644 index 0000000000..235f2911dc --- /dev/null +++ b/src/app/+detail/+child-detail/child-detail.component.ts @@ -0,0 +1,25 @@ +import { + Component, + OnInit, +} from '@angular/core'; +/** + * We're loading this component asynchronously + * We are using some magic with es6-promise-loader that will wrap the module with a Promise + * see https://github.com/gdi2290/es6-promise-loader for more info + */ + +console.log('`ChildDetail` component loaded asynchronously'); + +@Component({ + selector: 'child-detail', + template: ` +

Hello from Child Detail

+ `, +}) +export class ChildDetailComponent implements OnInit { + + public ngOnInit() { + console.log('hello `ChildDetail` component'); + } + +} diff --git a/src/app/+detail/+child-detail/child-detail.module.ts b/src/app/+detail/+child-detail/child-detail.module.ts new file mode 100644 index 0000000000..02553e1378 --- /dev/null +++ b/src/app/+detail/+child-detail/child-detail.module.ts @@ -0,0 +1,26 @@ +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { routes } from './child-detail.routes'; +import { ChildDetailComponent } from './child-detail.component'; + +console.log('`ChildDetail` bundle loaded asynchronously'); + +@NgModule({ + declarations: [ + /** + * Components / Directives/ Pipes + */ + ChildDetailComponent, + ], + imports: [ + CommonModule, + FormsModule, + RouterModule.forChild(routes), + ], +}) +export class ChildDetailModule { + public static routes = routes; +} diff --git a/src/app/+detail/+child-detail/child-detail.routes.ts b/src/app/+detail/+child-detail/child-detail.routes.ts new file mode 100644 index 0000000000..dc94cac3d2 --- /dev/null +++ b/src/app/+detail/+child-detail/child-detail.routes.ts @@ -0,0 +1,5 @@ +import { ChildDetailComponent } from './child-detail.component'; + +export const routes = [ + { path: '', component: ChildDetailComponent, pathMatch: 'full' }, +]; diff --git a/src/app/+detail/+child-detail/index.ts b/src/app/+detail/+child-detail/index.ts new file mode 100644 index 0000000000..c23f15ff60 --- /dev/null +++ b/src/app/+detail/+child-detail/index.ts @@ -0,0 +1 @@ +export { ChildDetailModule } from './child-detail.module'; diff --git a/src/app/+detail/detail.component.ts b/src/app/+detail/detail.component.ts new file mode 100644 index 0000000000..0fa814658e --- /dev/null +++ b/src/app/+detail/detail.component.ts @@ -0,0 +1,31 @@ +import { + Component, + OnInit, +} from '@angular/core'; +/** + * We're loading this component asynchronously + * We are using some magic with es6-promise-loader that will wrap the module with a Promise + * see https://github.com/gdi2290/es6-promise-loader for more info + */ + +console.log('`Detail` component loaded asynchronously'); + +@Component({ + selector: 'detail', + template: ` +

Hello from Detail

+ + + Child Detail + + + + `, +}) +export class DetailComponent implements OnInit { + + public ngOnInit() { + console.log('hello `Detail` component'); + } + +} diff --git a/src/app/+detail/detail.module.ts b/src/app/+detail/detail.module.ts new file mode 100644 index 0000000000..947b4d4346 --- /dev/null +++ b/src/app/+detail/detail.module.ts @@ -0,0 +1,26 @@ +import { CommonModule } from '@angular/common'; +import { FormsModule } from '@angular/forms'; +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { routes } from './detail.routes'; +import { DetailComponent } from './detail.component'; + +console.log('`Detail` bundle loaded asynchronously'); + +@NgModule({ + declarations: [ + /** + * Components / Directives/ Pipes + */ + DetailComponent, + ], + imports: [ + CommonModule, + FormsModule, + RouterModule.forChild(routes), + ], +}) +export class DetailModule { + public static routes = routes; +} diff --git a/src/app/+detail/detail.routes.ts b/src/app/+detail/detail.routes.ts new file mode 100644 index 0000000000..1c3cd81103 --- /dev/null +++ b/src/app/+detail/detail.routes.ts @@ -0,0 +1,8 @@ +import { DetailComponent } from './detail.component'; + +export const routes = [ + { path: '', children: [ + { path: '', component: DetailComponent }, + { path: 'child-detail', loadChildren: './+child-detail#ChildDetailModule' } + ]}, +]; diff --git a/src/app/+detail/index.ts b/src/app/+detail/index.ts new file mode 100644 index 0000000000..b2463a4dce --- /dev/null +++ b/src/app/+detail/index.ts @@ -0,0 +1 @@ +export { DetailModule } from './detail.module'; diff --git a/src/app/+dev-module/dev-module.component.ts b/src/app/+dev-module/dev-module.component.ts new file mode 100644 index 0000000000..393f46d068 --- /dev/null +++ b/src/app/+dev-module/dev-module.component.ts @@ -0,0 +1,15 @@ +import { Component, OnInit } from '@angular/core'; + +@Component({ + selector: 'dev-module', + template: ` +

Hello from DevModule Component

+ `, +}) +export class DevModuleComponent implements OnInit { + + public ngOnInit() { + console.log('hello `DevModule` component'); + } + +} diff --git a/src/app/+dev-module/dev-module.module.ts b/src/app/+dev-module/dev-module.module.ts new file mode 100644 index 0000000000..83f4b0cb15 --- /dev/null +++ b/src/app/+dev-module/dev-module.module.ts @@ -0,0 +1,24 @@ +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { RouterModule } from '@angular/router'; + +import { routes } from './dev-module.routes'; +import { DevModuleComponent } from './dev-module.component'; + +/* + Don't leave side-effects outside of classes so this will tree-shake nicely on prod + e.g. `console.log('something')` is a side effect. +*/ +@NgModule({ + declarations: [ DevModuleComponent ], + imports: [ + CommonModule, + RouterModule.forChild(routes), + ], +}) +export class DevModuleModule { + public static routes = routes; + constructor() { + console.log('`DevModuleModule` module initialized'); + } +} diff --git a/src/app/+dev-module/dev-module.routes.ts b/src/app/+dev-module/dev-module.routes.ts new file mode 100644 index 0000000000..dc7323b4f2 --- /dev/null +++ b/src/app/+dev-module/dev-module.routes.ts @@ -0,0 +1,5 @@ +import { DevModuleComponent } from './dev-module.component'; + +export const routes = [ + { path: 'dev-module', component: DevModuleComponent } +]; diff --git a/src/app/+dev-module/index.ts b/src/app/+dev-module/index.ts new file mode 100644 index 0000000000..47a5d082ae --- /dev/null +++ b/src/app/+dev-module/index.ts @@ -0,0 +1 @@ +export { DevModuleModule } from './dev-module.module'; diff --git a/src/app/about/about.component.spec.ts b/src/app/about/about.component.spec.ts new file mode 100644 index 0000000000..241750fa70 --- /dev/null +++ b/src/app/about/about.component.spec.ts @@ -0,0 +1,41 @@ +import { ActivatedRoute, Data } from '@angular/router'; +import { Component } from '@angular/core'; +import { inject, TestBed } from '@angular/core/testing'; + +/** + * Load the implementations that should be tested. + */ +import { AboutComponent } from './about.component'; + +describe('About', () => { + /** + * Provide our implementations or mocks to the dependency injector + */ + beforeEach(() => TestBed.configureTestingModule({ + providers: [ + /** + * Provide a better mock. + */ + { + provide: ActivatedRoute, + useValue: { + data: { + subscribe: (fn: (value: Data) => void) => fn({ + yourData: 'yolo' + }) + } + } + }, + AboutComponent + ] + })); + + it('should log ngOnInit', inject([AboutComponent], (about: AboutComponent) => { + spyOn(console, 'log'); + expect(console.log).not.toHaveBeenCalled(); + + about.ngOnInit(); + expect(console.log).toHaveBeenCalled(); + })); + +}); diff --git a/src/app/about/about.component.ts b/src/app/about/about.component.ts new file mode 100644 index 0000000000..a7a6d13140 --- /dev/null +++ b/src/app/about/about.component.ts @@ -0,0 +1,68 @@ +import { + Component, + OnInit +} from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +@Component({ + selector: 'about', + styles: [` + `], + template: ` +

About

+
+ For hot module reloading run +
npm run start:hmr
+
+
+

+ patrick@tipe.io +

+
+
this.localState = {{ localState | json }}
+ ` +}) +export class AboutComponent implements OnInit { + + public localState: any; + constructor( + public route: ActivatedRoute + ) {} + + public ngOnInit() { + this.route + .data + .subscribe((data: any) => { + /** + * Your resolved data from route. + */ + this.localState = data.yourData; + }); + + console.log('hello `About` component'); + /** + * static data that is bundled + * var mockData = require('assets/mock-data/mock-data.json'); + * console.log('mockData', mockData); + * if you're working with mock data you can also use http.get('assets/mock-data/mock-data.json') + */ + this.asyncDataWithWebpack(); + } + private asyncDataWithWebpack() { + /** + * you can also async load mock data with 'es6-promise-loader' + * you would do this if you don't want the mock-data bundled + * remember that 'es6-promise-loader' is a promise + */ + setTimeout(() => { + + import('../../assets/mock-data/mock-data.json') + .then((json) => { + console.log('async mockData', json); + this.localState = json; + }); + + }); + } + +} diff --git a/src/app/about/index.ts b/src/app/about/index.ts new file mode 100644 index 0000000000..b7cb92aea6 --- /dev/null +++ b/src/app/about/index.ts @@ -0,0 +1 @@ +export * from './about.component'; diff --git a/src/app/app.component.css b/src/app/app.component.css new file mode 100644 index 0000000000..f78b9d9d28 --- /dev/null +++ b/src/app/app.component.css @@ -0,0 +1,8 @@ +html, body{ + height: 100%; + font-family: Arial, Helvetica, sans-serif +} + +a.active { + background-color: gray; +} diff --git a/src/app/app.component.spec.ts b/src/app/app.component.spec.ts new file mode 100644 index 0000000000..866abe6b04 --- /dev/null +++ b/src/app/app.component.spec.ts @@ -0,0 +1,66 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { + inject, + async, + TestBed, + ComponentFixture +} from '@angular/core/testing'; + +/** + * Load the implementations that should be tested + */ +import { AppComponent } from './app.component'; +import { AppState } from './app.service'; + +describe(`App`, () => { + let comp: AppComponent; + let fixture: ComponentFixture; + + /** + * async beforeEach + */ + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ AppComponent ], + schemas: [NO_ERRORS_SCHEMA], + providers: [AppState] + }) + /** + * Compile template and css + */ + .compileComponents(); + })); + + /** + * Synchronous beforeEach + */ + beforeEach(() => { + fixture = TestBed.createComponent(AppComponent); + comp = fixture.componentInstance; + + /** + * Trigger initial data binding + */ + fixture.detectChanges(); + }); + + it(`should be readly initialized`, () => { + expect(fixture).toBeDefined(); + expect(comp).toBeDefined(); + }); + + it(`should be @TipeIO`, () => { + expect(comp.twitter).toEqual('https://twitter.com/gdi2290'); + expect(comp.tipe).toEqual('assets/img/tipe.png'); + expect(comp.name).toEqual('Angular Starter'); + }); + + it('should log ngOnInit', () => { + spyOn(console, 'log'); + expect(console.log).not.toHaveBeenCalled(); + + comp.ngOnInit(); + expect(console.log).toHaveBeenCalled(); + }); + +}); diff --git a/src/app/app.component.ts b/src/app/app.component.ts new file mode 100644 index 0000000000..5963620b89 --- /dev/null +++ b/src/app/app.component.ts @@ -0,0 +1,87 @@ +/** + * Angular 2 decorators and services + */ +import { Component, OnInit, ViewEncapsulation } from '@angular/core'; +import { environment } from 'environments/environment'; +import { AppState } from './app.service'; + +export const ROOT_SELECTOR = 'app'; + +/** + * App Component + * Top Level Component + */ +@Component({ + selector: ROOT_SELECTOR, + encapsulation: ViewEncapsulation.None, + styleUrls: [ + './app.component.css' + ], + template: ` + + +
+ +
+ +
this.appState.state = {{ appState.state | json }}
+ + + ` +}) +export class AppComponent implements OnInit { + public name = 'Angular Starter'; + public tipe = 'assets/img/tipe.png'; + public twitter = 'https://twitter.com/gdi2290'; + public url = 'https://tipe.io'; + public showDevModule: boolean = environment.showDevModule; + + constructor( + public appState: AppState + ) {} + + public ngOnInit() { + console.log('Initial App State', this.appState.state); + } + +} + +/** + * Please review the https://github.com/AngularClass/angular-examples/ repo for + * more angular app examples that you may copy/paste + * (The examples may not be updated as quickly. Please open an issue on github for us to update it) + * For help or questions please contact us at @AngularClass on twitter + * or our chat on Slack at https://AngularClass.com/slack-join + */ diff --git a/src/app/app.e2e.ts b/src/app/app.e2e.ts new file mode 100644 index 0000000000..368de16db5 --- /dev/null +++ b/src/app/app.e2e.ts @@ -0,0 +1,34 @@ +import { browser, by, element } from 'protractor'; +import 'tslib'; + +describe('App', () => { + + beforeEach(async () => { + await browser.get('/'); + }); + + it('should have a title', async () => { + const subject = await browser.getTitle(); + const result = 'Angular Starter by @gdi2290 from @TipeIO'; + expect(subject).toEqual(result); + }); + + it('should have header', async () => { + const subject = await element(by.css('h1')).isPresent(); + const result = true; + expect(subject).toEqual(result); + }); + + it('should have ', async () => { + const subject = await element(by.css('app home')).isPresent(); + const result = true; + expect(subject).toEqual(result); + }); + + it('should have buttons', async () => { + const subject = await element(by.css('button')).getText(); + const result = 'Submit Value'; + expect(subject).toEqual(result); + }); + +}); diff --git a/src/app/app.module.ts b/src/app/app.module.ts new file mode 100644 index 0000000000..7a537c880e --- /dev/null +++ b/src/app/app.module.ts @@ -0,0 +1,78 @@ +import { NgModule } from '@angular/core'; +import { BrowserModule } from '@angular/platform-browser'; +import { FormsModule } from '@angular/forms'; +import { HttpClientModule } from '@angular/common/http'; +import { RouterModule, PreloadAllModules } from '@angular/router'; +import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; + +/* + * Platform and Environment providers/directives/pipes + */ +import { environment } from 'environments/environment'; +import { ROUTES } from './app.routes'; +// App is our top level component +import { AppComponent } from './app.component'; +import { APP_RESOLVER_PROVIDERS } from './app.resolver'; +import { AppState, InternalStateType } from './app.service'; +import { HomeComponent } from './home'; +import { AboutComponent } from './about'; +import { NoContentComponent } from './no-content'; +import { XLargeDirective } from './home/x-large'; +import { DevModuleModule } from './+dev-module'; + +import '../styles/styles.scss'; +import '../styles/headings.css'; + +// Application wide providers +const APP_PROVIDERS = [ + ...APP_RESOLVER_PROVIDERS, + AppState +]; + +interface StoreType { + state: InternalStateType; + restoreInputValues: () => void; + disposeOldHosts: () => void; +} + +/** + * `AppModule` is the main entry point into Angular2's bootstraping process + */ +@NgModule({ + bootstrap: [ AppComponent ], + declarations: [ + AppComponent, + AboutComponent, + HomeComponent, + NoContentComponent, + XLargeDirective + ], + /** + * Import Angular's modules. + */ + imports: [ + BrowserModule, + BrowserAnimationsModule, + FormsModule, + HttpClientModule, + RouterModule.forRoot(ROUTES, { + useHash: Boolean(history.pushState) === false, + preloadingStrategy: PreloadAllModules + }), + + /** + * This section will import the `DevModuleModule` only in certain build types. + * When the module is not imported it will get tree shaked. + * This is a simple example, a big app should probably implement some logic + */ + ...environment.showDevModule ? [ DevModuleModule ] : [], + ], + /** + * Expose our Services and Providers into Angular's dependency injection. + */ + providers: [ + environment.ENV_PROVIDERS, + APP_PROVIDERS + ] +}) +export class AppModule {} diff --git a/src/app/app.resolver.ts b/src/app/app.resolver.ts new file mode 100644 index 0000000000..ca5bec8615 --- /dev/null +++ b/src/app/app.resolver.ts @@ -0,0 +1,17 @@ +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; +import { Injectable } from '@angular/core'; +import { of } from 'rxjs'; + +@Injectable() +export class DataResolver implements Resolve { + public resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + return of({ res: 'I am data'}); + } +} + +/** + * An array of services to resolve routes with data. + */ +export const APP_RESOLVER_PROVIDERS = [ + DataResolver +]; diff --git a/src/app/app.routes.ts b/src/app/app.routes.ts new file mode 100644 index 0000000000..39ca8dc2af --- /dev/null +++ b/src/app/app.routes.ts @@ -0,0 +1,13 @@ +import { Routes } from '@angular/router'; +import { HomeComponent } from './home'; +import { AboutComponent } from './about'; +import { NoContentComponent } from './no-content'; + +export const ROUTES: Routes = [ + { path: '', component: HomeComponent }, + { path: 'home', component: HomeComponent }, + { path: 'about', component: AboutComponent }, + { path: 'detail', loadChildren: './+detail#DetailModule'}, + { path: 'barrel', loadChildren: './+barrel#BarrelModule'}, + { path: '**', component: NoContentComponent }, +]; diff --git a/src/app/app.service.ts b/src/app/app.service.ts new file mode 100644 index 0000000000..ad84162ade --- /dev/null +++ b/src/app/app.service.ts @@ -0,0 +1,46 @@ +import { Injectable } from '@angular/core'; + +export interface InternalStateType { + [key: string]: any; +} + +@Injectable() +export class AppState { + + public _state: InternalStateType = { }; + + /** + * Already return a clone of the current state. + */ + public get state() { + return this._state = this._clone(this._state); + } + /** + * Never allow mutation + */ + public set state(value) { + throw new Error('do not mutate the `.state` directly'); + } + + public get(prop?: any) { + /** + * Use our state getter for the clone. + */ + const state = this.state; + return state.hasOwnProperty(prop) ? state[prop] : state; + } + + public set(prop: string, value: any) { + /** + * Internally mutate our state. + */ + return this._state[prop] = value; + } + + private _clone(object: InternalStateType) { + /** + * Simple object clone. + */ + return JSON.parse(JSON.stringify( object )); + } +} diff --git a/src/app/app.spec.ts b/src/app/app.spec.ts deleted file mode 100644 index d745caa2c3..0000000000 --- a/src/app/app.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { - it, - inject, - injectAsync, - beforeEachProviders, - TestComponentBuilder -} from 'angular2/testing'; - -// Load the implementations that should be tested -import {App} from './app'; -import {Title} from './providers/title'; - -describe('App', () => { - // provide our implementations or mocks to the dependency injector - beforeEachProviders(() => [ - App, - Title - ]); - - it('should have a url', inject([ App ], (app) => { - expect(app.url).toEqual('https://twitter.com/AngularClass'); - })); - -}); diff --git a/src/app/app.ts b/src/app/app.ts deleted file mode 100644 index 753b1d4947..0000000000 --- a/src/app/app.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Angular 2 decorators and services - */ -import {Component} from 'angular2/core'; -import {RouteConfig, Router, ROUTER_DIRECTIVES} from 'angular2/router'; -import {Http} from 'angular2/http'; -import {FORM_PROVIDERS} from 'angular2/common'; - -import {Title} from './providers/title'; -import {XLarge} from './directives/x-large'; -import {Home} from './home/home'; - -/* - * App Component - * Top Level Component - */ -@Component({ - // The selector is what angular internally uses - // for `document.querySelectorAll(selector)` in our index.html - // where, in this case, selector is the string 'app' - selector: 'app', // - // We need to tell Angular's Dependency Injection which providers are in our app. - providers: [ ...FORM_PROVIDERS, Title], - // We need to tell Angular's compiler which directives are in our template. - // Doing so will allow Angular to attach our behavior to an element - directives: [ ...ROUTER_DIRECTIVES, XLarge ], - // We need to tell Angular's compiler which custom pipes are in our template. - pipes: [], - // Our list of styles in our component. We may add more to compose many styles together - styles: [` - .title { - font-family: Arial, Helvetica, sans-serif; - } - main { - padding: 1em; - } - - `], - // Every Angular template is first compiled by the browser before Angular runs it's compiler - template: ` -
-

Hello {{ title.value }}

- -
- -
- -
- - - ` -}) -@RouteConfig([ - { path: '/', component: Home, name: 'Home' } -]) -export class App { - url: string = 'https://twitter.com/AngularClass'; - constructor(public title: Title) {} -} - -/* - * Please review the https://github.com/AngularClass/angular2-examples/ repo for - * more angular app examples that you may copy/paste - * (The examples may not be updated as quickly. Please open an issue on github for us to update it) - * For help or questions please contact us at @AngularClass on twitter - * or our chat on Slack at https://AngularClass.com/slack-join - * or via chat on Gitter at https://gitter.im/AngularClass/angular2-webpack-starter - */ diff --git a/src/app/directives/x-large.spec.ts b/src/app/directives/x-large.spec.ts deleted file mode 100644 index 2a055061b5..0000000000 --- a/src/app/directives/x-large.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { - it, - inject, - injectAsync, - beforeEachProviders, - TestComponentBuilder -} from 'angular2/testing'; - -import {Component, provide} from 'angular2/core'; -import {BaseRequestOptions, Http} from 'angular2/http'; -import {MockBackend} from 'angular2/http/testing'; - -// Load the implementations that should be tested -import { XLarge } from './x-large'; - -describe('x-large directive', () => { - // Create a test component to test directives - @Component({ - template: '', - directives: [XLarge] - }) - class TestComponent {} - - it('should sent font-size to x-large', injectAsync([TestComponentBuilder], (tcb) => { - return tcb.overrideTemplate(TestComponent, '
Content
') - .createAsync(TestComponent).then((fixture: any) => { - fixture.detectChanges(); - let compiled = fixture.debugElement.nativeElement.children[0]; - expect(compiled.style.fontSize).toBe('x-large'); - }); - })); - -}); diff --git a/src/app/directives/x-large.ts b/src/app/directives/x-large.ts deleted file mode 100644 index 2aa0ad7678..0000000000 --- a/src/app/directives/x-large.ts +++ /dev/null @@ -1,18 +0,0 @@ -import {Directive, Component, ElementRef, Renderer} from 'angular2/core'; -/* - * Directive - * XLarge is a simple directive to show how one is made - */ -@Directive({ - selector: '[x-large]' // using [ ] means selecting attributes -}) -export class XLarge { - constructor(element: ElementRef, renderer: Renderer) { - // simple DOM manipulation to set font size to x-large - // `nativeElement` is the direct reference to the DOM element - // element.nativeElement.style.fontSize = 'x-large'; - - // for server/webworker support use the renderer - renderer.setElementStyle(element, 'fontSize', 'x-large'); - } -} diff --git a/src/app/home/home.component.css b/src/app/home/home.component.css new file mode 100644 index 0000000000..4511e22d14 --- /dev/null +++ b/src/app/home/home.component.css @@ -0,0 +1 @@ +/*styles for home content only*/ \ No newline at end of file diff --git a/src/app/home/home.component.html b/src/app/home/home.component.html new file mode 100644 index 0000000000..f37acb218d --- /dev/null +++ b/src/app/home/home.component.html @@ -0,0 +1,37 @@ +
+

Your Content Here

+ +
+ +
+ For hot module reloading run +
npm run start:hmr
+
+ +
+ +
+

Local State

+ +
+ + + + +
+ + +
this.localState = {{ localState | json }}
+ +
+ +
diff --git a/src/app/home/home.component.spec.ts b/src/app/home/home.component.spec.ts new file mode 100644 index 0000000000..e3f71c5808 --- /dev/null +++ b/src/app/home/home.component.spec.ts @@ -0,0 +1,75 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { + inject, + async, + TestBed, + ComponentFixture, + getTestBed +} from '@angular/core/testing'; +import { Component } from '@angular/core'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +/** + * Load the implementations that should be tested. + */ +import { AppState } from '../app.service'; +import { HomeComponent } from './home.component'; +import { Title } from './title'; + +describe(`Home`, () => { + let comp: HomeComponent; + let fixture: ComponentFixture; + let injector: TestBed; + let service: AppState; + let httpMock: HttpTestingController; + + /** + * async beforeEach. + */ + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [HomeComponent], + schemas: [NO_ERRORS_SCHEMA], + imports: [HttpClientTestingModule], + providers: [AppState, Title] + }) + + /** + * Compile template and css. + */ + .compileComponents(); + injector = getTestBed(); + service = injector.get(AppState); + httpMock = injector.get(HttpTestingController); + })); + + /** + * Synchronous beforeEach. + */ + beforeEach(() => { + fixture = TestBed.createComponent(HomeComponent); + comp = fixture.componentInstance; + + /** + * Trigger initial data binding. + */ + fixture.detectChanges(); + }); + + it('should have default data', () => { + expect(comp.localState).toEqual({ value: '' }); + }); + + it('should have a title', () => { + expect(!!comp.title).toEqual(true); + }); + + it('should log ngOnInit', () => { + spyOn(console, 'log'); + expect(console.log).not.toHaveBeenCalled(); + + comp.ngOnInit(); + expect(console.log).toHaveBeenCalled(); + }); + +}); diff --git a/src/app/home/home.component.ts b/src/app/home/home.component.ts new file mode 100644 index 0000000000..7ea4f15be1 --- /dev/null +++ b/src/app/home/home.component.ts @@ -0,0 +1,57 @@ +import { + Component, + OnInit +} from '@angular/core'; + +import { AppState } from '../app.service'; +import { Title } from './title'; +import { XLargeDirective } from './x-large'; + +@Component({ + /** + * The selector is what angular internally uses + * for `document.querySelectorAll(selector)` in our index.html + * where, in this case, selector is the string 'home'. + */ + selector: 'home', // + /** + * We need to tell Angular's Dependency Injection which providers are in our app. + */ + providers: [ + Title + ], + /** + * Our list of styles in our component. We may add more to compose many styles together. + */ + styleUrls: [ './home.component.css' ], + /** + * Every Angular template is first compiled by the browser before Angular runs it's compiler. + */ + templateUrl: './home.component.html' +}) +export class HomeComponent implements OnInit { + /** + * Set our default values + */ + public localState = { value: '' }; + /** + * TypeScript public modifiers + */ + constructor( + public appState: AppState, + public title: Title + ) {} + + public ngOnInit() { + console.log('hello `Home` component'); + /** + * this.title.getData().subscribe(data => this.data = data); + */ + } + + public submitState(value: string) { + console.log('submitState', value); + this.appState.set('value', value); + this.localState.value = ''; + } +} diff --git a/src/app/home/home.e2e.ts b/src/app/home/home.e2e.ts new file mode 100644 index 0000000000..d8dd92cd16 --- /dev/null +++ b/src/app/home/home.e2e.ts @@ -0,0 +1,26 @@ +import { browser, by, element } from 'protractor'; +import 'tslib'; + +describe('Home', () => { + + beforeEach(async () => { + /** + * Change hash depending on router LocationStrategy. + */ + await browser.get('/'); + await element(by.linkText('Home')).click(); + }); + + it('should have a title', async () => { + const subject = await browser.getTitle(); + const result = 'Angular Starter by @gdi2290 from @TipeIO'; + expect(subject).toEqual(result); + }); + + it('should have `your content here` x-large', async () => { + const subject = await element(by.css('[x-large]')).getText(); + const result = 'Your Content Here'; + expect(subject).toEqual(result); + }); + +}); diff --git a/src/app/home/home.html b/src/app/home/home.html deleted file mode 100644 index c9d4b085a9..0000000000 --- a/src/app/home/home.html +++ /dev/null @@ -1,11 +0,0 @@ -
- Your Content Here - - - -
this.title = {{ title | json }}
-
diff --git a/src/app/home/home.spec.ts b/src/app/home/home.spec.ts deleted file mode 100644 index 97d158a52f..0000000000 --- a/src/app/home/home.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { - it, - inject, - injectAsync, - beforeEachProviders, - TestComponentBuilder -} from 'angular2/testing'; - -import {Component, provide} from 'angular2/core'; -import {BaseRequestOptions, Http} from 'angular2/http'; -import {MockBackend} from 'angular2/http/testing'; - -// Load the implementations that should be tested -import {Home} from './home'; -import {Title} from '../providers/title'; - -describe('Home', () => { - // provide our implementations or mocks to the dependency injector - beforeEachProviders(() => [ - Title, - Home, - BaseRequestOptions, - MockBackend, - provide(Http, { - useFactory: function(backend, defaultOptions) { - return new Http(backend, defaultOptions); - }, - deps: [MockBackend, BaseRequestOptions]}) - ]); - - it('should have a title', inject([ Home ], (app) => { - expect(app.title.value).toEqual('Angular 2'); - })); - -}); diff --git a/src/app/home/home.ts b/src/app/home/home.ts deleted file mode 100644 index fc90f33583..0000000000 --- a/src/app/home/home.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {Component} from 'angular2/core'; -import {FORM_DIRECTIVES} from 'angular2/common'; -import {Http} from 'angular2/http'; - -import {Title} from '../providers/title'; - -@Component({ - selector: 'home', - directives: [ ...FORM_DIRECTIVES ], - providers: [ Title ], - pipes: [], - styles: [ require('./home.css') ], - template: require('./home.html') -}) -export class Home { - // TypeScript public modifiers - constructor(public title: Title, public http: Http) { - } - - ngOnInit() { - console.log('hello Home'); - } - -} diff --git a/src/app/home/index.ts b/src/app/home/index.ts new file mode 100644 index 0000000000..ab5a522cb1 --- /dev/null +++ b/src/app/home/index.ts @@ -0,0 +1 @@ +export * from './home.component'; diff --git a/src/app/home/title/index.ts b/src/app/home/title/index.ts new file mode 100644 index 0000000000..1410559951 --- /dev/null +++ b/src/app/home/title/index.ts @@ -0,0 +1 @@ +export * from './title.service'; diff --git a/src/app/home/title/title.service.spec.ts b/src/app/home/title/title.service.spec.ts new file mode 100644 index 0000000000..5e55da4800 --- /dev/null +++ b/src/app/home/title/title.service.spec.ts @@ -0,0 +1,35 @@ +import { + inject, + async, + TestBed, + ComponentFixture, + getTestBed +} from '@angular/core/testing'; +import { Component } from '@angular/core'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { Title } from './title.service'; + +describe('Title', () => { + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [Title] + }); + }); + + it('should have http', inject([Title], (title: Title) => { + expect(!!title.http).toEqual(true); + })); + + it('should get data from the server', inject([Title], (title: Title) => { + spyOn(console, 'log'); + expect(console.log).not.toHaveBeenCalled(); + + title.getData(); + expect(console.log).toHaveBeenCalled(); + title.getData().subscribe( (result) => { + expect(result).toEqual({ value: 'AngularClass' }); + }); + })); + +}); diff --git a/src/app/home/title/title.service.ts b/src/app/home/title/title.service.ts new file mode 100644 index 0000000000..ff3c41b68b --- /dev/null +++ b/src/app/home/title/title.service.ts @@ -0,0 +1,18 @@ +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; + +@Injectable() +export class Title { + + public value = 'Angular 2'; + + constructor( + public http: HttpClient + ) { } + + public getData() { + console.log('Title#getData(): Get Data'); + return this.http.get('/assets/data.json'); + } + +} diff --git a/src/app/home/x-large/index.ts b/src/app/home/x-large/index.ts new file mode 100644 index 0000000000..7038da2552 --- /dev/null +++ b/src/app/home/x-large/index.ts @@ -0,0 +1 @@ +export * from './x-large.directive'; diff --git a/src/app/home/x-large/x-large.directive.spec.ts b/src/app/home/x-large/x-large.directive.spec.ts new file mode 100644 index 0000000000..fe7312bf7e --- /dev/null +++ b/src/app/home/x-large/x-large.directive.spec.ts @@ -0,0 +1,50 @@ +import { By } from '@angular/platform-browser'; +import { + inject, + fakeAsync, + tick, + async, + TestBed, + ComponentFixture, + getTestBed +} from '@angular/core/testing'; +import { Component } from '@angular/core'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +/** + * Load the implementations that should be tested. + */ +import { XLargeDirective } from './x-large.directive'; + +describe('x-large directive', () => { + /** + * Create a test component to test directives. + */ + @Component({ + template: '
Content
' + }) + class TestComponent { } + + beforeEach(() => { + TestBed.configureTestingModule({ + declarations: [ + XLargeDirective, + TestComponent + ] + }); + }); + + it('should sent font-size to x-large', fakeAsync(() => { + TestBed.compileComponents().then(() => { + + const fixture = TestBed.createComponent(TestComponent); + fixture.detectChanges(); + tick(); + const element = fixture.debugElement.query(By.css('div')); + + expect(element.nativeElement.style.fontSize).toBe('x-large'); + + }); + })); + +}); diff --git a/src/app/home/x-large/x-large.directive.ts b/src/app/home/x-large/x-large.directive.ts new file mode 100644 index 0000000000..83adab9f12 --- /dev/null +++ b/src/app/home/x-large/x-large.directive.ts @@ -0,0 +1,29 @@ +import { + Component, + Directive, + ElementRef, + Renderer +} from '@angular/core'; +/** + * Directive + * XLarge is a simple directive to show how one is made + */ +@Directive({ + // tslint:disable-next-line:directive-selector + selector: '[x-large]' // using [ ] means selecting attributes +}) +export class XLargeDirective { + constructor( + public element: ElementRef, + public renderer: Renderer + ) { + /** + * Simple DOM manipulation to set font size to x-large + * `nativeElement` is the direct reference to the DOM element + * element.nativeElement.style.fontSize = 'x-large'; + * + * for server/webworker support use the renderer + */ + renderer.setElementStyle(element.nativeElement, 'fontSize', 'x-large'); + } +} diff --git a/src/app/index.ts b/src/app/index.ts new file mode 100644 index 0000000000..10806a6f77 --- /dev/null +++ b/src/app/index.ts @@ -0,0 +1,4 @@ +/** + * App + */ +export * from './app.module'; diff --git a/src/app/no-content/index.ts b/src/app/no-content/index.ts new file mode 100644 index 0000000000..93ea576f7e --- /dev/null +++ b/src/app/no-content/index.ts @@ -0,0 +1 @@ +export * from './no-content.component'; diff --git a/src/app/no-content/no-content.component.ts b/src/app/no-content/no-content.component.ts new file mode 100644 index 0000000000..7aef10e4a8 --- /dev/null +++ b/src/app/no-content/no-content.component.ts @@ -0,0 +1,13 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'no-content', + template: ` +
+

404: page missing

+
+ ` +}) +export class NoContentComponent { + +} diff --git a/src/app/providers/title.spec.ts b/src/app/providers/title.spec.ts deleted file mode 100644 index a9b34e8e36..0000000000 --- a/src/app/providers/title.spec.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - it, - inject, - injectAsync, - beforeEachProviders, - TestComponentBuilder -} from 'angular2/testing'; -import {Title} from './title'; - -describe('Title', () => { - let title; - - beforeEach(() => { - title = new Title(); - }); - - it('should return the list of names', () => { - expect(title.value).toEqual('Angular 2'); - }); -}); diff --git a/src/app/providers/title.ts b/src/app/providers/title.ts deleted file mode 100644 index 98957a6789..0000000000 --- a/src/app/providers/title.ts +++ /dev/null @@ -1,9 +0,0 @@ -import {Injectable} from 'angular2/core'; - -@Injectable() -export class Title { - value: string; - constructor() { - this.value = 'Angular 2'; - } -} diff --git a/src/public/css/.gitkeep b/src/assets/css/.gitkeep similarity index 100% rename from src/public/css/.gitkeep rename to src/assets/css/.gitkeep diff --git a/src/assets/data.json b/src/assets/data.json new file mode 100644 index 0000000000..b566a0bbd0 --- /dev/null +++ b/src/assets/data.json @@ -0,0 +1,3 @@ +{ + "value": "AngularClass" +} diff --git a/src/public/humans.txt b/src/assets/humans.txt similarity index 100% rename from src/public/humans.txt rename to src/assets/humans.txt diff --git a/src/public/icon/android-icon-144x144.png b/src/assets/icon/android-icon-144x144.png similarity index 100% rename from src/public/icon/android-icon-144x144.png rename to src/assets/icon/android-icon-144x144.png diff --git a/src/public/icon/android-icon-192x192.png b/src/assets/icon/android-icon-192x192.png similarity index 100% rename from src/public/icon/android-icon-192x192.png rename to src/assets/icon/android-icon-192x192.png diff --git a/src/public/icon/android-icon-36x36.png b/src/assets/icon/android-icon-36x36.png similarity index 100% rename from src/public/icon/android-icon-36x36.png rename to src/assets/icon/android-icon-36x36.png diff --git a/src/public/icon/android-icon-48x48.png b/src/assets/icon/android-icon-48x48.png similarity index 100% rename from src/public/icon/android-icon-48x48.png rename to src/assets/icon/android-icon-48x48.png diff --git a/src/public/icon/android-icon-72x72.png b/src/assets/icon/android-icon-72x72.png similarity index 100% rename from src/public/icon/android-icon-72x72.png rename to src/assets/icon/android-icon-72x72.png diff --git a/src/public/icon/android-icon-96x96.png b/src/assets/icon/android-icon-96x96.png similarity index 100% rename from src/public/icon/android-icon-96x96.png rename to src/assets/icon/android-icon-96x96.png diff --git a/src/public/icon/apple-icon-114x114.png b/src/assets/icon/apple-icon-114x114.png similarity index 100% rename from src/public/icon/apple-icon-114x114.png rename to src/assets/icon/apple-icon-114x114.png diff --git a/src/public/icon/apple-icon-120x120.png b/src/assets/icon/apple-icon-120x120.png similarity index 100% rename from src/public/icon/apple-icon-120x120.png rename to src/assets/icon/apple-icon-120x120.png diff --git a/src/public/icon/apple-icon-144x144.png b/src/assets/icon/apple-icon-144x144.png similarity index 100% rename from src/public/icon/apple-icon-144x144.png rename to src/assets/icon/apple-icon-144x144.png diff --git a/src/public/icon/apple-icon-152x152.png b/src/assets/icon/apple-icon-152x152.png similarity index 100% rename from src/public/icon/apple-icon-152x152.png rename to src/assets/icon/apple-icon-152x152.png diff --git a/src/public/icon/apple-icon-180x180.png b/src/assets/icon/apple-icon-180x180.png similarity index 100% rename from src/public/icon/apple-icon-180x180.png rename to src/assets/icon/apple-icon-180x180.png diff --git a/src/public/icon/apple-icon-57x57.png b/src/assets/icon/apple-icon-57x57.png similarity index 100% rename from src/public/icon/apple-icon-57x57.png rename to src/assets/icon/apple-icon-57x57.png diff --git a/src/public/icon/apple-icon-60x60.png b/src/assets/icon/apple-icon-60x60.png similarity index 100% rename from src/public/icon/apple-icon-60x60.png rename to src/assets/icon/apple-icon-60x60.png diff --git a/src/public/icon/apple-icon-72x72.png b/src/assets/icon/apple-icon-72x72.png similarity index 100% rename from src/public/icon/apple-icon-72x72.png rename to src/assets/icon/apple-icon-72x72.png diff --git a/src/public/icon/apple-icon-76x76.png b/src/assets/icon/apple-icon-76x76.png similarity index 100% rename from src/public/icon/apple-icon-76x76.png rename to src/assets/icon/apple-icon-76x76.png diff --git a/src/public/icon/apple-icon-precomposed.png b/src/assets/icon/apple-icon-precomposed.png similarity index 100% rename from src/public/icon/apple-icon-precomposed.png rename to src/assets/icon/apple-icon-precomposed.png diff --git a/src/public/icon/apple-icon.png b/src/assets/icon/apple-icon.png similarity index 100% rename from src/public/icon/apple-icon.png rename to src/assets/icon/apple-icon.png diff --git a/src/public/icon/browserconfig.xml b/src/assets/icon/browserconfig.xml similarity index 100% rename from src/public/icon/browserconfig.xml rename to src/assets/icon/browserconfig.xml diff --git a/src/public/icon/favicon-16x16.png b/src/assets/icon/favicon-16x16.png similarity index 100% rename from src/public/icon/favicon-16x16.png rename to src/assets/icon/favicon-16x16.png diff --git a/src/public/icon/favicon-32x32.png b/src/assets/icon/favicon-32x32.png similarity index 100% rename from src/public/icon/favicon-32x32.png rename to src/assets/icon/favicon-32x32.png diff --git a/src/public/icon/favicon-96x96.png b/src/assets/icon/favicon-96x96.png similarity index 100% rename from src/public/icon/favicon-96x96.png rename to src/assets/icon/favicon-96x96.png diff --git a/src/public/icon/favicon.ico b/src/assets/icon/favicon.ico similarity index 100% rename from src/public/icon/favicon.ico rename to src/assets/icon/favicon.ico diff --git a/src/public/icon/ms-icon-144x144.png b/src/assets/icon/ms-icon-144x144.png similarity index 100% rename from src/public/icon/ms-icon-144x144.png rename to src/assets/icon/ms-icon-144x144.png diff --git a/src/public/icon/ms-icon-150x150.png b/src/assets/icon/ms-icon-150x150.png similarity index 100% rename from src/public/icon/ms-icon-150x150.png rename to src/assets/icon/ms-icon-150x150.png diff --git a/src/public/icon/ms-icon-310x310.png b/src/assets/icon/ms-icon-310x310.png similarity index 100% rename from src/public/icon/ms-icon-310x310.png rename to src/assets/icon/ms-icon-310x310.png diff --git a/src/public/icon/ms-icon-70x70.png b/src/assets/icon/ms-icon-70x70.png similarity index 100% rename from src/public/icon/ms-icon-70x70.png rename to src/assets/icon/ms-icon-70x70.png diff --git a/src/public/img/angular-logo.png b/src/assets/img/angular.png similarity index 100% rename from src/public/img/angular-logo.png rename to src/assets/img/angular.png diff --git a/src/assets/img/tipe.png b/src/assets/img/tipe.png new file mode 100644 index 0000000000..4939f07061 Binary files /dev/null and b/src/assets/img/tipe.png differ diff --git a/src/assets/manifest.json b/src/assets/manifest.json new file mode 100644 index 0000000000..850f16fb8e --- /dev/null +++ b/src/assets/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "App", + "icons": [ + { + "src": "/assets/icon/android-icon-36x36.png", + "sizes": "36x36", + "type": "image/png" + }, + { + "src": "/assets/icon/android-icon-48x48.png", + "sizes": "48x48", + "type": "image/png" + }, + { + "src": "/assets/icon/android-icon-72x72.png", + "sizes": "72x72", + "type": "image/png" + }, + { + "src": "/assets/icon/android-icon-96x96.png", + "sizes": "96x96", + "type": "image/png" + }, + { + "src": "/assets/icon/android-icon-144x144.png", + "sizes": "144x144", + "type": "image/png" + }, + { + "src": "/assets/icon/android-icon-192x192.png", + "sizes": "192x192", + "type": "image/png" + } + ] +} diff --git a/src/assets/mock-data/mock-data.json b/src/assets/mock-data/mock-data.json new file mode 100644 index 0000000000..d7285e8e72 --- /dev/null +++ b/src/assets/mock-data/mock-data.json @@ -0,0 +1,3 @@ +[ + {"res": "data"} +] diff --git a/src/public/robots.txt b/src/assets/robots.txt similarity index 100% rename from src/public/robots.txt rename to src/assets/robots.txt diff --git a/src/public/service-worker.js b/src/assets/service-worker.js similarity index 100% rename from src/public/service-worker.js rename to src/assets/service-worker.js diff --git a/src/bootstrap.ts b/src/bootstrap.ts deleted file mode 100644 index a700d0880d..0000000000 --- a/src/bootstrap.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Providers provided by Angular - */ -import {bootstrap} from 'angular2/platform/browser'; -import {ROUTER_PROVIDERS} from 'angular2/router'; -import {HTTP_PROVIDERS} from 'angular2/http'; -// include for development builds -import {ELEMENT_PROBE_PROVIDERS} from 'angular2/platform/common_dom'; -// include for production builds -// import {enableProdMode} from 'angular2/core'; - -/* - * App Component - * our top level component that holds all of our components - */ -import {App} from './app/app'; - -/* - * Bootstrap our Angular app with a top level component `App` and inject - * our Services and Providers into Angular's dependency injection - */ -// enableProdMode() // include for production builds -function main() { - return bootstrap(App, [ - // These are dependencies of our App - HTTP_PROVIDERS, - ROUTER_PROVIDERS, - ELEMENT_PROBE_PROVIDERS // remove in production - ]) - .catch(err => console.error(err)); -} - -document.addEventListener('DOMContentLoaded', main); diff --git a/src/custom-typings.d.ts b/src/custom-typings.d.ts new file mode 100644 index 0000000000..6a9f6d22af --- /dev/null +++ b/src/custom-typings.d.ts @@ -0,0 +1,141 @@ +/* + * Custom Type Definitions + * When including 3rd party modules you also need to include the type definition for the module + * if they don't provide one within the module. You can try to install it with @types + +npm install @types/node +npm install @types/lodash + + * If you can't find the type definition in the registry we can make an ambient/global definition in + * this file for now. For example + +declare module 'my-module' { + export function doesSomething(value: string): string; +} + + * If you are using a CommonJS module that is using module.exports then you will have to write your + * types using export = yourObjectOrFunction with a namespace above it + * notice how we have to create a namespace that is equal to the function we're + * assigning the export to + +declare module 'jwt-decode' { + function jwtDecode(token: string): any; + namespace jwtDecode {} + export = jwtDecode; +} + + * + * If you're prototying and you will fix the types later you can also declare it as type any + * + +declare var assert: any; +declare var _: any; +declare var $: any; + + * + * If you're importing a module that uses Node.js modules which are CommonJS you need to import as + * in the files such as main.browser.ts or any file within app/ + * + +import * as _ from 'lodash' + + * You can include your type definitions in this file until you create one for the @types + * + */ + +// support NodeJS modules without type definitions +declare module '*'; + +/* +// for legacy tslint etc to understand rename 'modern-lru' with your package +// then comment out `declare module '*';`. For each new module copy/paste +// this method of creating an `any` module type definition +declare module 'modern-lru' { + let x: any; + export = x; +} +*/ + +// Extra variables that live on Global that will be replaced by webpack DefinePlugin +declare var ENV: string; +declare var HMR: boolean; +declare var System: SystemJS; +// declare const FIREBASE_CONFIG: FirebaseConfig; + +interface FirebaseConfig { + apiKey: string; + authDomain: string; + databaseURL: string; + projectId: string; + storageBucket: string; + messagingSenderId: string; +} + +interface SystemJS { + import: (path?: string) => Promise; +} + +interface GlobalEnvironment { + ENV: string; + HMR: boolean; + SystemJS: SystemJS; + System: SystemJS; + // FIREBASE_CONFIG: FirebaseConfig; +} + +interface Es6PromiseLoader { + (id: string): (exportName?: string) => Promise; +} + +type FactoryEs6PromiseLoader = () => Es6PromiseLoader; +type FactoryPromise = () => Promise; + +type AsyncRoutes = { + [component: string]: Es6PromiseLoader | + Function | + FactoryEs6PromiseLoader | + FactoryPromise ; +}; + +type IdleCallbacks = Es6PromiseLoader | + Function | + FactoryEs6PromiseLoader | + FactoryPromise ; + +interface WebpackModule { + hot: { + data?: any, + idle: any, + accept(dependencies?: string | string[], callback?: (updatedDependencies?: any) => void): void; + decline(deps?: any | string | string[]): void; + dispose(callback?: (data?: any) => void): void; + addDisposeHandler(callback?: (data?: any) => void): void; + removeDisposeHandler(callback?: (data?: any) => void): void; + check(autoApply?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; + apply(options?: any, callback?: (err?: Error, outdatedModules?: any[]) => void): void; + status(callback?: (status?: string) => void): void | string; + removeStatusHandler(callback?: (status?: string) => void): void; + }; +} + +interface WebpackRequire { + (id: string): any; + (paths: string[], callback: (...modules: any[]) => void): void; + ensure(ids: string[], callback: (req: WebpackRequire) => void, chunkName?: string): void; + context(directory: string, useSubDirectories?: boolean, regExp?: RegExp): WebpackContext; +} + +interface WebpackContext extends WebpackRequire { + keys(): string[]; +} + +interface ErrorStackTraceLimit { + stackTraceLimit: number; +} + +// Extend typings +interface NodeRequire extends WebpackRequire {} +interface ErrorConstructor extends ErrorStackTraceLimit {} +interface NodeRequireFunction extends Es6PromiseLoader {} +interface NodeModule extends WebpackModule {} +interface Global extends GlobalEnvironment {} diff --git a/src/environments/environment.e2e.prod.ts b/src/environments/environment.e2e.prod.ts new file mode 100644 index 0000000000..2aaa245f23 --- /dev/null +++ b/src/environments/environment.e2e.prod.ts @@ -0,0 +1,26 @@ +/* tslint:disable */ +import { enableProdMode, NgModuleRef } from '@angular/core'; +import { disableDebugTools } from '@angular/platform-browser'; +import { Environment } from './model'; + +enableProdMode(); + +// export const ENV_FIREBASE_CONFIG: any = FIREBASE_CONFIG; + +export const environment: Environment = { + production: true, + showDevModule: true, + + /** Angular debug tools in the dev console + * https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md + * @param modRef + * @return {any} + */ + decorateModuleRef(modRef: NgModuleRef) { + disableDebugTools(); + return modRef; + }, + ENV_PROVIDERS: [ + + ] +}; diff --git a/src/environments/environment.prod.ts b/src/environments/environment.prod.ts new file mode 100644 index 0000000000..7c04dd7b9a --- /dev/null +++ b/src/environments/environment.prod.ts @@ -0,0 +1,26 @@ +/* tslint:disable */ +import { enableProdMode, NgModuleRef } from '@angular/core'; +import { disableDebugTools } from '@angular/platform-browser'; +import { Environment } from './model'; + +enableProdMode(); + +// export const ENV_FIREBASE_CONFIG: any = FIREBASE_CONFIG; + +export const environment: Environment = { + production: true, + showDevModule: false, + + /** Angular debug tools in the dev console + * https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md + * @param modRef + * @return {any} + */ + decorateModuleRef(modRef: NgModuleRef) { + disableDebugTools(); + return modRef; + }, + ENV_PROVIDERS: [ + + ] +}; diff --git a/src/environments/environment.ts b/src/environments/environment.ts new file mode 100644 index 0000000000..995732f715 --- /dev/null +++ b/src/environments/environment.ts @@ -0,0 +1,36 @@ +/* tslint:disable */ + +import { ApplicationRef, NgModuleRef } from '@angular/core'; +import { enableDebugTools } from '@angular/platform-browser'; +import { Environment } from './model'; + +Error.stackTraceLimit = Infinity; +require('zone.js/dist/long-stack-trace-zone'); + +// export const ENV_FIREBASE_CONFIG: any = FIREBASE_CONFIG; + +export const environment: Environment = { + production: false, + + showDevModule: true, + + /** Angular debug tools in the dev console + * https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md + * @param modRef + * @return {any} + */ + decorateModuleRef(modRef: NgModuleRef) { + const appRef = modRef.injector.get(ApplicationRef); + const cmpRef = appRef.components[0]; + + let _ng = (window).ng; + enableDebugTools(cmpRef); + (window).ng.probe = _ng.probe; + (window).ng.coreTokens = _ng.coreTokens; + return modRef; + }, + ENV_PROVIDERS: [ + + ] +}; + diff --git a/src/environments/model.ts b/src/environments/model.ts new file mode 100644 index 0000000000..2c46f0e828 --- /dev/null +++ b/src/environments/model.ts @@ -0,0 +1,8 @@ +import { NgModuleRef } from '@angular/core'; + +export interface Environment { + production: boolean; + ENV_PROVIDERS: any; + showDevModule: boolean; + decorateModuleRef(modRef: NgModuleRef): NgModuleRef; +} diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000000..502936bd3c --- /dev/null +++ b/src/index.html @@ -0,0 +1,54 @@ + + + + + + + <%= htmlWebpackPlugin.options.title %> + + + + <% if (webpackConfig.htmlElements.headTags) { %> + + <%= webpackConfig.htmlElements.headTags %> + <% } %> + + <%= htmlWebpackPlugin.files.webpackManifest %> + + <% if (htmlWebpackPlugin.options.metadata.isDevServer && htmlWebpackPlugin.options.metadata.HMR !== true) { %> + + + <% } %> + + + <% if (htmlWebpackPlugin.options.gtmKey) { %> + + + + <% } %> + + + + + + + + +<% if (htmlWebpackPlugin.options.gtmKey) { %> + + + +<% } %> + + + Loading... + + + + + diff --git a/src/main.browser.ts b/src/main.browser.ts new file mode 100644 index 0000000000..170a5c4ad0 --- /dev/null +++ b/src/main.browser.ts @@ -0,0 +1,62 @@ +/** + * Angular bootstrapping + */ +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; +import { environment } from 'environments/environment'; +import { NgModuleRef } from '@angular/core'; + +/** + * App Module + * our top level module that holds all of our components + */ +import { AppModule } from './app'; +import { ROOT_SELECTOR } from './app/app.component'; + +/** + * Bootstrap our Angular app with a top level NgModule + */ +export function main(): Promise { + let modulePromise: Promise> = null; + + if (module['hot']) { + module['hot'].accept(); + module['hot'].dispose(() => { + // Before restarting the app, we create a new root element and dispose the old one + const oldRootElem = document.querySelector(ROOT_SELECTOR); + const newRootElem = document.createElement(ROOT_SELECTOR); + oldRootElem!.parentNode!.insertBefore(newRootElem, oldRootElem); + if (modulePromise) { + modulePromise.then((appModule) => { + appModule.destroy(); + if (oldRootElem !== null) { + oldRootElem!.parentNode!.removeChild(oldRootElem); + } + return appModule; + }); + } + }); + } + + modulePromise = platformBrowserDynamic().bootstrapModule(AppModule); + + return modulePromise.then(environment.decorateModuleRef).catch((err) => console.error(err)); +} + +/** + * Needed for hmr + * in prod this is replace for document ready + */ +switch (document.readyState) { + case 'loading': + document.addEventListener('DOMContentLoaded', _domReadyHandler, false); + break; + case 'interactive': + case 'complete': + default: + main(); +} + +function _domReadyHandler() { + document.removeEventListener('DOMContentLoaded', _domReadyHandler, false); + main(); +} diff --git a/src/meta/humans.txt b/src/meta/humans.txt new file mode 100644 index 0000000000..b2d8794194 --- /dev/null +++ b/src/meta/humans.txt @@ -0,0 +1,17 @@ +# humanstxt.org/ +# The humans responsible & technology colophon + +# TEAM + + -- -- + +# THANKS + + + PatrickJS -- @gdi2290 + AngularClass -- @AngularClass + +# TECHNOLOGY COLOPHON + + HTML5, CSS3 + Angular2, TypeScript, Webpack diff --git a/src/meta/robots.txt b/src/meta/robots.txt new file mode 100644 index 0000000000..941749507a --- /dev/null +++ b/src/meta/robots.txt @@ -0,0 +1,3 @@ +# robotstxt.org + +User-agent: * diff --git a/src/polyfills.browser.ts b/src/polyfills.browser.ts new file mode 100644 index 0000000000..77edce8764 --- /dev/null +++ b/src/polyfills.browser.ts @@ -0,0 +1,79 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +// Internet Explorer 9 support +// import 'ie-shim'; + +// IE9, IE10 and IE11 requires all of the following polyfills. +// import 'core-js/es6/symbol'; +// import 'core-js/es6/object'; +// import 'core-js/es6/function'; +// import 'core-js/es6/parse-int'; +// import 'core-js/es6/parse-float'; +// import 'core-js/es6/number'; +// import 'core-js/es6/math'; +// import 'core-js/es6/string'; +// import 'core-js/es6/date'; +// import 'core-js/es6/array'; +// import 'core-js/es6/regexp'; +// import 'core-js/es6/map'; +// import 'core-js/es6/weak-map'; +// import 'core-js/es6/set'; + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +// Evergreen browsers require these. +import 'core-js/es6/reflect'; +import 'core-js/es7/reflect'; + +/** + * Required to support Web Animations `@angular/animation`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation + */ + +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/*************************************************************************************************** + * Zone JS is required by Angular itself. + */ +import 'zone.js/dist/zone'; +// import 'zone.js/dist/long-stack-trace-zone' // async stack traces with zone.js included for dev + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ + +/** + * Date, currency, decimal and percent pipes. + * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 + */ +// import 'intl'; // Run `npm install --save intl`. +/** + * Need to import at least one locale-data with intl. + */ +// import 'intl/locale-data/jsonp/en'; +if ('production' === ENV) { + // Production + +} else { + + // Development +} diff --git a/src/public/img/angularclass-logo.png b/src/public/img/angularclass-logo.png deleted file mode 100644 index 4342316a84..0000000000 Binary files a/src/public/img/angularclass-logo.png and /dev/null differ diff --git a/src/public/index.html b/src/public/index.html deleted file mode 100644 index 9904cc5794..0000000000 --- a/src/public/index.html +++ /dev/null @@ -1,60 +0,0 @@ - - - - Angular2 Webpack Starter by @gdi2990 from @AngularClass - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Loading... - - - - - - - - - - - - - - diff --git a/src/public/manifest.json b/src/public/manifest.json deleted file mode 100644 index d40b70567a..0000000000 --- a/src/public/manifest.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "App", - "icons": [ - { - "src": "/icon/android-icon-36x36.png", - "sizes": "36x36", - "type": "image/png", - "density": "0.75" - }, - { - "src": "/icon/android-icon-48x48.png", - "sizes": "48x48", - "type": "image/png", - "density": "1.0" - }, - { - "src": "/icon/android-icon-72x72.png", - "sizes": "72x72", - "type": "image/png", - "density": "1.5" - }, - { - "src": "/icon/android-icon-96x96.png", - "sizes": "96x96", - "type": "image/png", - "density": "2.0" - }, - { - "src": "/icon/android-icon-144x144.png", - "sizes": "144x144", - "type": "image/png", - "density": "3.0" - }, - { - "src": "/icon/android-icon-192x192.png", - "sizes": "192x192", - "type": "image/png", - "density": "4.0" - } - ] -} diff --git a/src/styles/_variables.scss b/src/styles/_variables.scss new file mode 100644 index 0000000000..0644143bc7 --- /dev/null +++ b/src/styles/_variables.scss @@ -0,0 +1 @@ +$nav-button-color: #00838F; \ No newline at end of file diff --git a/src/styles/headings.css b/src/styles/headings.css new file mode 100644 index 0000000000..6fe295cfed --- /dev/null +++ b/src/styles/headings.css @@ -0,0 +1,3 @@ +h1 { + color: #00BCD4; +} \ No newline at end of file diff --git a/src/styles/styles.scss b/src/styles/styles.scss new file mode 100644 index 0000000000..948e97dc71 --- /dev/null +++ b/src/styles/styles.scss @@ -0,0 +1,19 @@ +/* this file will be extracted to main dist folder and is imported in index.html */ +/* This file is for setting global styles */ +@import 'variables'; + +nav { + margin-top: 16px; +} + +nav a { + background-color: $nav-button-color; + color: white; + padding: 8px 16px; + margin: 8px; + vertical-align: middle; + line-height: 1.25; + text-align: center; + text-decoration: none; + border-radius: 4px; +} diff --git a/src/vendor.ts b/src/vendor.ts deleted file mode 100644 index d368fcddc9..0000000000 --- a/src/vendor.ts +++ /dev/null @@ -1,19 +0,0 @@ -// Polyfills -import 'es6-shim'; -import 'es6-promise'; -// (these modules are what is in 'angular2/bundles/angular2-polyfills' so don't use that here) -import 'es7-reflect-metadata/dist/browser'; -import 'zone.js/lib/browser/zone-microtask'; -import 'zone.js/lib/browser/long-stack-trace-zone'; // in Production you may want to remove this - -// Angular 2 -import 'angular2/platform/browser'; -import 'angular2/platform/common_dom'; -import 'angular2/core'; -import 'angular2/router'; -import 'angular2/http'; - -// RxJS -import 'rxjs'; - -// Other vendors for example jQuery or Lodash diff --git a/test/app/app.e2e.js b/test/app/app.e2e.js deleted file mode 100644 index 7c258d8730..0000000000 --- a/test/app/app.e2e.js +++ /dev/null @@ -1,35 +0,0 @@ - /* - * TODO: ES5 for now until I make a webpack plugin for protractor - */ -describe('App', function() { - - beforeEach(function() { - browser.get('/'); - }); - - - it('should have a title', function() { - var subject = browser.getTitle(); - var result = 'Angular2 Webpack Starter by @gdi2990 from @AngularClass'; - expect(subject).toEqual(result); - }); - - it('should have
', function() { - var subject = element(by.deepCss('app /deep/ header')).isPresent(); - var result = true; - expect(subject).toEqual(result); - }); - - it('should have
', function() { - var subject = element(by.deepCss('app /deep/ main')).isPresent(); - var result = true; - expect(subject).toEqual(result); - }); - - it('should have