関数などを別ファイルに分割したい場合。
復数に分割したファイルをそのまま<script src="xxx.js"></script>
としても取り込んでもjavascriptは実行できない。
といったことが考えられるが、一番簡単なのはparcelを使用することのようだ。
// プロジェクトのディレクトリに移動して >npm init
>npm install --save-dev parcel
export default function getAsterString(target:string):string{ return "*" + target + "*" }
import getAsterString from "./func" ... console.log(getAsterString("aaa"))
> npx parcel index.html --open
npx parcel build index.html
htmlファイルのjs参照が
<script src=“main.ts”></script>
のようにトップディレクトリにあると、ビルド後は
<script src=“/main.2799c73f.js”>となってしまい、jsが参照できない。
サブディレクトリを作成してtsの作成やコンパイルをするか、コンパイル後のhtmlの参照を
<script src=“./main.2799c73f.js”>
<script src=“main.2799c73f.js”>
と変更する必要がある。
export function getAsterString(target:string):string{ return "*" + target + "*" }
import { getAsterString } from "./comm/func" console.log(getAsterString("aaa"))
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ ↓moduleの設定を変える "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ "module": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
tsc の–outオプションを付けて1つのファイルにまとめて出力するか、出来上がったjsファイルをすべて参照する必要がある。
<body> ... <script src="./comm/func.js"></script> <script src="./main.js"></script> </body> </html>
// 実際にはまとまらない... >tsc main.ts comm/func.ts --out all.js comm/func.ts:1:17 - error TS6131: Cannot compile modules using option 'out' unless the '--module' flag is 'amd' or 'system'.
>tsc main.ts comm/func.ts