我正在尝试将宠物项目转换为TypeScript,但似乎无法使用该tsc
实用程序来监视和编译我的文件。帮助说我应该使用该-w
开关,但是看起来它无法*.ts
递归监视和编译某个目录中的所有文件。这似乎tsc
应该可以处理。我有什么选择?
Answers:
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
目录中。
compilerOptions.rootDir
您可以使用tsconfig的include
属性指定多个源目录,而不必使用设置单个源目录:{ "compilerOptions": { ...myOptions }, "include": [ "src", "otherSrc" ] }
TypeScript 1.5 beta引入了对名为tsconfig.json的配置文件的支持。在该文件中,您可以配置编译器,定义代码格式化规则,更重要的是,为您提供有关项目中TS文件的信息。
正确配置后,您只需运行tsc命令并使其编译项目中的所有TypeScript代码。
如果要让它监视文件的更改,则只需在--tsc命令中添加--watch即可。
这是一个示例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
从技术上讲,您可以在此处选择以下几种方式:
如果您使用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 Build System。
您甚至可以定义.js
在文件保存时将源代码编译为目标文件。github上托管了一个sublime软件包:https : //github.com/alexnj/SublimeOnSaveBuild,可以做到这一点,只需要ts
在SublimeOnSaveBuild.sublime-settings
文件中包含扩展名即可。
另一种可能性是在命令行中编译每个文件。您可以使用空格将它们分开,甚至可以一次编译多个文件tsc foo.ts bar.ts
。检查此线程:如何将多个源文件传递给TypeScript编译器?,但我认为第一种选择更方便。
考虑使用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
您可以通过以下示例文件夹轻松观看和使用打字稿:
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"
}
}
和一个咕gr的文件:
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']);
}
tsc 0.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 >
参考: 自动监视和编译TypeScript文件。
今天,我针对与您相同的问题设计了此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中使用。
编辑:注意,这是如果您的打字稿源中有多个tsconfig.json文件。对于我的项目,我们将每个tsconfig.json文件编译为一个不同名称的.js文件。这使得观看每个打字稿文件确实非常容易。
我编写了一个不错的bash脚本,该脚本查找所有tsconfig.json文件并在后台运行它们,然后,如果您在终端上按CTRL + C,它将关闭所有正在运行的打字稿监视命令。
这已经在MacOS上进行了测试,但是应该可以在支持BASH 3.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
有用的资源:
tsc
给出了一个错误,error TS6050: Unable to open file 'tsconfig.json'.
直到我删除了注释