ペットプロジェクトをTypeScriptに変換しようとしていますが、tsc
ユーティリティを使用してファイルを監視およびコンパイルできないようです。ヘルプには、スイッチを使用する必要があると書かれていますが、一部のディレクトリ内のすべてのファイルを再帰的に-w
監視およびコンパイルできないようです。*.ts
これは何かtsc
が処理できるはずのようです。私のオプションは何ですか?
11 に答える
プロジェクトルートで名前が付けられたファイルを作成し、そのtsconfig.json
中に次の行を含めます。
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"module": "commonjs",
"target": "ES5",
"outDir": "ts-built",
"rootDir": "src"
}
}
outDir
コンパイルされたJSファイルを受信するディレクトリのパスであるrootDir
必要があり、ソース(.ts)ファイルを含むディレクトリのパスである必要があることに注意してください。
ターミナルを開いて実行すると、ディレクトリ内のファイルtsc -w
がコンパイルされ、ディレクトリに保存されます。.ts
src
.js
ts-built
TypeScript 1.5ベータ版では、と呼ばれる構成ファイルのサポートが導入されましたtsconfig.json
。そのファイルでは、コンパイラーを構成し、コードのフォーマット規則を定義し、さらに重要なことに、プロジェクト内のTSファイルに関する情報をコンパイラーに提供できます。
正しく構成されたら、tsc
コマンドを実行して、プロジェクト内のすべてのTypeScriptコードをコンパイルすることができます。
ファイルの変更を監視する場合は--watch
、tsc
コマンドに追加するだけです。
tsconfig.jsonファイルの例を次に示します
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false
},
"include": [
"**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]}
上記の例では、すべての.ts
ファイルをプロジェクトに(再帰的に)含めています。"exclude"
配列を持つプロパティを使用してファイルを除外することもできることに注意してください。
詳細については、ドキュメントを参照してください:http ://www.typescriptlang.org/docs/handbook/tsconfig-json.html
このようなすべてのファイルを見ることができます
tsc *.ts --watch
技術的に言えば、ここにはいくつかのオプションがあります。
Sublime TextのようなIDEとTypescript用の統合MSNプラグインを使用している場合:http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled。 aspx.ts
は、ソースを.js
自動的にコンパイルするビルドシステムを作成できます。これを行う方法の説明は次のとおりです。TypeScript用にSublimeビルドシステムを構成する方法。
ファイル保存時にソースコードを宛先.js
ファイルにコンパイルするように定義することもできます。githubでホストされている崇高なパッケージがあります:https ://github.com/alexnj/SublimeOnSaveBuildこれを実現します。ファイルにts
拡張子を含める必要があるだけですSublimeOnSaveBuild.sublime-settings
。
別の可能性は、コマンドラインで各ファイルをコンパイルすることです。次のようにスペースで区切ることにより、一度に複数のファイルをコンパイルすることもできますtsc foo.ts bar.ts
。このスレッドを確認してください:TypeScriptコンパイラに複数のソースファイルを渡すにはどうすればよいですか?、しかし私は最初のオプションがより便利だと思います。
他の答えは何年も前に有用だったかもしれませんが、それらは現在時代遅れです。
プロジェクトにtsconfigファイルがある場合、このコマンドを実行します...
tsc --watch
...変更されたファイルを監視し、必要に応じてコンパイルします。ドキュメントは説明します:
コンパイラを監視モードで実行します。入力ファイルを監視し、変更時に再コンパイルをトリガーします。監視ファイルとディレクトリの実装は、環境変数を使用して構成できます。詳細については、ウォッチの構成を参照してください。
元の質問に答えるために、 Watchの構成に関するドキュメントで説明されているように、ネイティブサポートがないプラットフォームでも再帰的なディレクトリ監視が可能です。
ノードでの再帰的なディレクトリ監視をサポートしていないプラットフォームでのディレクトリの監視は、TSC_WATCHDIRECTORYによって選択されたさまざまなオプションを使用して、子ディレクトリのディレクトリウォッチャーを再帰的に作成することでサポートされます。
tscコンパイラは、コマンドラインで渡したファイルのみを監視します。参照を使用して含まれているファイルは監視されません/// <sourcefile>
。bashを使用している場合は、findを使用してすべての*.ts
ファイルを再帰的に検索し、それらをコンパイルできます。
find . -name "*.ts" | xargs tsc -w
これを自動化するためにgruntを使用することを検討してください。周りには多数のチュートリアルがありますが、ここから簡単に始めます。
次のようなフォルダ構造の場合:
blah/
blah/one.ts
blah/two.ts
blah/example/
blah/example/example.ts
blah/example/package.json
blah/example/Gruntfile.js
blah/example/index.html
次の例のフォルダから、typescriptを簡単に監視および操作できます。
npm install
grunt
package.jsonを使用する場合:
{
"name": "PROJECT",
"version": "0.0.1",
"author": "",
"description": "",
"homepage": "",
"private": true,
"devDependencies": {
"typescript": "~0.9.5",
"connect": "~2.12.0",
"grunt-ts": "~1.6.4",
"grunt-contrib-watch": "~0.5.3",
"grunt-contrib-connect": "~0.6.0",
"grunt-open": "~0.2.3"
}
}
そしてうなり声のファイル:
module.exports = function (grunt) {
// Import dependencies
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-ts');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: { // <--- Run a local server on :8089
options: {
port: 8089,
base: './'
}
}
},
ts: {
lib: { // <-- compile all the files in ../ to PROJECT.js
src: ['../*.ts'],
out: 'PROJECT.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: true,
removeComments: false
}
},
example: { // <--- compile all the files in . to example.js
src: ['*.ts'],
out: 'example.js',
options: {
target: 'es3',
sourceMaps: false,
declaration: false,
removeComments: false
}
}
},
watch: {
lib: { // <-- Watch for changes on the library and rebuild both
files: '../*.ts',
tasks: ['ts:lib', 'ts:example']
},
example: { // <--- Watch for change on example and rebuild
files: ['*.ts', '!*.d.ts'],
tasks: ['ts:example']
}
},
open: { // <--- Launch index.html in browser when you run grunt
dev: {
path: 'http://localhost:8089/index.html'
}
}
});
// Register the default tasks to run when you run grunt
grunt.registerTask('default', ['ts', 'connect', 'open', 'watch']);
}
tsc0.9.1.1には監視機能がないようです。
次のようなPowerShellスクリプトを使用できます。
#watch a directory, for changes to TypeScript files.
#
#when a file changes, then re-compile it.
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "V:\src\MyProject"
$watcher.IncludeSubdirectories = $true
$watcher.EnableRaisingEvents = $true
$changed = Register-ObjectEvent $watcher "Changed" -Action {
if ($($eventArgs.FullPath).EndsWith(".ts"))
{
$command = '"c:\Program Files (x86)\Microsoft SDKs\TypeScript\tsc.exe" "$($eventArgs.FullPath)"'
write-host '>>> Recompiling file ' $($eventArgs.FullPath)
iex "& $command"
}
}
write-host 'changed.Id:' $changed.Id
#to stop the watcher, then close the PowerShell window, OR run this command:
# Unregister-Event < change Id >
今日、私はあなたと同じ問題のためにこのAnt MacroDefを設計しました:
<!--
Recursively read a source directory for TypeScript files, generate a compile list in the
format needed by the TypeScript compiler adding every parameters it take.
-->
<macrodef name="TypeScriptCompileDir">
<!-- required attribute -->
<attribute name="src" />
<!-- optional attributes -->
<attribute name="out" default="" />
<attribute name="module" default="" />
<attribute name="comments" default="" />
<attribute name="declarations" default="" />
<attribute name="nolib" default="" />
<attribute name="target" default="" />
<sequential>
<!-- local properties -->
<local name="out.arg"/>
<local name="module.arg"/>
<local name="comments.arg"/>
<local name="declarations.arg"/>
<local name="nolib.arg"/>
<local name="target.arg"/>
<local name="typescript.file.list"/>
<local name="tsc.compile.file"/>
<property name="tsc.compile.file" value="@{src}compile.list" />
<!-- Optional arguments are not written to compile file when attributes not set -->
<condition property="out.arg" value="" else='--out "@{out}"'>
<equals arg1="@{out}" arg2="" />
</condition>
<condition property="module.arg" value="" else="--module @{module}">
<equals arg1="@{module}" arg2="" />
</condition>
<condition property="comments.arg" value="" else="--comments">
<equals arg1="@{comments}" arg2="" />
</condition>
<condition property="declarations.arg" value="" else="--declarations">
<equals arg1="@{declarations}" arg2="" />
</condition>
<condition property="nolib.arg" value="" else="--nolib">
<equals arg1="@{nolib}" arg2="" />
</condition>
<!-- Could have been defaulted to ES3 but let the compiler uses its own default is quite better -->
<condition property="target.arg" value="" else="--target @{target}">
<equals arg1="@{target}" arg2="" />
</condition>
<!-- Recursively read TypeScript source directory and generate a compile list -->
<pathconvert property="typescript.file.list" dirsep="\" pathsep="${line.separator}">
<fileset dir="@{src}">
<include name="**/*.ts" />
</fileset>
<!-- In case regexp doesn't work on your computer, comment <mapper /> and uncomment <regexpmapper /> -->
<mapper type="regexp" from="^(.*)$" to='"\1"' />
<!--regexpmapper from="^(.*)$" to='"\1"' /-->
</pathconvert>
<!-- Write to the file -->
<echo message="Writing tsc command line arguments to : ${tsc.compile.file}" />
<echo file="${tsc.compile.file}" message="${typescript.file.list}${line.separator}${out.arg}${line.separator}${module.arg}${line.separator}${comments.arg}${line.separator}${declarations.arg}${line.separator}${nolib.arg}${line.separator}${target.arg}" append="false" />
<!-- Compile using the generated compile file -->
<echo message="Calling ${typescript.compiler.path} with ${tsc.compile.file}" />
<exec dir="@{src}" executable="${typescript.compiler.path}">
<arg value="@${tsc.compile.file}"/>
</exec>
<!-- Finally delete the compile file -->
<echo message="${tsc.compile.file} deleted" />
<delete file="${tsc.compile.file}" />
</sequential>
</macrodef>
ビルドファイルで次のように使用します。
<!-- Compile a single JavaScript file in the bin dir for release -->
<TypeScriptCompileDir
src="${src-js.dir}"
out="${release-file-path}"
module="amd"
/>
これは、Webstormを使用して現在取り組んでいるTypeScript用のPureMVCプロジェクトで使用されています。
編集:これは、typescriptソースに複数のtsconfig.jsonファイルがある場合であることに注意してください。私のプロジェクトでは、各tsconfig.jsonファイルを異なる名前の.jsファイルにコンパイルします。これにより、すべてのtypescriptファイルを非常に簡単に監視できます。
すべてのtsconfig.jsonファイルを見つけてバックグラウンドで実行する甘いbashスクリプトを作成しました。次に、ターミナルをCTRL + Cすると、実行中のすべてのtypescriptウォッチコマンドが閉じます。
これはMacOSでテストされていますが、BASH3.2.57がサポートされている場所であればどこでも機能するはずです。将来のバージョンではいくつかの変更が行われる可能性があるため、注意してください。
#!/bin/bash
# run "chmod +x typescript-search-and-compile.sh" in the directory of this file to ENABLE execution of this script
# then in terminal run "path/to/this/file/typescript-search-and-compile.sh" to execute this script
# (or "./typescript-search-and-compile.sh" if your terminal is in the folder the script is in)
# !!! CHANGE ME !!!
# location of your scripts root folder
# make sure that you do not add a trailing "/" at the end!!
# also, no spaces! If you have a space in the filepath, then
# you have to follow this link: https://stackoverflow.com/a/16703720/9800782
sr=~/path/to/scripts/root/folder
# !!! CHANGE ME !!!
# find all typescript config files
scripts=$(find $sr -name "tsconfig.json")
for s in $scripts
do
# strip off the word "tsconfig.json"
cd ${s%/*} # */ # this function gets incorrectly parsed by style linters on web
# run the typescript watch in the background
tsc -w &
# get the pid of the last executed background function
pids+=$!
# save it to an array
pids+=" "
done
# end all processes we spawned when you close this process
wait $pids
役立つリソース:
- bash:文字列変数をファイル名/パスとして解釈します
- whileループ内で変更された変数は記憶されません
- https://www.cyberciti.biz/faq/search-for-files-in-bash/
- https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays
- https://linuxize.com/post/bash-concatenate-strings/
- https://www.cyberciti.biz/faq/bash-for-loop/
- https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
- https://unix.stackexchange.com/questions/144298/delete-the-last-character-of-a-string-using-string-manipulation-in-shell-script
- 特別なドル記号シェル変数とは何ですか?
Linuxでは以下を使用します:
tsc -w $(find。| grep .ts)
これにより、現在のディレクトリの下にあるすべてのtypescriptファイルが監視されます。