LoginSignup
88
75

More than 5 years have passed since last update.

TypeScript 2.7.1 以降での import の書き方

Posted at

https://qiita.com/karak/items/29ff148788f5abb15331 の続編。

結局、どの CommonJS モジュールをどうやって import すればいいんだときかれたので回答。
export のパターンごとに対応する import を列挙するので参考にしてほしい。必要に応じて型定義ファイルも示してある。

はじめにES6流儀のモジュールの書き方をおさらいする。

Named export 型

条件:
export default 以外の export member 文のみで構成されている。

モジュール

fs/index.mjs
export function readFileSync() { ... }

アプリケーションコード

app.ts
import * as fs from 'fs';

fs.readFileAsync();

import { readFileAsync } from 'fs' ももちろん可。

Default export 型

条件:
export default が使われている。

material-ui/components/Button.mjs
var Button = ...;

export default Button;

アプリケーションコード

app.ts
import Button from 'material-ui/components/Button';

React.createElement(Button);

バリエーション

export default とそれ以外の export member 文が混在する場合は、下の記法を使う。

material-ui/components/Button.mjs
var styles = ...;
var Button = ...;

export styles;
export default Button;
app.ts
import {
  default as Button,
  styles,
} from 'material-ui/components/Button';

React.createElement(Button);

ES6 Modules の仕様を熟知していれば言わずもがなだが、念のため。

以下は CommonJS 型で書いてあるパターン。

名前空間型-A

条件:
exports.member = (または module.member =) だけで書かれている。
※ ただし、member に "default" がない前提。

モジュール

fs/index.js
exports.readFileSync = function() { ... }

アプリケーションコード

app.ts
import * as fs from 'fs';

fs.readFileAsync();

名前空間型-B

条件:
exports = (または module.exports =)で書かれ、かつ exports されたものが、関数でもクラス(コンストラクタ)でもないオブジェクトである。

モジュール

fs/index.js
var fs = { };
fs.readFileSync = function() { ... }
exports = fs;

型定義

@types/fs/index.d.ts
export function readFileSync(): void { ... };

アプリケーションコード

app.ts
import * as fs from 'fs';

fs.readFileAsync();

Callable 型

条件:
exports = (または module.exports =)で書かれ、かつ exports されたものに、関数かクラス(コンストラクタ)である。あるいはその要素を含む。

モジュール

jquery/index.js
var jQuery = function () { ... }
jQuery.each = function (array, cb) { ... }
...
exports = jQuery;
// module.exports = jQuery; も同じ

型定義

@types/jquery/index.d.ts
interface jQueryStatic {
   (selector: string): jQueryStatic;
   each<T>(array: T[], cb: (x: T, i: number) => any): jQueryStatic;
   ...
}
declare var jQuery jQueryStatic;
exports = jQuery;

アプリケーションコード

app.ts
import jQuery = require('jquery');

jQuery('#app');

終わりに

すべてのモジュールがES6形式で書かれる日がくることを切に願う。

88
75
1

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
88
75