Program Tip

모든 TypeScript 소스를보고 컴파일하는 방법은 무엇입니까?

programtip 2020. 11. 10. 22:07
반응형

모든 TypeScript 소스를보고 컴파일하는 방법은 무엇입니까?


애완 동물 프로젝트를 TypeScript로 변환하려고하는데 tsc유틸리티를 사용하여 파일을보고 컴파일 할 수없는 것 같습니다 . 도움말에는 -w스위치를 사용해야한다고 나와 있지만 *.ts일부 디렉터리의 모든 파일을 재귀 적으로 보고 컴파일 할 수없는 것 같습니다 . 이것은 무언가 tsc를 처리 할 수있을 것 같습니다 . 내 옵션은 무엇입니까?


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 코드를 컴파일하도록 할 수 있습니다.

파일의 변경 사항을 확인하려면 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 설명서를 참조하십시오 .


이 같은 모든 파일을 볼 수 있습니다

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 컴파일러에 어떻게 전달할 수 있습니까? ,하지만 첫 번째 옵션이 더 편리하다고 생각합니다.


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

그리고 grunt 파일 :

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

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

참고URL : https://stackoverflow.com/questions/12799237/how-to-watch-and-compile-all-typescript-sources

반응형