JavaScriptでやるのはまだ厳しそうなのでimport,exportしたい場合TypeScript使った方がいいかも。
TypwScript 2.8くらいが対象
JavaScript + 型定義ファイル(type.d.ts) のソースをimportする
test.js
function test() {
console.log("test")
}
test.d.ts
declare module "test" {
export function test(): void;
}
import * as test1 from "test" test1.test()
type.d.ts を用意してimportする(declareはアンビエント宣言というらしい)
パスを指定する必要はなくdeclare module "xxxx" のxxxxをimport時に指定する。
type.d.tsは恐らくtscが捕捉できる範囲ならどこでもいい(node_modules以下とtsconfig.jsonのincludeで指定したパス?)
もともとJavaScriptで書かれていて後からTypeScript対応したタイプのライブラリでよく見る。
ES Modules とも互換性がある模様。
type.d.tsファイルの場所は
fsなどの型定義ファイルを参照するとイメージがつかめるかもしれない。
TypeScriptで書かれているコードをimport,exportする
export class Common {
public static test() {
console.log("test")
}
}
export enum TestType {
A,
B,
C,
}
import { Common, TestType } from "./../common"
new Common().test()
importするときのパスは呼び出しファイルからの相対パスになる。
自前でクラスを作成する場合はほぼこの形式。
import{} 内にカンマ区切りでexportしたclass名などを記述することで1ファイル内に記述された複数のクラスを利用できる。
classとenumの組み合わせで使うことが多いか。
1ファイル1クラスのみの場合はexport defaultも使用できる。
export default class Common {
public static test() {
console.log("test")
}
}
import Common from "./../common"
ハマりどころとしてはブラウザの場合はwebpackなどを利用してファイルを結合するなどの対応を入れる必要があるということ、
ちなみに
/// <reference path="xxxx" />
はどうしても型定義を手に入れらない場合やwebpackなどを使用しない場合に使うことになるかもしれない。
webpack使わない時期にやってたりしたがあまり読みやすくはないので使わない方法を考えた方がいいかも。型定義がないなら(opencvとか)自分で型定義を用意してもいい。
現在使用しているTypeScript のオプションは以下
サーバとブラウザで分けているがそれほど違いはないはず
サーバ
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"target": "ES5",
"module": "commonjs",
"sourceMap": true,
"declaration": true,
"inlineSources": true,
"moduleResolution": "node",
"rootDir": ".",
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"forceConsistentCasingInFileNames": false,
"newLine": "LF",
"lib": [
"dom",
"es5",
"es2015.promise"
]
},
"include": [
"routes/*",
"utils/*",
"test/*",
"devtools/*"
]
}
ブラウザ
{
"compilerOptions": {
"outDir": "./built/",
"sourceMap": true,
"strict": true,
"noImplicitReturns": true,
"module": "es2015",
"moduleResolution": "node",
"target": "es5"
},
"include": [
"./public/javascripts/*",
"./public/javascripts/**/*"
]
}
参考
https://www.typescriptlang.org/docs/handbook/modules.html
https://teppeis.hatenablog.com/entry/2017/08/es-modules-in-nodejs
https://qiita.com/kiyodori/items/01d07d5c0659e539ecb9
https://qiita.com/karak/items/29ff148788f5abb15331
https://qiita.com/karak/items/b7af3cb2843c39fb3949
色々あって訳が分からなくなるがこれだけあれば大体の用途には対応できるかと