エラー内容
TypeScriptで、
const XMLHttpRequest: any = require("xmlhttprequest").XMLHttpRequest;
とするとrequireが読み込めないエラーになった。
対処方法
npm init
PC:ts User$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (ts)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /Users/katsuki_y/Develop/ts/package.json:
{
"name": "ts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes) yes
これでプロジェクトフォルダ内にpackage.jsonが出来る
npm i @types/node
Node.jsの型定義用のパッケージをインストール
https://www.npmjs.com/package/@types/node
PC:ts User$ npm i @types/node
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN ts@1.0.0 No description
npm WARN ts@1.0.0 No repository field.
+ @types/node@12.6.8
added 1 package in 1.008s
プロジェクトフォルダ内にnode_modules
というフォルダが出来る。
その中の@types/node/globals.d.ts
に定義されているため、requireが使えるようになる。