Modern Web Resource Workspace in Dynamics 365 – Part 1: TypeScript

Web Resources are essential components when you want to extend front-end functionalities in Dynamics 365 Customer Engagement. Where HTML, CSS, and Images are used to design the view layer facing users, JavaScript is used to implement the logic layer behind the view. Those components are the most common and basic in Web and Front-end development.

With today advances in Front-end framework and tools, we can easily build a web component or application with better usability, manageability, extendibility, scalability, maintainability, and testability which are often lacked in plain HTML, JavaScript development. In this series, I will setup a modern workspace to work with Web Resources in D365 using most relevant technologies:

  1. TypeScript, ESLint, Prettier in Visual Studio Code. (Part 1 – This post)
  2. Using declaration files: @types/xrm, XrmDefinitelyTyped (Part 2)
  3. Debugging with Fiddler (Part 3)
  4. Deployment (Part 4)

Why TypeScript?

The main problem, also it’s advantage, with JavaScript is too dynamic. There is no concept of Object Oriented Programming, no Strongly/Static Type. And you don’t know what type of a object, you don’t know what properties and methods of the object. You will need to type exact “strings” which you know “it should work” without any validation, that makes your code prone to errors and hidden bugs, also not ideal for complicated business scenarios or team collaboration.

TypeScript is an object-oriented programming language developed and maintained by Microsoft. It is a superset of JavaScript and contains all of its elements. With the help of TSC (TypeScript Compiler), we can transpile Typescript code (.ts file) to JavaScript (.js file). It does this by supporting static typing so that type mismatches can be caught at compile time rather than at run time. When coupled with tools that understand TypeScript, developers benefit from autocompletion, navigation and refactoring.

TS code transpiles to JS code

Learn more about TypeScript from official docs.

Why ESLint?

TypeScript is a superset of Javascript, there’s nothing prevent you from writing Javascript in a ts file. What’s the point using TypeScript then?! This is where ESLint comes in, it’s like a spell checker for Typescript/Javascript, a code of conduct for developer.

Linting is important to reduce errors and improve the overall quality of your code. Using lint tools can help you accelerate development and reduce costs by finding errors earlier. Simply put, a linter is a tool that programmatically scans your code with the goal of finding issues that can lead to bugs or inconsistencies with code health and style. Some can even help fix them for you! For example:

  • Identify unused variables.
  • Identify unsafe type using.
  • Stop using var, start using let and const.
ESLint Demo

In the TypeScript 2019 Roadmap, the TypeScript core team explains that ESLint has a more performant architecture than TSLint and that they will only be focusing on ESLint when providing editor linting integration for TypeScript. For that reason, I would recommend using ESLint for linting TypeScript projects.

Learn more about ESLint and how to use from official docs.

Why Prettier?

While ESLint is more about enforcing rules in code by showing errors and warnings, Prettier is like “styling-guide” for code which formats your code to look “prettier”, more readable, and more consistent.

ESLint can enforce formatting rules, while Prettier can fix those formatting. Note that ESLint can enforce code-quality rules, but Prettier has nothing to do with those ones.

Prettier Logo

Learn more about Prettier and how to use from official docs.

Why Visual Studio Code?

Visual Studio Code is a lightweight but powerful source code editor that runs on your desktop and is available for Windows, MacOS, and Linux. It comes with built-in support for JavaScript, TypeScript, and Node.js and has a rich ecosystem of extensions for other languages (such as C++, C#, Java, Python, PHP, and Go) and runtimes (such as .Net and Unity).

Aside from the whole idea of being lightweight and starting quickly, VS Code has IntelliSense code completion for variables, methods, and imported modules; graphical debugging; linting, multi-cursor editing, parameter hints, and other powerful editing features; snazzy code navigation and refactoring; and built-in source code control including Git support. Much of this was adapted from Visual Studio technology.

Learn more about VS Code and awesome features from official docs.

Setting up Workspace

Prerequisites

We need to install below tools before setting up our workspace:

  • Visual Studio Code
  • Node.js with NPM
    • Node.js is a JavaScript runtime environment which includes everything you need to execute a program written in JavaScript.
    • NPM is a library/package manager for front-end world, while Nuget package manager is for .Net.

Setup VS Code

Setup below folder hierarchy, and open in VS Code.

  • DCE.WebResources: Workspace folder
    • dce_: solution prefix
    • css: contains all CSS resources
    • html: contains all HTML resources
    • img: contains all images resources
    • js: contains all JavaScript files complied from TS files
    • ts: contains TypeScript source files

Add tsconfig.json file to workspace folder and add below code snippet. This is to specify the compiler options required to compile the project. Learn more about typescript compiler options here.

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "dce_/js",
    "rootDir": "dce_/ts"
  },
  "compileOnSave": true,
  "exclude": ["node_modules"],
  "include": ["dce_/ts/**/*"]
}

Install VS Code Extensions

Open Extensions panel from the left menu (Ctrl+Shift+X), search for ESLint and Prettier extensions and install them.

Install packages

In VS Code, open Terminal by Ctrl+` or menu View > Terminal, enter below command:

npm init

Then enter any appropriate values or use default values. Then a package.json is created, this file is used to keep related information of installed packages/dependencies. It will look like this, you can remove any unnecessary values if you want.

{
  "name": "dce.webresources",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC
}

Use this command to install TypeScript, ESLint and related plugins:

npm i -D typescript eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin

Use this command to install Prettier and related plugins:

npm i -D prettier eslint-config-prettier eslint-plugin-prettier

Next, we configure ESLint by adding a .eslintrc.json configuration file in the root project directory. Learn more configuration options.

{
  "env": {
    "browser": true,
    "commonjs": true
  },
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 5,
    "project": "./tsconfig.json",
    "sourceType": "module", // Allows for the use of imports
    "ecmaFeatures": {
      "jsx": true // Allows for the parsing of JSX
    }
  },
  "plugins": ["@typescript-eslint", "prettier"],
  "extends": [
    "plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    "prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  "rules": {}
}

Make sure that plugin:prettier/recommended is the last configuration in the extends array

Then configure Prettier by adding .prettierrc.json in the root project directory. Learn more configuration options.

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 120,
  "tabWidth": 2,
  "endOfLine": "auto"
}

Automatically fix and format code on save

Adding scripts options to the package.json

{
  "name": "dce.webresources",
  "scripts": {
    "format": "prettier './**/*.ts' --write",
    "lint": "eslint './**/*.ts' --fix"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^3.3.0",
    "@typescript-eslint/parser": "^3.3.0",
    "eslint": "^7.2.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-prettier": "^3.1.4",
    "prettier": "^2.0.5",
    "typescript": "^3.9.5"
  }
}

Run TypeScript Compiler Build Task

Final step is to run the compiler to watch for any changes in ts files and build immediately. Open menu Terminal > Run Build Task (Ctrl+Shift+B), select TSC watch.

Run build task

That’s it! TypeScript workspace is ready for you to build awesome components!

3 thoughts on “Modern Web Resource Workspace in Dynamics 365 – Part 1: TypeScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s