SharePoint Framework SPFX with Angular2 and TypeScript – Part 1

Pankaj Salunkhe

Pankaj Salunkhe

Technical Specialist at CG
Microsoft Certified Solution expert in SharePoint and O365 with 9+ years of experience.

write to admin@sharecareinspire.com for contribution
Pankaj Salunkhe

Latest posts by Pankaj Salunkhe (see all)

<<SharePoint Framework SPFx      >> Part 2      Download code

Introduction

This article explains how to develop SharePoint online web part with open source web stack Angualr2, TypeScript and SharePoint Framework (SPFx). These technologies are fairly new and equally challenging to digest, especially if you are coming from a background of server side development.

This is whole new world for those who are not aware of open source web stack and client side frameworks. For me also this journey was pretty challenging, I use word challenging because I had to unlearn my old school concepts of server side programming and get into new world right from scratch.

So if you really want to learn SharePoint framework and development using open source web stack, you need to understand few new tools and frameworks. For more details on installations steps of web stack please refer article Open Source Web Stack

This articles is solely for developers who are beginners in Angular2, TypeScript and SharePoint Framework, and who want to try hands on available open source.

SharePoint Framework

if you want to know more about SharePoint, you can refer article <<SharePoint Framework SPFx

Why SharePoint Framework?

1. It enables developers to leverage the latest JavaScript frameworks like React and Angular.

2. Provides better experience, performance, mobile support while extending developer ecosystem from .NET and beyond.

3. Provides structured approach to modern end-to-end app development, which is not dependent on .NET.

4. SPFx page structure allows developers of all skill levels to extend SharePoint capabilities more efficiently, reliably and faster which is mobile ready and responsive .

Angular2

Angular2 is different than former AngularJS framework. Angular2 is a TypeScript based open source front end web application platform led by the Angular Team at Google and by a community of individuals and corporations to address all of the parts of the developer’s workflow while building complex web applications.

Angular is a complete rewrite from the same team that built AngularJS. Angular recommends use of TypeScript for development. not getting into depth of Angular2 here, but following flow would give you some insights.

TypeScript

TypeScript is a free and open source programming language developed and maintained by Microsoft.  It is a strict syntactical superset of JavaScript, and adds class-based object-oriented programming to the language. TypeScript may be used to develop JavaScript applications for client-side or server-side (Node.js) execution.

As TypeScript is a superset of JavaScript, any existing JavaScript programs are also valid TypeScript programs. TypeScript is designed for development of large applications and transcompiles to JavaScript.

 

Lets see step by step how to develop web part on SharePoint online with open source web stack and SPFx.

A part of source code i am referring is from open GitHub repository by community contributors, so you can have a look at it.

If you want to create SPFx web part using full stack, generally you would be using Yeoman for code generation, but my experience is the yeoman code generator is currently not supporting TypeScript+Angular2 as on  June 2017 (correct me if i am wrong). So i decided to create project structure manually.

Now lets see how to develop  web part step by step.

Step 1: Create folder structure and code files

1. Create a folder for your solution (e.g. SPFx_Angular2_TypeScript)

2. Use code . command to open visual studio code

3. Create file tsconfig.json

Create a File tsconfig.json under folder SPFX_Angular2_Typescript through visual studio code and add below code in tsconfig.json, or even you can use it from git.

The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways.

File: tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "types": [
      "webpack-env"
    ]
  }
}

4. Create file package.json

Create file package.json under folder SPFX_Angular2_Typescript through visual studio code and add below code in package.json.

This file holds various metadata relevant to the project. This file is used to give information to npm that allows it to identify the project as well as handle the project’s dependencies. It can also contain other metadata such as a project description

File: package.json

