Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing basic DOM types in TypeScript project

I am setting a web app up in TypeScript and I seem to be missing some basic types I need.

When I compile (npm run build), I get the following errors,

error TS2304: Cannot find name 'HTMLElement'.

error TS2304: Cannot find name 'SVGElement'.

error TS2304: Cannot find name 'EventTarget'.

error TS2304: Cannot find name 'TouchEvent'.

error TS2304: Cannot find name 'MouseEvent'.

error TS2304: Cannot find name 'PointerEvent'.

Based on my Googling I assuming I am missing something basic in my project setup. It seems like these types are just assumed to be there with Typescript.

EDIT: Specially it should be part of the ES6 types, https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts.

Here is my package.json file:

{
  "name": "wip",
  "version": "1.0.0",
  "description": "",
  "main": "index.html",
  "dependencies": {
    "hammerjs": "2.0.8"
  },
  "devDependencies": {
    "@types/chai": "3.4.35",
    "@types/mocha": "2.2.39",
    "@types/node": "7.0.5",
    "@types/hammerjs": "2.0.34",
    "chai": "3.5.0",
    "mocha": "3.2.0",
    "safe-mock": "0.2.0",
    "ts-node": "2.1.0",
    "tslint": "4.5.1",
    "typescript": "2.2.1",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.1"
  },
  "scripts": {
    "test": "mocha test --require ts-node/register test/**/*.ts && npm run build",
    "dev": "webpack-dev-server --watch --content-base . -d --progress",
    "build": "tsc"
  },
  "author": "",
  "license": "ISC"
}

Any suggestions?

like image 547
James McMahon Avatar asked Mar 05 '17 02:03

James McMahon


2 Answers

Try adding the following lib section to your tsconfig.json file.

{
    "compilerOptions": {
        "lib": [
            "es2016",
            "dom"
        ]
    }
}
like image 115
Shaun Luttin Avatar answered Oct 19 '22 07:10

Shaun Luttin


Additional answer for testing.

If using mocha, you also need to tell mocha about the DOM environment using jsdom.

https://journal.artfuldev.com/unit-testing-node-applications-with-typescript-using-mocha-and-chai-384ef05f32b2

$ npm install jsdom jsdom-global --save-dev

So your "test" script would add -r jsdom-global/register:

{
  "scripts": {
    "test": "mocha test -r ts-node/register -r jsdom-global/register test/**/*.ts && npm run build"
  }
}
like image 1
Xeoncross Avatar answered Oct 19 '22 06:10

Xeoncross