Javascript 如何查看和编译所有 TypeScript 源代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12799237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:19:01  来源:igfitidea点击:

How to watch and compile all TypeScript sources?

javascriptcompilationtypescript

提问by VoY

I'm trying to convert a pet project to TypeScript and don't seem to be able to use the tscutility to watch and compile my files. The help says I should use the -wswitch, but it looks like it can't watch and compile all *.tsfiles in the some directory recursively. This seems like something tscshould be able to handle. What are my options?

我正在尝试将一个宠物项目转换为 TypeScript,但似乎无法使用该tsc实用程序来查看和编译我的文件。帮助说我应该使用-w开关,但它似乎无法*.ts递归地监视和编译某个目录中的所有文件。这似乎tsc应该能够处理。我有哪些选择?

回答by budhajeewa

Create a file named tsconfig.jsonin your project root and include following lines in it:

创建一个tsconfig.json在项目根目录中命名的文件,并在其中包含以下几行:

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "module": "commonjs",
        "target": "ES5",
        "outDir": "ts-built",
        "rootDir": "src"
    }
}

Please notethat outDirshould be the path of the directory to receive compiled JS files, and rootDirshould be the path of the directory containing your source (.ts) files.

请注意outDir应该是接收编译后的 JS 文件rootDir的目录路径,并且应该是包含您的源 (.ts) 文件的目录的路径。

Open a terminal and run tsc -w, it'll compile any .tsfile in srcdirectory into .jsand store them in ts-builtdirectory.

打开终端并运行tsc -w,它会将目录中的任何.ts文件编译src.js并存储在ts-built目录中。

回答by dSebastien

TypeScript 1.5 beta has introduced support for a configuration file called tsconfig.json. In that file you can configure the compiler, define code formatting rules and more importantly for you, provide it with information about the TS files in your project.

TypeScript 1.5 beta 引入了对名为 tsconfig.json 的配置文件的支持。在该文件中,您可以配置编译器、定义代码格式规则,更重要的是,为您提供有关项目中 TS 文件的信息。

Once correctly configured, you can simply run the tsc command and have it compile all the TypeScript code in your project.

正确配置后,您可以简单地运行 tsc 命令并让它编译项目中的所有 TypeScript 代码。

If you want to have it watch the files for changes then you can simply add --watch to the tsc command.

如果你想让它监视文件的变化,那么你可以简单地将 --watch 添加到 tsc 命令。

Here's an example tsconfig.json file

这是一个示例 tsconfig.json 文件

{
"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false
},
"include": [
    "**/*"
],
"exclude": [
    "node_modules",
    "**/*.spec.ts"
]}

In the example above, I include all .ts files in my project (recursively). Note that you can also exclude files using an "exclude" property with an array.

在上面的示例中,我将所有 .ts 文件包含在我的项目中(递归)。请注意,您还可以使用带有数组的“排除”属性来排除文件。

For more information, refer to the documentation: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

有关更多信息,请参阅文档:http: //www.typescriptlang.org/docs/handbook/tsconfig-json.html

回答by Wambua Makenzi

you can watch all files like this

你可以像这样观看所有文件

tsc *.ts --watch

回答by Endre Simo

Technically speaking you have a few options here:

从技术上讲,您在这里有几个选择:

If you are using an IDE like Sublime Text and integrated MSN plugin for Typescript: http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspxyou can create a build system which compile the .tssource to .jsautomatically. Here is the explanation how you can do it: How to configure a Sublime Build System for TypeScript.

如果您使用的是像 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 构建系统

You can define even to compile the source code to destination .jsfile on file save. There is a sublime package hosted on github: https://github.com/alexnj/SublimeOnSaveBuildwhich make this happen, only you need to include the tsextension in the SublimeOnSaveBuild.sublime-settingsfile.

您甚至可以定义.js在文件保存时将源代码编译为目标文件。github 上托管了一个 sublime 包:https: //github.com/alexnj/SublimeOnSaveBuild可以实现这一点,只需要tsSublimeOnSaveBuild.sublime-settings文件中包含扩展名。

Another possibility would be to compile each file in the command line. You can compile even multiple files at once by separating them with spaces like so: tsc foo.ts bar.ts. Check this thread: How can I pass multiple source files to the TypeScript compiler?, but i think the first option is more handy.

另一种可能性是在命令行中编译每个文件。您甚至可以一次编译多个文件,方法是用空格分隔它们,如下所示:tsc foo.ts bar.ts. 检查此线程:如何将多个源文件传递给 TypeScript 编译器?,但我认为第一个选项更方便。

回答by Valentin

The tsc compiler will only watch those files that you pass on the command line. It will notwatch files that are included using a /// <sourcefile>reference. If your working with the bash, you could use find to recursively find all *.tsfiles and compile them:

tsc 编译器只会监视您在命令行上传递的那些文件。它不会监视使用/// <sourcefile>引用包含的文件。如果您使用 bash,您可以使用 find 递归查找所有*.ts文件并编译它们:

find . -name "*.ts" | xargs tsc -w

回答by Doug

Look into using grunt to automate this, there are numerous tutorials around, but here's a quick start.

考虑使用 grunt 来自动执行此操作,周围有很多教程,但这里有一个快速入门。

For a folder structure like:

对于文件夹结构,如:

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

You can watch and work with typescript easily from the example folder with:

您可以使用以下示例文件夹轻松查看和使用打字稿:

npm install
grunt

With package.json:

使用 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"
  }
}

And a grunt file:

还有一个咕噜文件:

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']);
}

回答by Sean

tsc 0.9.1.1 does not seem to have a watchfeature.

tsc 0.9.1.1 似乎没有手表功能。

You could use a PowerShell script like the one:

您可以使用像这样的 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 >  

Ref: Automatically watch and compile TypeScript files.

Ref: Automatically watch and compile TypeScript files

回答by Tekool

Today I designed this Ant MacroDef for the same problem as yours :

今天我为和你一样的问题设计了这个 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='""' />
            <!--regexpmapper from="^(.*)$" to='""' /-->

        </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>

Use it in your build file with :

在您的构建文件中使用它:

    <!-- Compile a single JavaScript file in the bin dir for release -->
    <TypeScriptCompileDir
        src="${src-js.dir}"
        out="${release-file-path}"
        module="amd"
    />

It is used in the project PureMVC for TypeScriptI'm working on at the time using Webstorm.

它在我当时正在使用 Webstorm 的TypeScript项目PureMVC 中使用。