{
  "name": "ang-2-webparts",
  "version": "0.0.1",
  "private": true,
  "engines": {
    "node": ">=0.10.0"
  },
  "dependencies": {
    "@angular/common": "^2.4.4",
    "@angular/compiler": "^2.4.4",
    "@angular/core": "^2.4.4",
    "@angular/forms": "^2.4.4",
    "@angular/http": "^2.4.4",
    "@angular/platform-browser": "^2.4.4",
    "@angular/platform-browser-dynamic": "^2.4.4",
    "@angular/router": "^3.4.4",
    "@angular/upgrade": "^2.4.4",
    "@microsoft/sp-client-base": "~0.7.0",
    "@microsoft/sp-client-preview": "~0.9.0",
    "@microsoft/sp-core-library": "~0.1.2",
    "@microsoft/sp-webpart-base": "~0.4.0",
    "@types/webpack-env": ">=1.12.1 <1.14.0",
    "reflect-metadata": "^0.1.9",
    "rxjs": "^5.0.3",
    "zone.js": "^0.7.6"
  },
  "devDependencies": {
    "@microsoft/sp-build-web": "~0.9.0",
    "@microsoft/sp-module-interfaces": "~0.7.0",
    "@microsoft/sp-webpart-workbench": "~0.8.0",
    "@types/chai": "^3.4.34",
    "@types/mocha": "^2.2.38",
    "gulp": "~3.9.1"
  },
  "scripts": {
    "build": "gulp bundle",
    "clean": "gulp clean",
    "test": "gulp test"
  }
}

5. Run npm Install

npm install  command is used for installing dependent modules which are mentioned in packages.json file.  This command creates node_modules directory in your current directory (if one doesn’t exist yet), and will download the package to that directory.

6. Create folder structure for source code

Create following folder structure under folder SPFX_Angular2_Typescript.
This folder structure is used to store all the source code files of TypeScript.

7. Create file BaseAngular2WebPart.ts

You can download this file from this GitHub location. This is the default base class for Angular2 client side web parts, all the web parts should inherit from this class.

8. Create file en-us.js

Create file en-us.js under loc folder, and add below code in en-us.js file.

This is a locale file, probably if you want to use multilingual, honestly I have not explored much about it.

File: en-us.js

define([], function() {
  return {
    "PropertyPaneDescription": "Description",
    "BasicGroupName": "Group Name",
    "DescriptionFieldLabel": "Description Field"
  }
});

9. Create file mystrings.d.ts

Create file mystrings.d.ts under loc folder and add below code in mystrings.d.ts file. This is the interface file which will be imported in the web part file used for the properties of web part.

File: mystrings.d.ts

declare interface ITodoStrings {
  PropertyPaneDescription: string;
  BasicGroupName: string;
  DescriptionFieldLabel: string;
}

declare module 'todoStrings' {
  const strings: ITodoStrings;
  export = strings;
}

10. Create file ITodoWebPartProps.ts

Create file ITodoWebPartProps.ts under todo folder, and below code in the file. This is an interface file which is getting used to implement web part.

File ITodoWebPartProps.ts

export interface ITodoWebPartProps {
  description: string;
  todos: string[];
}

11. Create file ListComponent.ts

Create file ListComponent.ts under todo folder and add follwing code in the file.

Component is the new concept in Angular2, it consist of following.

Template: This is used to render the view for the application. This contains the HTML that needs to be rendered in the application.
Class: This is like a class defined in any language such as C. This contains properties and methods. This has the code which is used to support the view.
Metadata: This has the extra data defined for the Angular class.

File: ListComponent.ts

import {Component, Input} from '@angular/core';
@Component({
  selector: `list-component`,
  template:
  `<button (click)="addTodo()">Add Item</button>
        <ul>
          <li *ngFor="let todo of todos">
            {{ todo }}
          </li>
        </ul>`
})
export default class ListComponent {
  @Input()
  private todos: string[];
  constructor() {
    console.log('*** ListComponent constructor ***');
  }
  public addTodo(): void {
    this.todos.push(`item ${this.todos.length + 1}`);
  };
}

12. Create files Todo.module.scss & Todo.module.scss.ts

You can download scss file from GitHub repository. This is a CSS file which contains the classes to apply on HTML.

File: Todo.module.scss.ts

/* tslint:disable */
require('Todo.module.css');
const styles = {
  row: 'row_9768566e',
  column: 'column_0ea28010',
  title: 'title_b1a7976c',
  subtitle: 'subtitle_fb529e76',
  description: 'description_37a84ec1',
  button: 'button_30f578eb',
};
export default styles;
/* tslint:enable */

13.  Create file TodoWebPart.manifest.json

Create file TodoWebPart.manifest.json under todo folder add following code in the file. The manifest.json file contains all core details such as the display name and description, other associations are also specified here such as the associated JavaScript file a bundle and any dependent JavaScript modules which will be loaded.

File: TodoWebPart.manifest.json

