Jak oglądać i kompilować wszystkie źródła maszynopisu?

Próbuję przekonwertować projekt pet do maszynopisu i wydaje się, że nie jestem w stanie użyć narzędzia tsc do oglądania i kompilowania moich plików. Pomoc mówi, że powinienem użyć przełącznika -w, ale wygląda na to, że nie może on oglądać i kompilować rekurencyjnie wszystkich plików *.ts w jakimś katalogu. Wygląda na to, że coś tsc powinno sobie z tym poradzić. Jakie mam opcje?

Author: VoY, 2012-10-09

10 answers

Utwórz plik o nazwie tsconfig.json w głównym projekcie i dołącz do niego następujące wiersze:

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

Zauważ, że outDir powinna być ścieżką katalogu do otrzymywania skompilowanych plików JS, a {[3] } powinna być ścieżką katalogu zawierającego twoje źródło (.ts) pliki.

Otwórz terminal i uruchom tsc -w, skompiluje dowolny plik .ts w katalogu src do .js i zapisze je w katalogu ts-built.

 126
Author: budhajeewa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-07 00:58:11

TypeScript 1.5 beta wprowadził obsługę pliku konfiguracyjnego o nazwie tsconfig.json. W tym pliku możesz skonfigurować kompilator, zdefiniować reguły formatowania kodu i, co ważniejsze, dostarczyć mu informacje o plikach TS w Twoim projekcie.

Po poprawnym skonfigurowaniu, możesz po prostu uruchomić polecenie tsc i zlecić kompilację całego kodu maszynopisu w Twoim projekcie.

Jeśli chcesz, aby oglądał pliki pod kątem zmian, możesz po prostu dodać --watch do dowództwo tsc.

Oto przykład tsconfig.plik json

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

W powyższym przykładzie uwzględniam wszystkie .pliki ts w moim projekcie (rekurencyjnie). Zauważ, że możesz również wykluczyć pliki za pomocą właściwości "exclude" z tablicą.

Aby uzyskać więcej informacji, zapoznaj się z dokumentacją: http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

 27
Author: dSebastien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-08 03:11:57

Możesz oglądać wszystkie takie pliki

tsc *.ts --watch
 18
Author: Wambua Makenzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-23 12:32:25

Technicznie rzecz biorąc masz kilka opcji tutaj:

Jeśli używasz IDE jak Sublime Text i zintegrowanej wtyczki MSN dla maszynopisu: http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspx możesz utworzyć system kompilacji, który automatycznie kompiluje źródło .ts do .js. Oto wyjaśnienie, jak to zrobić: Jak skonfigurować Sublime Build System Dla maszynopisu .

Możesz zdefiniować nawet aby skompilować kod źródłowy do docelowego pliku .js w pliku zapisz. Istnieje sublime pakiet hostowany na GitHubie: https://github.com/alexnj/SublimeOnSaveBuild które sprawiają, że tak się dzieje, tylko musisz dołączyć rozszerzenie ts w pliku SublimeOnSaveBuild.sublime-settings.

Inną możliwością byłoby skompilowanie KAŻDEGO pliku w wierszu poleceń. Możesz skompilować nawet wiele plików naraz, rozdzielając je spacjami w ten sposób: tsc foo.ts bar.ts. Sprawdź ten wątek: Jak mogę przekazać wiele plików źródłowych do Kompilator maszynopisu?, ale myślę, że pierwsza opcja jest bardziej przydatna.

 8
Author: Endre Simo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 11:47:13

Kompilator tsc będzie obserwował tylko te pliki, które przekazujesz w wierszu poleceń. Będzie to, a nie oglądać pliki, które są dołączane za pomocą referencji /// <sourcefile>. Jeśli pracujesz z bash, możesz użyć find, aby rekurencyjnie znaleźć wszystkie pliki *.ts i skompilować je:

find . -name "*.ts" | xargs tsc -w
 6
Author: Valentin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-09 12:30:43

Przyjrzyj się użyciu grunt do zautomatyzowania tego, istnieje wiele samouczków wokół, ale tutaj jest szybki start.

Dla struktury folderów typu:

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

Możesz łatwo oglądać i pracować z maszynopisem z przykładowego folderu z:

npm install
grunt

Z pakietem.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"
  }
}

I plik gruntowy:

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']);
}
 6
Author: Doug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-29 08:36:45

Tsc 0.9.1.1 nie wydaje się mieć funkcji watch .

Możesz użyć skryptu PowerShell, takiego jak ten:

#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: automatycznie ogląda i kompiluje pliki maszynopisu .

 3
Author: Sean,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-05 02:23:32

Dzisiaj zaprojektowałem ten mrówkowy MacroDef dla tego samego problemu co Twój:

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

Użyj go w pliku kompilacji z :

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

Jest on używany w projekcie PureMVC dla maszynopisu pracuję w tym czasie przy użyciu Webstorm.

 1
Author: Tekool,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-24 22:46:35

EDIT: uwaga, jest to jeśli masz wiele tsconfig.pliki json w źródle maszynopisu. Dla mojego projektu mamy każdy tsconfig.plik json kompiluje się do innej nazwy .plik js. Dzięki temu oglądanie KAŻDEGO pliku maszynopisu jest naprawdę łatwe.

Napisałem skrypt sweet bash, który znajduje wszystkie Twoje tsconfig.pliki json i uruchamia je w tle, a następnie jeśli CTRL + C terminal zamknie wszystkie uruchomione polecenia TypeScript watch.

To jest testowane na MacOS, ale powinno działać wszędzie tam, gdzie BASH 3.2.57 jest obsługiwany. Przyszłe wersje mogą zmienić pewne rzeczy, więc bądźcie ostrożni!

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

Pomocne zasoby:

 0
Author: Matt Wyndham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-30 18:16:24

Inne odpowiedzi mogły być przydatne lata temu, ale teraz są nieaktualne.

Biorąc pod uwagę, że projekt posiada plik tsconfig , Uruchom to polecenie...

tsc --watch

... aby obserwować zmienione pliki i kompilować w razie potrzeby. dokumentacja wyjaśnia :

Uruchom kompilator w trybie czuwania. Obserwuj pliki wejściowe i uruchom rekompilację zmian. Implementację obserwujących plików i katalogów można skonfigurować przy użyciu zmiennej środowiskowej. Zobacz też konfiguracja zegarka aby uzyskać więcej szczegółów.

Aby odpowiedzieć na pierwotne pytanie, rekurencyjne oglądanie katalogów jest możliwe nawet na platformach, które nie mają natywnej obsługi, jak wyjaśniono w Konfigurowanie watch docs:

Obserwowanie katalogów na platformach, które nie obsługują rekurencyjnego obserwowania katalogów natywnie w węźle, jest obsługiwane przez rekurencyjnie tworzoną kontrolę katalogów dla katalogów podrzędnych przy użyciu różnych opcji wybranych przez TSC_WATCHDIRECTORY

 0
Author: David J.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-02-08 15:37:52