2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptでrequireを使おうとしたらエラーが出た

Last updated at Posted at 2019-07-29

エラー内容

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が使えるようになる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?