{
  "$schema": "../../../node_modules/@microsoft/sp-module-interfaces/lib/manifestSchemas/jsonSchemas/clientSideComponentManifestSchema.json",
  "id": "50548cd6-7ad8-4bb1-94f2-433d7445d778",
  "alias": "ItemWebPart",
  "componentType": "WebPart",
  "version": "0.0.1",
  "manifestVersion": 2,
  "preconfiguredEntries": [{
    "groupId": "50548cd6-7ad8-4bb1-94f2-433d7445d778",
    "group": { "default": "Under Development" },
    "title": { "default": "Item" },
    "description": { "default": "Item description" },
    "officeFabricIconFontName": "Page",
    "properties": {
      "description": "Items",
      "todos": []
    }
  }]
}

14. Create TodoWebParts.ts

Create file TodoWebPart.ts under todo folder, you can download the file from GitHub location.

TodoWebParts.ts defines the main entry point for the web part. The web part class TodoWebPart extends the BaseClientSideWebPart. Any client-side web part should extend the BaseClientSideWebPart class in order to be defined as a valid web part.

BaseClientSideWebPart implements the minimal functionality that is required to build a web part. This class also provides many parameters to validate and access to read-only properties such as displayMode, web part properties, web part context, web part instanceId, the web part domElement and much more.
Notice that the web part class is defined to accept a property type ITodoWebPartProps, The property type is defined as an interface in a separate file ITodoWebPartProps.ts.

15. Create file config.json

Create file config.json under config folder and  add following code in the file, this file, this file contains the configuration information of web part, like  first file to be executed by the web part, out put path for the bundle file etc.

File: config.json

{
  "entries": [
    {
      "entry": "./lib/webparts/todo/TodoWebPart.js",
      "manifest": "./src/webparts/todo/TodoWebPart.manifest.json",
      "outputPath": "./dist/todo.bundle.js"
    }
  ],
  "externals": {},
  "localizedResources": {
    "todoStrings": "webparts/todo/loc/{locale}.js"
  }
}

16. Create file package-solution.json

Create file package-solution.json under config folder and add following code in the file. This file contains the information about package and the location where published package will be created .

File: package-solution.json

{
  "solution": {
    "name": "ang-2-webparts-client-side-solution",
    "id": "4f46fa78-b053-4fbb-9b61-f534c4e77bfa",
    "version": "1.0.0.0"
  },
  "paths": {
    "zippedPackage": "solution/ang-2-webparts.sppkg"
  }
}

17. Create file prepare-deploy.json

Create file prepare-deploy.json under config folder add following code in file. This file contains the location where deployable version of solution, this file needs to be modified later with the publicly accessible location where package is uploaded.

File: prepare-deploy.json

{
  "deployCdnPath": "temp/deploy"
}

18. Create file serve.json

Create file serve.json under config folder and add following code in serve.json file. This file contains the information of local workbench site like port, protocol etc. which is automatically hosted by gulp server for testing web parts locally on your development machine.

File: Server.json

{
  "port": 4321,
  "initialPage": "https://localhost:5432/workbench",
  "https": true,
  "api": {
    "port": 5432,
    "entryPath": "node_modules/@microsoft/sp-webpart-workbench/lib/api/"
  }
}

19. Create file tslint.json

Create file tslint.json under config folder, you can download from GitHub location. TSLint is an extensible static analysis tool that checks TypeScript code for readability, maintainability, and functionality errors.

20. Create file write-manifests.json

Create file write-manifests.json under config folder and add following code in write-manifests.json file. This file contains the location of files which are generated using gulp bundle command, and uploaded at publicly accessible location, following steps will show how to update this file.

File: write-manifests.json

{
  "cdnBasePath": "<!-- PATH TO CDN -->"
}

21. Create file gulpfile.js

Create file gulpfile.js under SPFX_Angular2_Typescript folder and add following code in gulpfile.js file. This file contains the dependencies of modules required to run gulp server. Gulpe serve command uses this file to initialize server.

File: gulpfile.js

'use strict';
const gulp = require('gulp');
const build = require('@microsoft/sp-build-web');
build.tslint.isEnabled = () => { return false; }
build.initialize(gulp);

we are now done with the folder structure and source code creation.

Step 2: Build and Deploy on SharePoint online

As this article is getting very very big due to code, I will be covering Build and Deployment steps in part 2.

 

<<SharePoint Framework SPFx      >> Part 2      Download code


Check Articles From Categories      Health and Parenting      Inspiring Stories      Technology      Microsoft Azure      SharePoint O365

Leave a Reply

Your email address will not be published. Required fields are marked *