start werk
This commit is contained in:
+509
@@ -0,0 +1,509 @@
|
||||
# Changelog
|
||||
|
||||
## v5.4.5
|
||||
|
||||
* [use @types/webpack for loader typings](https://github.com/TypeStrong/ts-loader/pull/927) - thanks @LukeSheard!
|
||||
|
||||
## v5.4.4
|
||||
|
||||
* [refactor: add common appendTsTsxSuffixesIfRequired function to instance](https://github.com/TypeStrong/ts-loader/pull/924) - thanks @johnnyreilly!
|
||||
|
||||
## v5.4.3
|
||||
|
||||
* [feat: resolveTypeReferenceDirective support for yarn PnP](https://github.com/TypeStrong/ts-loader/pull/921) - thanks @johnnyreilly!
|
||||
* [fix: don't include anything apart from ts-loader in publish](https://github.com/TypeStrong/ts-loader/pull/923) - thanks @johnnyreilly!
|
||||
|
||||
## v5.3.3
|
||||
|
||||
* [fix: Pass ts.Program to getCustomTransformers](https://github.com/TypeStrong/ts-loader/pull/889) (#860) - thanks @andersekdahl!
|
||||
|
||||
## v5.3.2
|
||||
|
||||
* [feat: enable experimentalFileCaching by default](https://github.com/TypeStrong/ts-loader/pull/885) (#868) - thanks @timocov!
|
||||
|
||||
## v5.3.1
|
||||
|
||||
* [fix: projectReferences with rootDir](https://github.com/TypeStrong/ts-loader/pull/871) (#868) - thanks @andrewbranch!
|
||||
|
||||
## v5.3.0
|
||||
|
||||
* [feat: Exposes a `resolveNodeModule` option](https://github.com/TypeStrong/ts-loader/pull/862) - thanks @arcanis!
|
||||
|
||||
## v5.2.2
|
||||
|
||||
* [feat: Micro-optimizations](https://github.com/TypeStrong/ts-loader/pull/855) - thanks @johnnyreilly
|
||||
|
||||
## v5.2.1
|
||||
|
||||
* [feat: Lists typescript as a peer dependency](https://github.com/TypeStrong/ts-loader/pull/841) - thanks @arcanis!
|
||||
|
||||
## v5.2.0
|
||||
|
||||
* [feat: Initial support for project references - `projectReferences`](https://github.com/TypeStrong/ts-loader/pull/817) - thanks @andrewbranch!
|
||||
|
||||
## v5.1.1
|
||||
|
||||
* [fix(getTranspilationEmit): pass the raw path to transpileModule](https://github.com/TypeStrong/ts-loader/pull/835) - thanks @Brooooooklyn
|
||||
|
||||
## v5.1.0
|
||||
|
||||
* [feat: Added cache for some FS operations while compiling - `experimentalFileCaching`](https://github.com/TypeStrong/ts-loader/pull/829) - thanks @timocov!
|
||||
|
||||
## v5.0.0
|
||||
|
||||
* [feat: Fixed issue with incorrect output path for declaration files](https://github.com/TypeStrong/ts-loader/pull/822) - thanks @JonWallsten! **BREAKING CHANGE**
|
||||
|
||||
## v4.5.0
|
||||
|
||||
* [feat: Added support for TypeScript declaration map](https://github.com/TypeStrong/ts-loader/pull/821) - thanks @JonWallsten!
|
||||
|
||||
## v4.4.2
|
||||
|
||||
* [fix(loader): new Error to webpack when errors occured in the loader function](https://github.com/TypeStrong/ts-loader/pull/792) - thanks @linxiaowu66 and @systemmetaphor!
|
||||
|
||||
## v4.4.1
|
||||
|
||||
* [fix(types): expose public interfaces from root index.d.ts](https://github.com/TypeStrong/ts-loader/pull/790) - thanks @Hotell!
|
||||
|
||||
## v4.4.0
|
||||
|
||||
* [feat: generate ambient types from implementation](https://github.com/TypeStrong/ts-loader/pull/788) - thanks @Hotell!
|
||||
* [error when not using webpack 4](https://github.com/TypeStrong/ts-loader/pull/786) - thanks @johnnyreilly
|
||||
|
||||
## v4.3.1
|
||||
|
||||
* [Fix options caching when ts-loader is used in multiple rules](https://github.com/TypeStrong/ts-loader/pull/782) - thanks @yyx990803!
|
||||
|
||||
Please note, this bug fix requires that vue-loader users still using v14 should either upgrade to v15 or explicitly pass the same ts-loader options via v14's loaders option. [See more details here](https://github.com/TypeStrong/ts-loader/pull/782#issuecomment-394406093)
|
||||
|
||||
## v4.3.0
|
||||
|
||||
* [Fix dependency resolution when using pnpm](https://github.com/TypeStrong/ts-loader/pull/774) - thanks @xbtsw and @zkochan!
|
||||
* [Add `allowTsInNodeModules` option for importing .ts files from node_modules](https://github.com/TypeStrong/ts-loader/pull/773) - thanks @aelawson!
|
||||
|
||||
## v4.2.0
|
||||
|
||||
* [Pass `context' to error formatters](https://github.com/TypeStrong/ts-loader/pull/756) - thanks @gustavderdrache!
|
||||
|
||||
## v4.1.0
|
||||
|
||||
* [Fix slow `experimentalWatchApi`](https://github.com/TypeStrong/ts-loader/pull/747) (#746) - thanks @sheetalkamat and @MLoughry!
|
||||
* [feat: `getCustomTransformers` support path string for a module](https://github.com/TypeStrong/ts-loader/pull/745) - thanks @vagusX and @s-panferov (upon whose work this is based I believe)
|
||||
|
||||
## v4.0.1
|
||||
|
||||
* [Fix name collision in experimentalWatchApi code](https://github.com/TypeStrong/ts-loader/pull/737) - thanks @MLoughry!
|
||||
|
||||
## v4.0.0
|
||||
|
||||
* Support webpack 4
|
||||
* Drop support for webpack 2/3 **BREAKING CHANGE** - use ts-loader 3.x if you need webpack 2/3 support
|
||||
* Minimum TypeScript version is now 2.4.1 **BREAKING CHANGE**
|
||||
* Deprecated option `entryFileCannotBeJs` removed' **BREAKING CHANGE**
|
||||
* Start using [prettier](https://prettier.io/) for the codebase
|
||||
|
||||
## v3.5.0
|
||||
|
||||
* [Add trace for traceResolution](https://github.com/TypeStrong/ts-loader/pull/721) - thanks @onigoetz!
|
||||
|
||||
## v3.4.0
|
||||
|
||||
* [local .d.ts files now marked as changed when watch is triggered](https://github.com/TypeStrong/ts-loader/pull/698) - thanks @KnisterPeter!
|
||||
|
||||
## v3.3.1
|
||||
|
||||
* [Fixes to support watch api for compiling - lib support etc](https://github.com/TypeStrong/ts-loader/pull/715) - thanks @sheetalkamat!
|
||||
|
||||
## v3.3.0
|
||||
|
||||
* [Report diagnostics only on certain files with `reportFiles` option](https://github.com/TypeStrong/ts-loader/pull/701) - thanks @freeman!
|
||||
* [Replaced option `contextAsConfigBasePath` with `context` option.](https://github.com/TypeStrong/ts-loader/pull/688/) Strictly speaking a breaking change. However, given the original option was never able to fulfil its intended purpose I've decided to treat this as just a new feature; there seems no possibility that anyone can be using `contextAsConfigBasePath` - thanks @christiantinauer!
|
||||
* [Added support for the new watch api of TypeScript compiler.](https://github.com/TypeStrong/ts-loader/pull/685) nb This feature has been placed behind a new `experimentalWatchApi` option until it has been thoroughly tested. All being well it is likely to become the default behaviour for ts-loader in future - thanks @sheetalkamat!
|
||||
|
||||
## v3.2.0
|
||||
|
||||
* [Add new loader option `contextAsConfigBasePath`](https://github.com/TypeStrong/ts-loader/pull/681) - thanks @christiantinauer
|
||||
|
||||
## v3.1.1
|
||||
|
||||
* [Fix error importing buildt ts files with allowJs](https://github.com/TypeStrong/ts-loader/pull/674) (#667) - thanks @Pajn!
|
||||
|
||||
## v3.1.0
|
||||
|
||||
* [Add `onlyCompileBundledFiles` option which modifies behaviour to load only those files that are actually bundled by webpack](https://github.com/TypeStrong/ts-loader/pull/671) #267 - thanks @maier49!
|
||||
* [Chore release; upgraded chalk dependency in `package.json` to 2.3, as 2.3 is another breaking changes release (from a TypeScript perspective).](https://github.com/TypeStrong/ts-loader/issues/664), see [here](https://github.com/chalk/chalk/issues/215) for context - thanks @johnnyreilly
|
||||
|
||||
## v3.0.5
|
||||
|
||||
* [Chore release; upgraded chalk dependency in `package.json` to 2.2, as 2.2 appears to be a breaking changes release.](https://github.com/TypeStrong/ts-loader/issues/664) - thanks @lmk123 for reporting
|
||||
|
||||
## v3.0.4
|
||||
|
||||
* [Chore release; upgraded chalk dependency.](https://github.com/TypeStrong/ts-loader/pull/662) - thanks @johnnyreilly
|
||||
|
||||
## v3.0.3
|
||||
|
||||
* [Fix allowJs @types resolution error](https://github.com/TypeStrong/ts-loader/pull/658) (#657, #655) - thanks @johnnyreilly and @roddypratt + @ldrick for providing minimal repro repos which allowed me to fix this long standing bug!
|
||||
|
||||
This fix resolves the issue for TypeScript 2.4+ (which is likely 95% of users). For those people stuck on 2.3 or below and impacted by this issue, you should be able to workaround this by setting `entryFileCannotBeJs: true` in your ts-loader options. This option should be considered deprecated as of this release. The option will likely disappear with the next major version of ts-loader which will drop support for TypeScript 2.3 and below, thus removing the need for this option.
|
||||
|
||||
## v3.0.0
|
||||
|
||||
All changes were made with this [PR](https://github.com/TypeStrong/ts-loader/pull/643) - thanks @johnnyreilly
|
||||
|
||||
([Published to npm as v3.0.2 due to npm publishing issues](https://github.com/TypeStrong/ts-loader/issues/654)) thanks @mattlewis92 for noticing!
|
||||
|
||||
* drop support for typescript < 2.0 (no-one seems to be using it and we can simplify the code) **BREAKING CHANGE**
|
||||
* remove `entryFileIsJs` option; it can be inferred from whether the `allowJs` TypeScript compiler option has been set.
|
||||
* move to webpack 3.0 for test harness
|
||||
* drop `configFileName` support [(replaced by `configFile`)](https://github.com/TypeStrong/ts-loader/pull/607) **BREAKING CHANGE**
|
||||
* add support for a custom formatter for output - drop visual studio format (this can be added back if there's clamour for it and people can supply their own formatters in the interim) **BREAKING CHANGE**
|
||||
* make loglevel warn by default (stop outputting typescript version number by default). Fixes [#488](https://github.com/TypeStrong/ts-loader/issues/488)
|
||||
* fix [tsc has "module" default to "es2015"when targetting es2015+, but ts-loader does not](https://github.com/TypeStrong/ts-loader/issues/570) - thanks [@Venryx](https://github.com/Venryx) for the suggestion!
|
||||
* [switch to build ts-loader / run tests with yarn](https://github.com/TypeStrong/ts-loader/issues/369) because of [this](https://stackoverflow.com/questions/45022048/why-does-npm-install-rewrite-package-lock-json/45566871#45566871)
|
||||
* allow controlling whether the output can contain colours
|
||||
|
||||
## v2.3.7
|
||||
|
||||
* [Start validating the options supplied to the loader](https://github.com/TypeStrong/ts-loader/pull/630) (#629) - thanks @johnnyreilly!
|
||||
|
||||
## v2.3.6
|
||||
|
||||
* [Fix kills ts-loader dependant builds issue](https://github.com/TypeStrong/ts-loader/pull/627) (#626) - thanks @Loilo!
|
||||
|
||||
## v2.3.5
|
||||
|
||||
* [Add an additional check for js files before reusing isExternalLibaryImport](https://github.com/TypeStrong/ts-loader/pull/622) (#620) - thanks @WillMartin!
|
||||
* [Make TypeScript `basePath` configurable](https://github.com/TypeStrong/ts-loader/pull/621) (#618) - thanks @Loilo!
|
||||
* [Fix relative configFile path](https://github.com/TypeStrong/ts-loader/pull/618) (#617) - thanks @Loilo!
|
||||
|
||||
## v2.3.4
|
||||
|
||||
* [Add `configFile` option](https://github.com/TypeStrong/ts-loader/pull/607) - thanks @Loilo!
|
||||
|
||||
## v2.3.3
|
||||
|
||||
* [fix(tsconfig): stop passing rootDir option to TypeScript compiler](https://github.com/TypeStrong/ts-loader/pull/598) (#597) - thanks @Brooooooklyn
|
||||
* [Fix findConfigFile in Windows](https://github.com/TypeStrong/ts-loader/pull/605) (#604) - thanks @mengxy
|
||||
|
||||
## v2.3.2
|
||||
|
||||
* [Move to use strictNullChecks](https://github.com/TypeStrong/ts-loader/pull/589) - thanks @johnnyreilly
|
||||
* [`allowJs` supports importing types from external libraries](https://github.com/TypeStrong/ts-loader/pull/590) (#586, #577) - thanks @bsouthga!
|
||||
|
||||
## v2.3.1
|
||||
|
||||
* [Fix undefined watcher in watch-run causes error](https://github.com/TypeStrong/ts-loader/pull/587) (#585) - thanks @zinserjan and @sokra!
|
||||
|
||||
## v2.3.0
|
||||
|
||||
* [add appendTsxSuffixTo option to support using tsx with Vue](https://github.com/TypeStrong/ts-loader/pull/581) - lots of discussion went into this PR. Thanks to @vhqtvn (author) and @HerringtonDarkholme, @johnnyreilly, @jbrantly, @octref, @rhyek and others for helping us land on our final implementation.
|
||||
* [refactor: Use chalk instead of colors](https://github.com/TypeStrong/ts-loader/pull/579) - thanks @develar!
|
||||
|
||||
## v2.2.2
|
||||
|
||||
* [Remove default of setting isolatedModules to true when in transpileOnly mode](https://github.com/TypeStrong/ts-loader/pull/569) - thanks @johnnyreilly and @donaldpipowitch
|
||||
|
||||
## v2.2.1
|
||||
|
||||
* [Report errors in JS(X) files when CheckJS is enabled](https://github.com/TypeStrong/ts-loader/pull/564) - thanks @schmuli!
|
||||
* [Cater for change to @types acquisition strategy in TypeScript 2.4.1](https://github.com/TypeStrong/ts-loader/pull/566) - thanks @johnnyreilly
|
||||
|
||||
## v2.2.0
|
||||
|
||||
* [Support custom transformers for ts](https://github.com/TypeStrong/ts-loader/pull/535) - thanks @longlho and @Igorbek!
|
||||
|
||||
## v2.1.0
|
||||
|
||||
* [Add happypack compatibility mode](https://github.com/TypeStrong/ts-loader/pull/547) - thanks @aindlq!
|
||||
|
||||
## v2.0.3
|
||||
|
||||
* [Don't include appended TS extension in webpack dependencies](https://github.com/TypeStrong/ts-loader/pull/497) - thanks again @wearymonkey!
|
||||
|
||||
## v2.0.2
|
||||
|
||||
* [Fix performance regression related to using getTimes() by tracking timestamps](https://github.com/TypeStrong/ts-loader/pull/500) - thanks @wearymonkey
|
||||
|
||||
## v2.0.1
|
||||
|
||||
* [make watch resilient to no watcher / watcher.mtimes](https://github.com/TypeStrong/ts-loader/pull/482) - thanks @bancek and @mredbishop
|
||||
* [move to using loader-utils 1.0](https://github.com/TypeStrong/ts-loader/pull/475)
|
||||
|
||||
## v2.0.0
|
||||
|
||||
* [Add support for IgnoringWatchFileSystem](https://github.com/TypeStrong/ts-loader/pull/444) - thanks @herschel666
|
||||
* [Use native Object.assign()](https://github.com/TypeStrong/ts-loader/pull/418) - thanks @arusakov
|
||||
|
||||
Breaking changes:
|
||||
|
||||
* ts-loader now officially only supports webpack 2. ts-loader 2.x may work with webpack 1 but it is not supported. Related to that, all continuous integration tests now run against webpack 2.
|
||||
* as webpack 2 does not support node 0.12 neither does ts-loader from now. node 4 at least is required.
|
||||
|
||||
## v1.3.3
|
||||
|
||||
* [Fix bug when "extend"ing a tsconfig that specifies "allowJs"](https://github.com/TypeStrong/ts-loader/pull/415) Thanks @cspotcode
|
||||
* [Minor perf optimisations](https://github.com/TypeStrong/ts-loader/pull/412)
|
||||
|
||||
## v1.3.2
|
||||
|
||||
* [Upgrade enhanced-resolve to v3](https://github.com/TypeStrong/ts-loader/pull/411)
|
||||
* [Remove arrify dependency](https://github.com/TypeStrong/ts-loader/pull/410)
|
||||
|
||||
## v1.3.1
|
||||
|
||||
* [Rolled back re-exported const enums no longer break emit in watch mode as performance cost was too high](https://github.com/TypeStrong/ts-loader/pull/406) resolves #393
|
||||
|
||||
## v1.3.0
|
||||
|
||||
* [Introduce meaningful error when importing TypeScript from `node_modules`](https://github.com/TypeStrong/ts-loader/pull/399)
|
||||
* [Introduce `entryFileIsJs` loader option which allows having an entry file which is js.](https://github.com/TypeStrong/ts-loader/pull/399) resolves #388 and #401 - thanks @Wykks and @pqr.
|
||||
|
||||
NB Previously the `entryFileIsJs` option was on by default when `allowJs` was true. Now it has to be specified directly. Strictly speaking this is a breaking change; however given this is a rarely used option which exists for what is arguably an edge case this is being added without moving to 2.0. If this breaks people then we'll never do this again; I'd be surprised if anyone is relying on this though so we're taking a chance. Related tests have been suffixed "-entryFileIsJs" in the test name.
|
||||
|
||||
## v1.2.2
|
||||
|
||||
* [Re-exported const enums no longer break emit in watch mode](https://github.com/TypeStrong/ts-loader/pull/377) [#376] - thanks @smphhh
|
||||
* [typescript.sys should be compiler.sys](https://github.com/TypeStrong/ts-loader/pull/380) [#379] - thanks @johnnyreilly and @jbrantly
|
||||
|
||||
## v1.2.1
|
||||
|
||||
* [Fix TS module resolution paths on Windows - watch mode becomes faster](https://github.com/TypeStrong/ts-loader/pull/373) [#372] - thanks @smphhh
|
||||
|
||||
## v1.2.0
|
||||
|
||||
* [Crash when adding/removing files in watch-mode](https://github.com/TypeStrong/ts-loader/pull/364) [#358] - thanks @jbbr for the suggested fix
|
||||
* [Provided an option to produce Visual Studio compatible error output](https://github.com/TypeStrong/ts-loader/pull/356) [#355] - thanks @gamli
|
||||
|
||||
## v1.1.0
|
||||
|
||||
* [Added support for vuejs via `appendTsSuffixTo` option](https://github.com/TypeStrong/ts-loader/pull/354) [#270] - thanks @HerringtonDarkholme
|
||||
|
||||
## v1.0.0
|
||||
|
||||
* [General refactor of ts-loader; some performance improvements](https://github.com/TypeStrong/ts-loader/pull/343) [#335] - thanks @johnnyreilly
|
||||
* [Make the loader resilient to watched declaration files being removed.](https://github.com/TypeStrong/ts-loader/pull/281) - thanks @opichals
|
||||
|
||||
## v0.9.5
|
||||
|
||||
* [Improve performance for watch mode / `after-compile` plugin](https://github.com/TypeStrong/ts-loader/pull/187) - thanks @Strate
|
||||
|
||||
## v0.9.4
|
||||
|
||||
* [Make logging to stderr or stdout configurable; introduce logging levels](https://github.com/TypeStrong/ts-loader/pull/313) [#214] - thanks @ThYpHo0n
|
||||
* [Fix regression that broke hot module replacement](https://github.com/TypeStrong/ts-loader/pull/322) [#321] - thanks @dopare
|
||||
|
||||
## v0.9.3
|
||||
|
||||
* [Added support for allowJs](https://github.com/TypeStrong/ts-loader/pull/320) (#316) - thanks @dschnare
|
||||
|
||||
## v0.9.2
|
||||
|
||||
* [Added support for @types](https://github.com/TypeStrong/ts-loader/pull/318) (#247) -thanks @basarat for the ideas
|
||||
|
||||
## v0.9.1
|
||||
|
||||
* [Normalize dependency graph paths - Fix broken dependencies on Windows ](https://github.com/TypeStrong/ts-loader/pull/286) - thanks @pzavolinsky
|
||||
* [Fixed the declaration issue](https://github.com/TypeStrong/ts-loader/pull/307) (#214 part deux) - thanks @dizel3d
|
||||
|
||||
## v0.9.0
|
||||
|
||||
* [Made ts-loader compatible with node v6](https://github.com/TypeStrong/ts-loader/commit/a4f835345e495f45b40365f025afce72d1817996) - thanks @Blechhirn
|
||||
* [Fixed the declaration issue](https://github.com/TypeStrong/ts-loader/commit/3bb0fec73a2fab47953b51d256f0f5378f236ad1) (#214) - thanks @17cupsofcoffee
|
||||
* [Declarations update independent of compiler.watchFileSystem](https://github.com/TypeStrong/ts-loader/pull/167/commits/ae824b2676b226bdd0c860a787754a4ae28e339c) (#155) - thanks @opichals
|
||||
|
||||
Now built using TypeScript v2.0
|
||||
|
||||
## v0.8.2
|
||||
|
||||
* Elided imports are now watched (#156, #169)
|
||||
* Declaration files for `.d.ts` files are now emitted (thanks @rob-bateman) (#174, #175)
|
||||
|
||||
## v0.8.1
|
||||
|
||||
* Add better error messaging when a file in tsconfig.json can not be loaded (#117, #145)
|
||||
* Fix incompatibility with html-webpack-plugin (#152, #154)
|
||||
|
||||
## v0.8.0
|
||||
|
||||
* Add support for emitting declaration files when `declaration: true` is set (#48, #128)
|
||||
* Fix bug with specifying `target: es6` and `module: commonjs` at the same time when using
|
||||
TS 1.7+ (#111, #132, #140).
|
||||
* Fix bug with resolving dependencies which are linked using `npm link` (#134, #141)
|
||||
|
||||
## v0.7.2
|
||||
|
||||
* Fix regression with watching definition files (#109, #110)
|
||||
|
||||
## v0.7.1
|
||||
|
||||
* Fix regression with Windows that was introduced in v0.7.0 (#92)
|
||||
|
||||
## v0.7.0
|
||||
|
||||
* Fix bug with webpack resolution that could sometimes cause TypeScript to not find modules (#92, #102)
|
||||
* Loader output is now written to stderr instead of stdout. (#95, #103)
|
||||
|
||||
## v0.6.1
|
||||
|
||||
* Improve initial build performance significantly for larger projects (#100)
|
||||
* Fix issue with nightly (#96)
|
||||
|
||||
## v0.6.0
|
||||
|
||||
* Remove support for 1.5 and 1.6-beta. TypeScript 1.6 (stable) is the now the lowest version
|
||||
supported.
|
||||
* Fix issue when using source maps and Babel in certain situations (#81)
|
||||
* Fix issue with nightly (#83)
|
||||
|
||||
## v0.5.6
|
||||
|
||||
* Add ignoreDiagnostics feature
|
||||
* Fix issue with node resolution and `noEmitOnError` (#71)
|
||||
|
||||
## v0.5.5
|
||||
|
||||
* Fix issue with nightly (Microsoft/TypeScript#4738)
|
||||
* Add support for the NoErrorsPlugin
|
||||
|
||||
## v0.5.4
|
||||
|
||||
* Fix issue with nightly (Microsoft/TypeScript#4497)
|
||||
|
||||
## v0.5.3
|
||||
|
||||
* Utilize TypeScript's new custom module resolution logic to integrate with webpack. This essentially
|
||||
means that TypeScript will resolve files exactly the same as webpack does (supporting aliases, etc).
|
||||
See the [aliasResolution test](test/aliasResolution) for an example. Only supported in TS 1.6 and
|
||||
above.
|
||||
* Rework error reporting to resolve certain edge cases with dependencies. In general errors should
|
||||
be much more consistent now in watch mode.
|
||||
* Fix issue with targeting ES6 and transpile mode (#36)
|
||||
|
||||
## v0.5.2
|
||||
|
||||
* Fix issue with TypeScript nightly and new node module resolution strategy (#34)
|
||||
|
||||
## v0.5.1
|
||||
|
||||
* Tweaked error message output to include error code (#32)
|
||||
* Add helpful messages around the TypeScript dependency
|
||||
* Suggest how to install TypeScript if it hasn't been installed
|
||||
* Show TypeScript version when compiling
|
||||
* Warn if TypeScript version is incompatible
|
||||
|
||||
## v0.5.0
|
||||
|
||||
* Add support for `transpileOnly` loader option. See README for more information.
|
||||
* TypeScript is no longer a dependency of the loader and must be installed separately
|
||||
* Loader options can now be set as a property in `webpack.config.js`
|
||||
* TypeScript options can be set through the loader option `compilerOptions`
|
||||
* Improved error reporting
|
||||
* Errors from all files in the TypeScript application are now reported in watch mode instead of
|
||||
from just those files that changed. This means that making a breaking change in a dependency
|
||||
will now be correctly reported as an error in the dependent file.
|
||||
* Errors with TypeScript options are now reported as webpack errors instead of logged to console
|
||||
* Error output no longer contains the filename once from webpack and again in the error message.
|
||||
Instead, the filename is only reported by webpack
|
||||
* Fixed issue with latest version of webpack where filenames could be reported twice for the same
|
||||
error in certain situations
|
||||
* Using the `declaration` TypeScript option no longer results in errors
|
||||
* Add support for the `newLine` TypeScript option
|
||||
* Tests have been revamped to be full integration tests with nightly builds against the current stable
|
||||
and nightly TypeScript. Many new tests have been added.
|
||||
|
||||
## v0.4.7
|
||||
|
||||
* Update TypeScript dependency to 1.5 release (1.5.3)
|
||||
|
||||
## v0.4.6
|
||||
|
||||
* Improve error reporting related to tsconfig.json
|
||||
* Fix bug that reported the wrong errors
|
||||
* Errors are now reported as webpack errors instead of logged to console
|
||||
* Add support for latest TypeScript nightly (#24)
|
||||
|
||||
## v0.4.5
|
||||
|
||||
* Add `silent` flag (#22)
|
||||
|
||||
## v0.4.4
|
||||
|
||||
* Add support for "noLib" compiler option (#19)
|
||||
* Make errors easier to parse programmatically (#20)
|
||||
* Errors in declaration files are now added to the stats object instead of written to console
|
||||
* Errors now include `file`, `rawMessage`, and `location` properties
|
||||
* Make --watch option more robust
|
||||
* Fix issue where changes to entry file were not detected
|
||||
* Fix issue where changes to typing information only did not result in a rebuild (#21)
|
||||
|
||||
## v0.4.3
|
||||
|
||||
* Fix error locations to be 1-based instead of 0-based (#18)
|
||||
|
||||
## v0.4.2
|
||||
|
||||
* Rework the way dependencies are loaded (#14)
|
||||
* Fix NPM dependency on TypeScript (#15, #16)
|
||||
|
||||
## v0.4.1
|
||||
|
||||
* Fix Windows issue with paths (#14)
|
||||
|
||||
## v0.4.0
|
||||
|
||||
* TypeScript 1.5 support! (#14)
|
||||
* tsconfig.json support (#2, #9)
|
||||
* ES6 target support
|
||||
* Remove TS-related options in favor of specifying them in tsconfig.json
|
||||
* Add `configFileName` option for custom tsconfig files
|
||||
|
||||
## v0.3.4
|
||||
|
||||
* Exclude TS 1.5 as a dependency since there are breaking changes
|
||||
|
||||
## v0.3.3
|
||||
|
||||
* Add support for reporting errors in declaration files (#10)
|
||||
* Add support for watch mode for declaration files (#11)
|
||||
* Fix issue with extra `sourceMappingURL` in output files (#12)
|
||||
|
||||
## v0.3.2
|
||||
|
||||
* Add support for manually adding files (#6)
|
||||
* Add paths to source maps (#8)
|
||||
|
||||
## v0.3.1
|
||||
|
||||
* Add support for specifying a custom TypeScript compiler
|
||||
|
||||
## v0.3.0
|
||||
|
||||
* Change how modules are resolved. Imports and declaration file references are
|
||||
now resolved through TypeScript instead of being resolved through webpack's
|
||||
`resolve` API. This fixes a number of issues and better aligns the loader to
|
||||
work as a replacement for the `tsc` command. (#3, #4, #5)
|
||||
|
||||
## v0.2.3
|
||||
|
||||
* Add noImplicitAny option (#2)
|
||||
|
||||
## v0.2.2
|
||||
|
||||
* Fix issue with source maps
|
||||
|
||||
## v0.2.1
|
||||
|
||||
* Add colors to error output
|
||||
|
||||
## v0.2.0
|
||||
|
||||
* Add new configuration options (#1)
|
||||
* target, module, sourceMap, instance
|
||||
* sourceMap default changed from `true` to `false`
|
||||
* Workaround issue with TypeScript always emitting Windows-style new lines
|
||||
* Add tests
|
||||
|
||||
## v0.1.0
|
||||
|
||||
* Initial version
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# History
|
||||
|
||||
`ts-loader` was started by [James Brantly](http://www.jbrantly.com/) back in January 2015. He created the initial codebase, wrote the comparison testpack and merrily maintained it until it reached v0.8.2.
|
||||
|
||||
At that point [John Reilly](https://blog.johnnyreilly.com/) started maintaining ts-loader. [On October 16th 2016 to be exact](https://twitter.com/jbrantly/status/785931975064444928). The full story of how that came to be can be read here: https://blog.johnnyreilly.com/2016/11/but-you-cant-die-i-love-you-ts-loader.html
|
||||
|
||||
Since that time, John (who wrote this and finds it peculiar to refer to himself in the third person) has continued maintaining ts-loader. He appreciates any and all people that contribute. Who knows, maybe one day the mantle will be passed on again and someone else will step up and take ts-loader forwards. Who knows? It could be you ;-)
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 TypeStrong
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
+632
@@ -0,0 +1,632 @@
|
||||
# TypeScript loader for webpack
|
||||
|
||||
[](https://www.npmjs.com/package/ts-loader)
|
||||
[](https://travis-ci.org/TypeStrong/ts-loader)
|
||||
[](https://ci.appveyor.com/project/JohnReilly/ts-loader/branch/master)
|
||||
[](https://npmjs.org/package/ts-loader)
|
||||
[](https://www.npmjs.com/package/ts-loader)
|
||||
[](https://github.com/prettier/prettier)
|
||||
[](https://gitter.im/TypeStrong/ts-loader)
|
||||
|
||||
This is the typescript loader for webpack.
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Examples
|
||||
|
||||
We have a number of example setups to accomodate different workflows. Our examples can be found [here](examples/).
|
||||
|
||||
We probably have more examples than we need. That said, here's a good way to get started:
|
||||
|
||||
- I want the simplest setup going. Use "[vanilla](examples/vanilla)" ts-loader
|
||||
- I want the fastest compilation that's available. Use [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin). It performs type checking in a separate process with `ts-loader` just handling transpilation.
|
||||
|
||||
### Faster Builds
|
||||
|
||||
As your project becomes bigger, compilation time increases linearly. It's because typescript's semantic checker has to inspect all files on every rebuild. The simple solution is to disable it by using the `transpileOnly: true` option, but doing so leaves you without type checking and *will not output declaration files*.
|
||||
|
||||
You probably don't want to give up type checking; that's rather the point of TypeScript. So what you can do is use the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin). It runs the type checker on a separate process, so your build remains fast thanks to `transpileOnly: true` but you still have the type checking. Also, the plugin has several optimizations to make incremental type checking faster (AST cache, multiple workers).
|
||||
|
||||
If you'd like to see a simple setup take a look at [our simple example](examples/fork-ts-checker-webpack-plugin/). For a more complex setup take a look at our [more involved example](examples/react-babel-karma-gulp).
|
||||
|
||||
### Yarn Plug’n’Play
|
||||
|
||||
`ts-loader` supports [Yarn Plug’n’Play](https://yarnpkg.com/en/docs/pnp). The recommended way to integrate is using the [pnp-webpack-plugin](https://github.com/arcanis/pnp-webpack-plugin#ts-loader-integration).
|
||||
|
||||
### Babel
|
||||
|
||||
ts-loader works very well in combination with [babel](https://babeljs.io/) and [babel-loader](https://github.com/babel/babel-loader). There is an [example](https://github.com/Microsoft/TypeScriptSamples/tree/master/react-flux-babel-karma) of this in the official [TypeScript Samples](https://github.com/Microsoft/TypeScriptSamples). Alternatively take a look at our own [example](examples/react-babel-karma-gulp).
|
||||
|
||||
### Parallelising Builds
|
||||
|
||||
It's possible to parallelise your builds. Historically this was useful from a performance perspective with webpack 2 / 3. [With webpack 4+ there appears to be significantly less benefit and perhaps even cost.](https://blog.johnnyreilly.com/2018/12/you-might-not-need-thread-loader.html)
|
||||
|
||||
But if that's what you want to do, there's two ways to achieve this: [happypack](https://github.com/amireh/happypack) and [thread-loader](https://github.com/webpack-contrib/thread-loader). Both should be used in combination with [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) for typechecking.)
|
||||
|
||||
To read more, look at [this post](https://medium.com/webpack/typescript-webpack-super-pursuit-mode-83cc568dea79) by [@johnny_reilly](https://twitter.com/johnny_reilly) on the webpack publication channel.
|
||||
|
||||
If you'd like find out further ways to improve your build using the watch API then take a look at [this post](https://medium.com/@kenneth_chau/speeding-up-webpack-typescript-incremental-builds-by-7x-3912ba4c1d15) by [@kenneth_chau](https://twitter.com/kenneth_chau).
|
||||
|
||||
### Installation
|
||||
|
||||
```
|
||||
yarn add ts-loader --dev
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
npm install ts-loader --save-dev
|
||||
```
|
||||
|
||||
You will also need to install TypeScript if you have not already.
|
||||
|
||||
```
|
||||
yarn add typescript --dev
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```
|
||||
npm install typescript --save-dev
|
||||
```
|
||||
|
||||
### Running
|
||||
|
||||
Use webpack like normal, including `webpack --watch` and `webpack-dev-server`, or through another
|
||||
build system using the [Node.js API](http://webpack.github.io/docs/node.js-api.html).
|
||||
|
||||
### Compatibility
|
||||
|
||||
* TypeScript: 2.4.1+
|
||||
* webpack: 4.x+ (please use ts-loader 3.x if you need webpack 2 or 3 support)
|
||||
* node: 6.11.5 minimum (aligned with webpack 4)
|
||||
|
||||
A full test suite runs each night (and on each pull request). It runs both on [Linux](https://travis-ci.org/TypeStrong/ts-loader) and [Windows](https://ci.appveyor.com/project/JohnReilly/ts-loader), testing ts-loader against major releases of TypeScript. The test suite also runs against TypeScript@next (because we want to use it as much as you do).
|
||||
|
||||
If you become aware of issues not caught by the test suite then please let us know. Better yet, write a test and submit it in a PR!
|
||||
|
||||
### Configuration
|
||||
|
||||
1. Create or update `webpack.config.js` like so:
|
||||
|
||||
```javascript
|
||||
module.exports = {
|
||||
mode: "development",
|
||||
devtool: "inline-source-map",
|
||||
entry: "./app.ts",
|
||||
output: {
|
||||
filename: "bundle.js"
|
||||
},
|
||||
resolve: {
|
||||
// Add `.ts` and `.tsx` as a resolvable extension.
|
||||
extensions: [".ts", ".tsx", ".js"]
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
// all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
|
||||
{ test: /\.tsx?$/, loader: "ts-loader" }
|
||||
]
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
2. Add a [`tsconfig.json`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file. (The one below is super simple; but you can tweak this to your hearts desire)
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The [tsconfig.json](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) file controls
|
||||
TypeScript-related options so that your IDE, the `tsc` command, and this loader all share the
|
||||
same options.
|
||||
|
||||
#### `devtool` / sourcemaps
|
||||
|
||||
If you want to be able to debug your original source then you can thanks to the magic of sourcemaps. There are 2 steps to getting this set up with ts-loader and webpack.
|
||||
|
||||
First, for ts-loader to produce **sourcemaps**, you will need to set the [tsconfig.json](http://www.typescriptlang.org/docs/handbook/tsconfig-json.html) option as `"sourceMap": true`.
|
||||
|
||||
Second, you need to set the `devtool` option in your `webpack.config.js` to support the type of sourcemaps you want. To make your choice have a read of the [`devtool` webpack docs](https://webpack.js.org/configuration/devtool/). You may be somewhat daunted by the choice available. You may also want to vary the sourcemap strategy depending on your build environment. Here are some example strategies for different environments:
|
||||
|
||||
* `devtool: 'inline-source-map'` - Solid sourcemap support; the best "all-rounder". Works well with karma-webpack (not all strategies do)
|
||||
* `devtool: 'cheap-module-eval-source-map'` - Best support for sourcemaps whilst debugging.
|
||||
* `devtool: 'source-map'` - Approach that plays well with UglifyJsPlugin; typically you might use this in Production
|
||||
|
||||
### Code Splitting and Loading Other Resources
|
||||
|
||||
Loading css and other resources is possible but you will need to make sure that
|
||||
you have defined the `require` function in a [declaration file](https://www.typescriptlang.org/docs/handbook/writing-declaration-files.html).
|
||||
|
||||
```typescript
|
||||
declare var require: {
|
||||
<T>(path: string): T;
|
||||
(paths: string[], callback: (...modules: any[]) => void): void;
|
||||
ensure: (
|
||||
paths: string[],
|
||||
callback: (require: <T>(path: string) => T) => void
|
||||
) => void;
|
||||
};
|
||||
```
|
||||
|
||||
Then you can simply require assets or chunks per the [webpack documentation](https://webpack.js.org/guides/code-splitting/).
|
||||
|
||||
```javascript
|
||||
require("!style!css!./style.css");
|
||||
```
|
||||
|
||||
The same basic process is required for code splitting. In this case, you `import` modules you need but you
|
||||
don't directly use them. Instead you require them at [split points](http://webpack.github.io/docs/code-splitting.html#defining-a-split-point). See [this example](test/comparison-tests/codeSplitting) and [this example](test/comparison-tests/es6codeSplitting) for more details.
|
||||
|
||||
[TypeScript 2.4 provides support for ECMAScript's new `import()` calls. These calls import a module and return a promise to that module.](https://blogs.msdn.microsoft.com/typescript/2017/06/12/announcing-typescript-2-4-rc/) This is also supported in webpack - details on usage can be found [here](https://webpack.js.org/guides/code-splitting-async/#dynamic-import-import-). Happy code splitting!
|
||||
|
||||
### Declarations (.d.ts)
|
||||
|
||||
To output a built .d.ts file, you can set `"declaration": true` in your tsconfig, and use the [DeclarationBundlerPlugin](https://www.npmjs.com/package/declaration-bundler-webpack-plugin) in your webpack config.
|
||||
|
||||
### Failing the build on TypeScript compilation error
|
||||
|
||||
The build **should** fail on TypeScript compilation errors as of webpack 2. If for some reason it does not, you can use the [webpack-fail-plugin](https://www.npmjs.com/package/webpack-fail-plugin).
|
||||
|
||||
For more background have a read of [this issue](https://github.com/TypeStrong/ts-loader/issues/108).
|
||||
|
||||
### `baseUrl` / `paths` module resolution
|
||||
|
||||
If you want to resolve modules according to `baseUrl` and `paths` in your `tsconfig.json` then you can use the [tsconfig-paths-webpack-plugin](https://www.npmjs.com/package/tsconfig-paths-webpack-plugin) package. For details about this functionality, see the [module resolution documentation](https://www.typescriptlang.org/docs/handbook/module-resolution.html#base-url).
|
||||
|
||||
This feature requires webpack 2.1+ and TypeScript 2.0+. Use the config below or check the [package](https://github.com/dividab/tsconfig-paths-webpack-plugin/blob/master/README.md) for more information on usage.
|
||||
|
||||
```javascript
|
||||
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
|
||||
|
||||
module.exports = {
|
||||
...
|
||||
resolve: {
|
||||
plugins: [new TsconfigPathsPlugin({ /*configFile: "./path/to/tsconfig.json" */ })]
|
||||
}
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
There are two types of options: TypeScript options (aka "compiler options") and loader options. TypeScript options should be set using a tsconfig.json file. Loader options can be specified through the `options` property in the webpack configuration:
|
||||
|
||||
```javascript
|
||||
module.exports = {
|
||||
...
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: [
|
||||
{
|
||||
loader: 'ts-loader',
|
||||
options: {
|
||||
transpileOnly: true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Loader Options
|
||||
|
||||
#### transpileOnly _(boolean) (default=false)_
|
||||
|
||||
If you want to speed up compilation significantly you can set this flag.
|
||||
However, many of the benefits you get from static type checking between
|
||||
different dependencies in your application will be lost.
|
||||
|
||||
It's advisable to use `transpileOnly` alongside the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) to get full type checking again. To see what this looks like in practice then either take a look at [our simple example](examples/fork-ts-checker-webpack-plugin). For a more complex setup take a look at our [more involved example](examples/react-babel-karma-gulp).
|
||||
|
||||
If you enable this option, webpack 4 will give you "export not found" warnings any time you re-export a type:
|
||||
|
||||
```
|
||||
WARNING in ./src/bar.ts
|
||||
1:0-34 "export 'IFoo' was not found in './foo'
|
||||
@ ./src/bar.ts
|
||||
@ ./src/index.ts
|
||||
```
|
||||
|
||||
The reason this happens is that when typescript doesn't do a full type check, it does not have enough information to determine whether an imported name is a type or not, so when the name is then exported, typescript has no choice but to emit the export. Fortunately, the extraneous export should not be harmful, so you can just suppress these warnings:
|
||||
|
||||
```javascript
|
||||
module.exports = {
|
||||
...
|
||||
stats: {
|
||||
warningsFilter: /export .* was not found in/
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### happyPackMode _(boolean) (default=false)_
|
||||
|
||||
If you're using [HappyPack](https://github.com/amireh/happypack) or [thread-loader](https://github.com/webpack-contrib/thread-loader) to parallise your builds then you'll need to set this to `true`. This implicitly sets `*transpileOnly*` to `true` and **WARNING!** stops registering **_all_** errors to webpack.
|
||||
|
||||
It's advisable to use this with the [fork-ts-checker-webpack-plugin](https://github.com/Realytics/fork-ts-checker-webpack-plugin) to get full type checking again. To see what this looks like in practice then either take a look at [our simple HappyPack example](examples/happypack) / [our simple thread-loader example](examples/thread-loader). For a more complex setup take a look at our [more involved HappyPack example](examples/react-babel-karma-gulp-happypack) / [more involved thread-loader example](examples/react-babel-karma-gulp-thread-loader). **_IMPORTANT_**: If you are using fork-ts-checker-webpack-plugin alongside HappyPack or thread-loader then ensure you set the `checkSyntacticErrors` option like so:
|
||||
|
||||
```javascript
|
||||
new ForkTsCheckerWebpackPlugin({ checkSyntacticErrors: true })
|
||||
```
|
||||
|
||||
This will ensure that the plugin checks for both syntactic errors (eg `const array = [{} {}];`) and semantic errors (eg `const x: number = '1';`). By default the plugin only checks for semantic errors (as when used with ts-loader in `transpileOnly` mode, ts-loader will still report syntactic errors).
|
||||
|
||||
Also, if you are using `thread-loader` in watch mode, remember to set `poolTimeout: Infinity` so workers don't die.
|
||||
|
||||
#### resolveModuleName and resolveTypeReferenceDirective:
|
||||
|
||||
These options should be functions which will be used to resolve the import statements and the `<reference types="...">` directives instead of the default TypeScript implementation. It's not intended that these will typically be used by a user of `ts-loader` - they exist to facilitate functionality such as [Yarn Plug’n’Play](https://yarnpkg.com/en/docs/pnp).
|
||||
|
||||
#### getCustomTransformers _( (program: Program) => { before?: TransformerFactory<SourceFile>[]; after?: TransformerFactory<SourceFile>[]; } )_
|
||||
|
||||
Provide custom transformers - only compatible with TypeScript 2.3+ (and 2.4 if using `transpileOnly` mode). For example usage take a look at [typescript-plugin-styled-components](https://github.com/Igorbek/typescript-plugin-styled-components) or our [test](test/comparison-tests/customTransformer).
|
||||
|
||||
You can also pass a path string to locate a js module file which exports the function described above, this useful especially in `happyPackMode`. (Because forked processes cannot serialize functions see more at [related issue](https://github.com/Igorbek/typescript-plugin-styled-components/issues/6#issue-303387183))
|
||||
|
||||
#### logInfoToStdOut _(boolean) (default=false)_
|
||||
|
||||
This is important if you read from stdout or stderr and for proper error handling.
|
||||
The default value ensures that you can read from stdout e.g. via pipes or you use webpack -j to generate json output.
|
||||
|
||||
#### logLevel _(string) (default=warn)_
|
||||
|
||||
Can be `info`, `warn` or `error` which limits the log output to the specified log level.
|
||||
Beware of the fact that errors are written to stderr and everything else is written to stderr (or stdout if logInfoToStdOut is true).
|
||||
|
||||
#### silent _(boolean) (default=false)_
|
||||
|
||||
If `true`, no console.log messages will be emitted. Note that most error
|
||||
messages are emitted via webpack which is not affected by this flag.
|
||||
|
||||
#### ignoreDiagnostics _(number[]) (default=[])_
|
||||
|
||||
You can squelch certain TypeScript errors by specifying an array of diagnostic
|
||||
codes to ignore.
|
||||
|
||||
#### reportFiles _(string[]) (default=[])_
|
||||
|
||||
Only report errors on files matching these glob patterns.
|
||||
|
||||
```javascript
|
||||
// in webpack.config.js
|
||||
{
|
||||
test: /\.ts$/,
|
||||
loader: 'ts-loader',
|
||||
options: { reportFiles: ['src/**/*.{ts,tsx}', '!src/skip.ts'] }
|
||||
}
|
||||
```
|
||||
|
||||
This can be useful when certain types definitions have errors that are not fatal to your application.
|
||||
|
||||
#### compiler _(string) (default='typescript')_
|
||||
|
||||
Allows use of TypeScript compilers other than the official one. Should be
|
||||
set to the NPM name of the compiler, eg [`ntypescript`](https://github.com/basarat/ntypescript).
|
||||
|
||||
#### configFile _(string) (default='tsconfig.json')_
|
||||
|
||||
Allows you to specify where to find the TypeScript configuration file.
|
||||
|
||||
You may provide
|
||||
|
||||
* just a file name. The loader then will search for the config file of each entry point in the respective entry point's containing folder. If a config file cannot be found there, it will travel up the parent directory chain and look for the config file in those folders.
|
||||
* a relative path to the configuration file. It will be resolved relative to the respective `.ts` entry file.
|
||||
* an absolute path to the configuration file.
|
||||
|
||||
Please note, that if the configuration file is outside of your project directory, you might need to set the `context` option to avoid TypeScript issues (like TS18003).
|
||||
In this case the `configFile` should point to the `tsconfig.json` and `context` to the project root.
|
||||
|
||||
#### colors _(boolean) (default=true)_
|
||||
|
||||
If `false`, disables built-in colors in logger messages.
|
||||
|
||||
#### errorFormatter _((message: ErrorInfo, colors: boolean) => string) (default=undefined)_
|
||||
|
||||
By default ts-loader formats TypeScript compiler output for an error or a warning in the style:
|
||||
|
||||
```
|
||||
[tsl] ERROR in myFile.ts(3,14)
|
||||
TS4711: you did something very wrong
|
||||
```
|
||||
|
||||
If that format is not to your taste you can supply your own formatter using the `errorFormatter` option. Below is a template for a custom error formatter. Please note that the `colors` parameter is an instance of [`chalk`](https://github.com/chalk/chalk) which you can use to color your output. (This instance will respect the `colors` option.)
|
||||
|
||||
```javascript
|
||||
function customErrorFormatter(error, colors) {
|
||||
const messageColor =
|
||||
error.severity === "warning" ? colors.bold.yellow : colors.bold.red;
|
||||
return (
|
||||
"Does not compute.... " +
|
||||
messageColor(Object.keys(error).map(key => `${key}: ${error[key]}`))
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
If the above formatter received an error like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"code":2307,
|
||||
"severity": "error",
|
||||
"content": "Cannot find module 'components/myComponent2'.",
|
||||
"file":"/.test/errorFormatter/app.ts",
|
||||
"line":2,
|
||||
"character":31
|
||||
}
|
||||
```
|
||||
|
||||
It would produce an error message that said:
|
||||
|
||||
```
|
||||
Does not compute.... code: 2307,severity: error,content: Cannot find module 'components/myComponent2'.,file: /.test/errorFormatter/app.ts,line: 2,character: 31
|
||||
```
|
||||
|
||||
And the bit after "Does not compute.... " would be red.
|
||||
|
||||
#### compilerOptions _(object) (default={})_
|
||||
|
||||
Allows overriding TypeScript options. Should be specified in the same format
|
||||
as you would do for the `compilerOptions` property in tsconfig.json.
|
||||
|
||||
#### instance _(string)_
|
||||
|
||||
Advanced option to force files to go through different instances of the
|
||||
TypeScript compiler. Can be used to force segregation between different parts
|
||||
of your code.
|
||||
|
||||
#### appendTsSuffixTo _(RegExp[]) (default=[])_
|
||||
|
||||
#### appendTsxSuffixTo _(RegExp[]) (default=[])_
|
||||
|
||||
A list of regular expressions to be matched against filename. If filename matches one of the regular expressions, a `.ts` or `.tsx` suffix will be appended to that filename.
|
||||
|
||||
This is useful for `*.vue` [file format](https://vuejs.org/v2/guide/single-file-components.html) for now. (Probably will benefit from the new single file format in the future.)
|
||||
|
||||
Example:
|
||||
|
||||
webpack.config.js:
|
||||
|
||||
```javascript
|
||||
module.exports = {
|
||||
entry: "./index.vue",
|
||||
output: { filename: "bundle.js" },
|
||||
resolve: {
|
||||
extensions: [".ts", ".vue"]
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.vue$/, loader: "vue-loader" },
|
||||
{
|
||||
test: /\.ts$/,
|
||||
loader: "ts-loader",
|
||||
options: { appendTsSuffixTo: [/\.vue$/] }
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
index.vue
|
||||
|
||||
```vue
|
||||
<template><p>hello {{msg}}</p></template>
|
||||
<script lang="ts">
|
||||
export default {
|
||||
data(): Object {
|
||||
return {
|
||||
msg: "world"
|
||||
};
|
||||
}
|
||||
};
|
||||
</script>
|
||||
```
|
||||
|
||||
We can handle `.tsx` by quite similar way:
|
||||
|
||||
webpack.config.js:
|
||||
|
||||
```javascript
|
||||
module.exports = {
|
||||
entry: './index.vue',
|
||||
output: { filename: 'bundle.js' },
|
||||
resolve: {
|
||||
extensions: ['.ts', '.tsx', '.vue', '.vuex']
|
||||
},
|
||||
module: {
|
||||
rules: [
|
||||
{ test: /\.vue$/, loader: 'vue-loader',
|
||||
options: {
|
||||
loaders: {
|
||||
ts: 'ts-loader',
|
||||
tsx: 'babel-loader!ts-loader',
|
||||
}
|
||||
}
|
||||
},
|
||||
{ test: /\.ts$/, loader: 'ts-loader', options: { appendTsSuffixTo: [/TS\.vue$/] } }
|
||||
{ test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/TSX\.vue$/] } }
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
tsconfig.json (set `jsx` option to `preserve` to let babel handle jsx)
|
||||
|
||||
```json
|
||||
{
|
||||
"compilerOptions": {
|
||||
"jsx": "preserve"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
index.vue
|
||||
|
||||
```vue
|
||||
<script lang="tsx">
|
||||
export default {
|
||||
functional: true,
|
||||
render(h, c) {
|
||||
return (<div>Content</div>);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
Or if you want to use only tsx, just use the `appendTsxSuffixTo` option only:
|
||||
|
||||
```javascript
|
||||
{ test: /\.ts$/, loader: 'ts-loader' }
|
||||
{ test: /\.tsx$/, loader: 'babel-loader!ts-loader', options: { appendTsxSuffixTo: [/\.vue$/] } }
|
||||
```
|
||||
|
||||
#### onlyCompileBundledFiles _(boolean) (default=false)_
|
||||
|
||||
The default behavior of ts-loader is to act as a drop-in replacement for the `tsc` command,
|
||||
so it respects the `include`, `files`, and `exclude` options in your `tsconfig.json`, loading
|
||||
any files specified by those options. The `onlyCompileBundledFiles` option modifies this behavior,
|
||||
loading only those files that are actually bundled by webpack, as well as any `.d.ts` files included
|
||||
by the `tsconfig.json` settings. `.d.ts` files are still included because they may be needed for
|
||||
compilation without being explicitly imported, and therefore not picked up by webpack.
|
||||
|
||||
#### allowTsInNodeModules _(boolean) (default=false)_
|
||||
|
||||
By default, ts-loader will not compile `.ts` files in `node_modules`.
|
||||
You should not need to recompile `.ts` files there, but if you really want to, use this option.
|
||||
Note that this option acts as a *whitelist* - any modules you desire to import must be included in
|
||||
the `"files"` or `"include"` block of your project's `tsconfig.json`.
|
||||
|
||||
See: [https://github.com/Microsoft/TypeScript/issues/12358](https://github.com/Microsoft/TypeScript/issues/12358)
|
||||
|
||||
```javascript
|
||||
// in webpack.config.js
|
||||
{
|
||||
test: /\.ts$/,
|
||||
loader: 'ts-loader',
|
||||
options: { allowTsInNodeModules: true }
|
||||
}
|
||||
```
|
||||
|
||||
And in your `tsconfig.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"include": [
|
||||
"node_modules/whitelisted_module.ts"
|
||||
],
|
||||
"files": [
|
||||
"node_modules/my_module/whitelisted_file.ts"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### context _(string) (default=undefined)_
|
||||
|
||||
If set, will parse the TypeScript configuration file with given **absolute path** as base path.
|
||||
Per default the directory of the configuration file is used as base path. Relative paths in the configuration
|
||||
file are resolved with respect to the base path when parsed. Option `context` allows to set option
|
||||
`configFile` to a path other than the project root (e.g. a NPM package), while the base path for `ts-loader`
|
||||
can remain the project root.
|
||||
|
||||
Keep in mind that **not** having a `tsconfig.json` in your project root can cause different behaviour between `ts-loader` and `tsc`.
|
||||
When using editors like `VS Code` it is advised to add a `tsconfig.json` file to the root of the project and extend the config file
|
||||
referenced in option `configFile`. For more information please [read the PR](https://github.com/TypeStrong/ts-loader/pull/681) that
|
||||
is the base and [read the PR](https://github.com/TypeStrong/ts-loader/pull/688) that contributed this option.
|
||||
|
||||
webpack:
|
||||
|
||||
```javascript
|
||||
{
|
||||
loader: require.resolve('ts-loader'),
|
||||
options: {
|
||||
context: __dirname,
|
||||
configFile: require.resolve('ts-config-react-app')
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Extending `tsconfig.json`:
|
||||
|
||||
```json
|
||||
{ "extends": "./node_modules/ts-config-react-app/index" }
|
||||
```
|
||||
|
||||
Note that changes in the extending file while not be respected by `ts-loader`. Its purpose is to satisfy the code editor.
|
||||
|
||||
#### experimentalFileCaching _(boolean) (default=true)_
|
||||
|
||||
By default whenever the TypeScript compiler needs to check that a file/directory exists or resolve symlinks it makes syscalls. It does not cache the result of these operations and this may result in many syscalls with the same arguments ([see comment](https://github.com/TypeStrong/ts-loader/issues/825#issue-354725524) with example).
|
||||
In some cases it may produce performance degradation.
|
||||
|
||||
This flag enables caching for some FS-functions like `fileExists`, `realpath` and `directoryExists` for TypeScript compiler. Note that caches are cleared between compilations.
|
||||
|
||||
#### projectReferences _(boolean) (default=false)_
|
||||
|
||||
**TL;DR:** Using project references currently requires building referenced projects outside of ts-loader. We don’t want to keep it that way, but we’re releasing what we’ve got now. To try it out, you’ll need to pass `projectReferences: true` to `loaderOptions`. You’ll also probably need to use TypeScript 3.1.1 or later (which, as of this writing, means `typescript@next`).
|
||||
|
||||
ts-loader has partial support for [project references](https://www.typescriptlang.org/docs/handbook/project-references.html) in that it will _load_ dependent composite projects that are already built, but will not currently _build/rebuild_ those upstream projects. The best way to explain exactly what this means is through an example. Say you have a project with a project reference pointing to the `lib/` directory:
|
||||
|
||||
```
|
||||
tsconfig.json
|
||||
app.ts
|
||||
lib/
|
||||
tsconfig.json
|
||||
niftyUtil.ts
|
||||
```
|
||||
|
||||
And we’ll assume that the root `tsconfig.json` has `{ "references": { "path": "lib" } }`, which means that any import of a file that’s part of the `lib` sub-project is treated as a reference to another project, not just a reference to a TypeScript file. Before discussing how ts-loader handles this, it’s helpful to review at a really basic level what `tsc` itself does here. If you were to run `tsc` on this tiny example project, the build would fail with the error:
|
||||
|
||||
```
|
||||
error TS6305: Output file 'lib/niftyUtil.d.ts' has not been built from source file 'lib/niftyUtil.ts'.
|
||||
```
|
||||
|
||||
Using project references actually instructs `tsc` _not_ to build anything that’s part of another project from source, but rather to look for any `.d.ts` and `.js` files that have already been generated from a previous build. Since we’ve never built the project in `lib` before, those files don’t exist, so building the root project fails. Still just thinking about how `tsc` works, there are two options to make the build succeed: either run `tsc -p lib/tsconfig.json` _first_, or simply run `tsc --build`, which will figure out that `lib` hasn’t been built and build it first for you.
|
||||
|
||||
Ok, so how is that relevant to ts-loader? Because the best way to think about what ts-loader does with project references is that it acts like `tsc`, but _not_ like `tsc --build`. If you run ts-loader on a project that’s using project references, and any upstream project hasn’t been built, you’ll get the exact same `error TS6305` that you would get with `tsc`. If you modify a source file in an upstream project and don’t rebuild that project, `ts-loader` won’t have any idea that you’ve changed anything—it will still be looking at the output from the last time you _built_ that file.
|
||||
|
||||
**“Hey, don’t you think that sounds kind of useless and terrible?”** Well, sort of. You can consider it a work-in-progress. It’s true that on its own, as of today, ts-loader doesn’t have everything you need to take advantage of project references in webpack. In practice, though, _consuming_ upstream projects and _building_ upstream projects are somewhat separate concerns. Building them will likely come in a future release. For background, see the [original issue](https://github.com/TypeStrong/ts-loader/issues/815).
|
||||
|
||||
**`outDir` Windows problemo.** At the moment, composite projects built using the [`outDir` compiler option](https://www.typescriptlang.org/docs/handbook/compiler-options.html) cannot be consumed using ts-loader on Windows. If you try to, ts-loader throws a "has not been built from source file" error. We don't know why yet; it's possible there's a bug in `tsc`. It's more likely there's a bug in `ts-loader`. Hopefully it's going to get solved at some point. (Hey, maybe you're the one to solve it!) Either way, we didn't want to hold back from releasing. So if you're building on Windows then avoid building `composite` projects using `outDir`.
|
||||
|
||||
**TypeScript version compatibility.** As a final caveat, [this commit to TypeScript](https://github.com/Microsoft/TypeScript/commit/d519e3f21ec36274726c44dab25c9eb48e34953f) is necessary for the `include` or `exclude` options of a project-referenced tsconfig file to work. It should be released in TypeScript 3.1.1 according to the tags. To use an earlier version of TypeScript, referenced project configuration files must specify `files`, and not `include`.
|
||||
|
||||
### Usage with webpack watch
|
||||
|
||||
Because TS will generate .js and .d.ts files, you should ignore these files, otherwise watchers may go into an infinite watch loop. For example, when using webpack, you may wish to add this to your webpack.conf.js file:
|
||||
|
||||
```javascript
|
||||
plugins: [
|
||||
new webpack.WatchIgnorePlugin([
|
||||
/\.js$/,
|
||||
/\.d\.ts$/
|
||||
])
|
||||
],
|
||||
```
|
||||
|
||||
It's worth noting that use of the `LoaderOptionsPlugin` is [only supposed to be a stopgap measure](https://webpack.js.org/plugins/loader-options-plugin/). You may want to look at removing it entirely.
|
||||
|
||||
### Hot Module replacement
|
||||
|
||||
To enable `webpack-dev-server` HMR, you need to follow the official [webpack HMR guide](https://webpack.js.org/guides/hot-module-replacement/), then tweak a few config options for `ts-loader`. The required configuration is as follows:
|
||||
|
||||
1. Set `transpileOnly` to `true` (see [transpileOnly](#transpileonly-boolean-defaultfalse) for config details and recommendations above).
|
||||
2. Inside your HMR acceptance callback function, you must re-require the module that was replaced.
|
||||
|
||||
For a boilerplate HMR project using React, check out the [react-hot-boilerplate example](./examples/react-hot-boilerplate/).
|
||||
|
||||
For a minimal HMR TypeScript setup, go to the [hot-module-replacement example](./examples/hot-module-replacement/).
|
||||
|
||||
## Contributing
|
||||
|
||||
This is your TypeScript loader! We want you to help make it even better. Please feel free to contribute; see the [contributor's guide](CONTRIBUTING.md) to get started.
|
||||
|
||||
## License
|
||||
|
||||
MIT License
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const constants = require("./constants");
|
||||
const instances_1 = require("./instances");
|
||||
const utils_1 = require("./utils");
|
||||
function makeAfterCompile(instance, configFilePath) {
|
||||
let getCompilerOptionDiagnostics = true;
|
||||
let checkAllFilesForErrors = true;
|
||||
return (compilation, callback) => {
|
||||
// Don't add errors for child compilations
|
||||
if (compilation.compiler.isChild()) {
|
||||
callback();
|
||||
return;
|
||||
}
|
||||
removeTSLoaderErrors(compilation.errors);
|
||||
provideCompilerOptionDiagnosticErrorsToWebpack(getCompilerOptionDiagnostics, compilation, instance, configFilePath);
|
||||
getCompilerOptionDiagnostics = false;
|
||||
const modules = determineModules(compilation);
|
||||
const filesToCheckForErrors = determineFilesToCheckForErrors(checkAllFilesForErrors, instance);
|
||||
checkAllFilesForErrors = false;
|
||||
const filesWithErrors = new Map();
|
||||
provideErrorsToWebpack(filesToCheckForErrors, filesWithErrors, compilation, modules, instance);
|
||||
provideDeclarationFilesToWebpack(filesToCheckForErrors, instance, compilation);
|
||||
instance.filesWithErrors = filesWithErrors;
|
||||
instance.modifiedFiles = null;
|
||||
instance.projectsMissingSourceMaps = new Set();
|
||||
callback();
|
||||
};
|
||||
}
|
||||
exports.makeAfterCompile = makeAfterCompile;
|
||||
/**
|
||||
* handle compiler option errors after the first compile
|
||||
*/
|
||||
function provideCompilerOptionDiagnosticErrorsToWebpack(getCompilerOptionDiagnostics, compilation, instance, configFilePath) {
|
||||
if (getCompilerOptionDiagnostics) {
|
||||
const { languageService, loaderOptions, compiler, program } = instance;
|
||||
const errorsToAdd = utils_1.formatErrors(program === undefined
|
||||
? languageService.getCompilerOptionsDiagnostics()
|
||||
: program.getOptionsDiagnostics(), loaderOptions, instance.colors, compiler, { file: configFilePath || 'tsconfig.json' }, compilation.compiler.context);
|
||||
compilation.errors.push(...errorsToAdd);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* build map of all modules based on normalized filename
|
||||
* this is used for quick-lookup when trying to find modules
|
||||
* based on filepath
|
||||
*/
|
||||
function determineModules(compilation) {
|
||||
return compilation.modules.reduce((modules, module) => {
|
||||
if (module.resource) {
|
||||
const modulePath = path.normalize(module.resource);
|
||||
const existingModules = modules.get(modulePath);
|
||||
if (existingModules !== undefined) {
|
||||
if (existingModules.indexOf(module) === -1) {
|
||||
existingModules.push(module);
|
||||
}
|
||||
}
|
||||
else {
|
||||
modules.set(modulePath, [module]);
|
||||
}
|
||||
}
|
||||
return modules;
|
||||
}, new Map());
|
||||
}
|
||||
function determineFilesToCheckForErrors(checkAllFilesForErrors, instance) {
|
||||
const { files, modifiedFiles, filesWithErrors, otherFiles } = instance;
|
||||
// calculate array of files to check
|
||||
const filesToCheckForErrors = new Map();
|
||||
if (checkAllFilesForErrors) {
|
||||
// check all files on initial run
|
||||
for (const [filePath, file] of files) {
|
||||
filesToCheckForErrors.set(filePath, file);
|
||||
}
|
||||
for (const [filePath, file] of otherFiles) {
|
||||
filesToCheckForErrors.set(filePath, file);
|
||||
}
|
||||
}
|
||||
else if (modifiedFiles !== null && modifiedFiles !== undefined) {
|
||||
// check all modified files, and all dependants
|
||||
for (const modifiedFileName of modifiedFiles.keys()) {
|
||||
utils_1.collectAllDependants(instance.reverseDependencyGraph, modifiedFileName).forEach(fileName => {
|
||||
const fileToCheckForErrors = files.get(fileName) || otherFiles.get(fileName);
|
||||
filesToCheckForErrors.set(fileName, fileToCheckForErrors);
|
||||
});
|
||||
}
|
||||
}
|
||||
// re-check files with errors from previous build
|
||||
if (filesWithErrors !== undefined) {
|
||||
for (const [fileWithErrorName, fileWithErrors] of filesWithErrors) {
|
||||
filesToCheckForErrors.set(fileWithErrorName, fileWithErrors);
|
||||
}
|
||||
}
|
||||
return filesToCheckForErrors;
|
||||
}
|
||||
function provideErrorsToWebpack(filesToCheckForErrors, filesWithErrors, compilation, modules, instance) {
|
||||
const { compiler, program, languageService, files, loaderOptions, compilerOptions, otherFiles } = instance;
|
||||
const filePathRegex = compilerOptions.checkJs === true
|
||||
? constants.dtsTsTsxJsJsxRegex
|
||||
: constants.dtsTsTsxRegex;
|
||||
for (const filePath of filesToCheckForErrors.keys()) {
|
||||
if (filePath.match(filePathRegex) === null) {
|
||||
continue;
|
||||
}
|
||||
const sourceFile = program === undefined ? undefined : program.getSourceFile(filePath);
|
||||
// If the source file is undefined, that probably means it’s actually part of an unbuilt project reference,
|
||||
// which will have already produced a more useful error than the one we would get by proceeding here.
|
||||
// If it’s undefined and we’re not using project references at all, I guess carry on so the user will
|
||||
// get a useful error about which file was unexpectedly missing.
|
||||
if (utils_1.isUsingProjectReferences(instance) && sourceFile === undefined) {
|
||||
continue;
|
||||
}
|
||||
const errors = program === undefined
|
||||
? [
|
||||
...languageService.getSyntacticDiagnostics(filePath),
|
||||
...languageService.getSemanticDiagnostics(filePath)
|
||||
]
|
||||
: [
|
||||
...program.getSyntacticDiagnostics(sourceFile),
|
||||
...program.getSemanticDiagnostics(sourceFile)
|
||||
];
|
||||
if (errors.length > 0) {
|
||||
const fileWithError = files.get(filePath) || otherFiles.get(filePath);
|
||||
filesWithErrors.set(filePath, fileWithError);
|
||||
}
|
||||
// if we have access to a webpack module, use that
|
||||
const associatedModules = modules.get(filePath);
|
||||
if (associatedModules !== undefined) {
|
||||
associatedModules.forEach(module => {
|
||||
// remove any existing errors
|
||||
removeTSLoaderErrors(module.errors);
|
||||
// append errors
|
||||
const formattedErrors = utils_1.formatErrors(errors, loaderOptions, instance.colors, compiler, { module }, compilation.compiler.context);
|
||||
module.errors.push(...formattedErrors);
|
||||
compilation.errors.push(...formattedErrors);
|
||||
});
|
||||
}
|
||||
else {
|
||||
// otherwise it's a more generic error
|
||||
const formattedErrors = utils_1.formatErrors(errors, loaderOptions, instance.colors, compiler, { file: filePath }, compilation.compiler.context);
|
||||
compilation.errors.push(...formattedErrors);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* gather all declaration files from TypeScript and output them to webpack
|
||||
*/
|
||||
function provideDeclarationFilesToWebpack(filesToCheckForErrors, instance, compilation) {
|
||||
for (const filePath of filesToCheckForErrors.keys()) {
|
||||
if (filePath.match(constants.tsTsxRegex) === null) {
|
||||
continue;
|
||||
}
|
||||
const outputFiles = instances_1.getEmitOutput(instance, filePath);
|
||||
const declarationFiles = outputFiles.filter(outputFile => outputFile.name.match(constants.dtsDtsxOrDtsDtsxMapRegex));
|
||||
declarationFiles.forEach(declarationFile => {
|
||||
const assetPath = path.relative(compilation.compiler.outputPath, declarationFile.name);
|
||||
compilation.assets[assetPath] = {
|
||||
source: () => declarationFile.text,
|
||||
size: () => declarationFile.text.length
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* handle all other errors. The basic approach here to get accurate error
|
||||
* reporting is to start with a "blank slate" each compilation and gather
|
||||
* all errors from all files. Since webpack tracks errors in a module from
|
||||
* compilation-to-compilation, and since not every module always runs through
|
||||
* the loader, we need to detect and remove any pre-existing errors.
|
||||
*/
|
||||
function removeTSLoaderErrors(errors) {
|
||||
let index = -1;
|
||||
let length = errors.length;
|
||||
while (++index < length) {
|
||||
if (errors[index].loaderSource === 'ts-loader') {
|
||||
errors.splice(index--, 1);
|
||||
length--;
|
||||
}
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const semver = require("semver");
|
||||
const typescript = require("typescript");
|
||||
function getCompiler(loaderOptions, log) {
|
||||
let compiler;
|
||||
let errorMessage;
|
||||
let compilerDetailsLogMessage;
|
||||
let compilerCompatible = false;
|
||||
try {
|
||||
compiler = require(loaderOptions.compiler);
|
||||
}
|
||||
catch (e) {
|
||||
errorMessage =
|
||||
loaderOptions.compiler === 'typescript'
|
||||
? 'Could not load TypeScript. Try installing with `yarn add typescript` or `npm install typescript`. If TypeScript is installed globally, try using `yarn link typescript` or `npm link typescript`.'
|
||||
: `Could not load TypeScript compiler with NPM package name \`${loaderOptions.compiler}\`. Are you sure it is correctly installed?`;
|
||||
}
|
||||
if (errorMessage === undefined) {
|
||||
compilerDetailsLogMessage = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`;
|
||||
compilerCompatible = false;
|
||||
if (loaderOptions.compiler === 'typescript') {
|
||||
if (compiler.version !== undefined &&
|
||||
semver.gte(compiler.version, '2.4.1')) {
|
||||
// don't log yet in this case, if a tsconfig.json exists we want to combine the message
|
||||
compilerCompatible = true;
|
||||
}
|
||||
else {
|
||||
log.logError(`${compilerDetailsLogMessage}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
log.logWarning(`${compilerDetailsLogMessage}. This version may or may not be compatible with ts-loader.`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
compiler,
|
||||
compilerCompatible,
|
||||
compilerDetailsLogMessage,
|
||||
errorMessage
|
||||
};
|
||||
}
|
||||
exports.getCompiler = getCompiler;
|
||||
function getCompilerOptions(configParseResult) {
|
||||
const compilerOptions = Object.assign({}, configParseResult.options, {
|
||||
skipLibCheck: true,
|
||||
suppressOutputPathCheck: true // This is why: https://github.com/Microsoft/TypeScript/issues/7363
|
||||
});
|
||||
// if `module` is not specified and not using ES6+ target, default to CJS module output
|
||||
if (compilerOptions.module === undefined &&
|
||||
(compilerOptions.target !== undefined &&
|
||||
compilerOptions.target < typescript.ScriptTarget.ES2015)) {
|
||||
compilerOptions.module = typescript.ModuleKind.CommonJS;
|
||||
}
|
||||
return compilerOptions;
|
||||
}
|
||||
exports.getCompilerOptions = getCompilerOptions;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const utils_1 = require("./utils");
|
||||
function getConfigFile(compiler, colors, loader, loaderOptions, compilerCompatible, log, compilerDetailsLogMessage) {
|
||||
const configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFile);
|
||||
let configFileError;
|
||||
let configFile;
|
||||
if (configFilePath !== undefined) {
|
||||
if (compilerCompatible) {
|
||||
log.logInfo(`${compilerDetailsLogMessage} and ${configFilePath}`);
|
||||
}
|
||||
else {
|
||||
log.logInfo(`ts-loader: Using config file at ${configFilePath}`);
|
||||
}
|
||||
configFile = compiler.readConfigFile(configFilePath, compiler.sys.readFile);
|
||||
if (configFile.error !== undefined) {
|
||||
configFileError = utils_1.formatErrors([configFile.error], loaderOptions, colors, compiler, { file: configFilePath }, loader.context)[0];
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (compilerCompatible) {
|
||||
log.logInfo(compilerDetailsLogMessage);
|
||||
}
|
||||
configFile = {
|
||||
config: {
|
||||
compilerOptions: {},
|
||||
files: []
|
||||
}
|
||||
};
|
||||
}
|
||||
if (configFileError === undefined) {
|
||||
configFile.config.compilerOptions = Object.assign({}, configFile.config.compilerOptions, loaderOptions.compilerOptions);
|
||||
}
|
||||
return {
|
||||
configFilePath,
|
||||
configFile,
|
||||
configFileError
|
||||
};
|
||||
}
|
||||
exports.getConfigFile = getConfigFile;
|
||||
/**
|
||||
* Find a tsconfig file by name or by path.
|
||||
* By name, the tsconfig.json is found using the same method as `tsc`, starting in the current
|
||||
* directory and continuing up the parent directory chain.
|
||||
* By path, the file will be found by resolving the given path relative to the requesting entry file.
|
||||
*
|
||||
* @param compiler The TypeScript compiler instance
|
||||
* @param requestDirPath The directory in which the entry point requesting the tsconfig.json lies
|
||||
* @param configFile The tsconfig file name to look for or a path to that file
|
||||
* @return The absolute path to the tsconfig file, undefined if none was found.
|
||||
*/
|
||||
function findConfigFile(compiler, requestDirPath, configFile) {
|
||||
// If `configFile` is an absolute path, return it right away
|
||||
if (path.isAbsolute(configFile)) {
|
||||
return compiler.sys.fileExists(configFile) ? configFile : undefined;
|
||||
}
|
||||
// If `configFile` is a relative path, resolve it.
|
||||
// We define a relative path as: starts with
|
||||
// one or two dots + a common directory delimiter
|
||||
if (configFile.match(/^\.\.?(\/|\\)/) !== null) {
|
||||
const resolvedPath = path.resolve(requestDirPath, configFile);
|
||||
return compiler.sys.fileExists(resolvedPath) ? resolvedPath : undefined;
|
||||
// If `configFile` is a file name, find it in the directory tree
|
||||
}
|
||||
else {
|
||||
while (true) {
|
||||
const fileName = path.join(requestDirPath, configFile);
|
||||
if (compiler.sys.fileExists(fileName)) {
|
||||
return fileName;
|
||||
}
|
||||
const parentPath = path.dirname(requestDirPath);
|
||||
if (parentPath === requestDirPath) {
|
||||
break;
|
||||
}
|
||||
requestDirPath = parentPath;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
function getConfigParseResult(compiler, configFile, basePath) {
|
||||
const configParseResult = compiler.parseJsonConfigFileContent(configFile.config, compiler.sys, basePath);
|
||||
return configParseResult;
|
||||
}
|
||||
exports.getConfigParseResult = getConfigParseResult;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const os = require("os");
|
||||
exports.EOL = os.EOL;
|
||||
exports.CarriageReturnLineFeed = '\r\n';
|
||||
exports.LineFeed = '\n';
|
||||
exports.CarriageReturnLineFeedCode = 0;
|
||||
exports.LineFeedCode = 1;
|
||||
exports.extensionRegex = /\.[^.]+$/;
|
||||
exports.tsxRegex = /\.tsx$/i;
|
||||
exports.tsTsxRegex = /\.ts(x?)$/i;
|
||||
exports.dtsDtsxOrDtsDtsxMapRegex = /\.d\.ts(x?)(\.map)?$/i;
|
||||
exports.dtsTsTsxRegex = /(\.d)?\.ts(x?)$/i;
|
||||
exports.dtsTsTsxJsJsxRegex = /((\.d)?\.ts(x?)|js(x?))$/i;
|
||||
exports.tsTsxJsJsxRegex = /\.tsx?$|\.jsx?$/i;
|
||||
exports.jsJsx = /\.js(x?)$/i;
|
||||
exports.jsJsxMap = /\.js(x?)\.map$/i;
|
||||
exports.jsonRegex = /\.json$/i;
|
||||
exports.nodeModules = /node_modules/i;
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
"use strict";
|
||||
const loaderUtils = require("loader-utils");
|
||||
const path = require("path");
|
||||
const constants = require("./constants");
|
||||
const instances_1 = require("./instances");
|
||||
const utils_1 = require("./utils");
|
||||
const webpackInstances = [];
|
||||
const loaderOptionsCache = {};
|
||||
/**
|
||||
* The entry point for ts-loader
|
||||
*/
|
||||
function loader(contents) {
|
||||
// tslint:disable-next-line:no-unused-expression strict-boolean-expressions
|
||||
this.cacheable && this.cacheable();
|
||||
const callback = this.async();
|
||||
const options = getLoaderOptions(this);
|
||||
const instanceOrError = instances_1.getTypeScriptInstance(options, this);
|
||||
if (instanceOrError.error !== undefined) {
|
||||
callback(new Error(instanceOrError.error.message));
|
||||
return;
|
||||
}
|
||||
return successLoader(this, contents, callback, options, instanceOrError.instance);
|
||||
}
|
||||
function successLoader(loaderContext, contents, callback, options, instance) {
|
||||
const rawFilePath = path.normalize(loaderContext.resourcePath);
|
||||
const filePath = options.appendTsSuffixTo.length > 0 || options.appendTsxSuffixTo.length > 0
|
||||
? utils_1.appendSuffixesIfMatch({
|
||||
'.ts': options.appendTsSuffixTo,
|
||||
'.tsx': options.appendTsxSuffixTo
|
||||
}, rawFilePath)
|
||||
: rawFilePath;
|
||||
const fileVersion = updateFileInCache(filePath, contents, instance);
|
||||
const referencedProject = utils_1.getAndCacheProjectReference(filePath, instance);
|
||||
if (referencedProject !== undefined) {
|
||||
const [relativeProjectConfigPath, relativeFilePath] = [
|
||||
path.relative(loaderContext.rootContext, referencedProject.sourceFile.fileName),
|
||||
path.relative(loaderContext.rootContext, filePath)
|
||||
];
|
||||
if (referencedProject.commandLine.options.outFile !== undefined) {
|
||||
throw new Error(`The referenced project at ${relativeProjectConfigPath} is using ` +
|
||||
`the outFile' option, which is not supported with ts-loader.`);
|
||||
}
|
||||
const jsFileName = utils_1.getAndCacheOutputJSFileName(filePath, referencedProject, instance);
|
||||
const relativeJSFileName = path.relative(loaderContext.rootContext, jsFileName);
|
||||
if (!instance.compiler.sys.fileExists(jsFileName)) {
|
||||
throw new Error(`Could not find output JavaScript file for input ` +
|
||||
`${relativeFilePath} (looked at ${relativeJSFileName}).\n` +
|
||||
`The input file is part of a project reference located at ` +
|
||||
`${relativeProjectConfigPath}, so ts-loader is looking for the ` +
|
||||
'project’s pre-built output on disk. Try running `tsc --build` ' +
|
||||
'to build project references.');
|
||||
}
|
||||
// Since the output JS file is being read from disk instead of using the
|
||||
// input TS file, we need to tell the loader that the compilation doesn’t
|
||||
// actually depend on the current file, but depends on the JS file instead.
|
||||
loaderContext.clearDependencies();
|
||||
loaderContext.addDependency(jsFileName);
|
||||
utils_1.validateSourceMapOncePerProject(instance, loaderContext, jsFileName, referencedProject);
|
||||
const mapFileName = jsFileName + '.map';
|
||||
const outputText = instance.compiler.sys.readFile(jsFileName);
|
||||
const sourceMapText = instance.compiler.sys.readFile(mapFileName);
|
||||
makeSourceMapAndFinish(sourceMapText, outputText, filePath, contents, loaderContext, options, fileVersion, callback);
|
||||
}
|
||||
else {
|
||||
const { outputText, sourceMapText } = options.transpileOnly
|
||||
? getTranspilationEmit(filePath, contents, instance, loaderContext)
|
||||
: getEmit(rawFilePath, filePath, instance, loaderContext);
|
||||
makeSourceMapAndFinish(sourceMapText, outputText, filePath, contents, loaderContext, options, fileVersion, callback);
|
||||
}
|
||||
}
|
||||
function makeSourceMapAndFinish(sourceMapText, outputText, filePath, contents, loaderContext, options, fileVersion, callback) {
|
||||
if (outputText === null || outputText === undefined) {
|
||||
const additionalGuidance = !options.allowTsInNodeModules && filePath.indexOf('node_modules') !== -1
|
||||
? ' By default, ts-loader will not compile .ts files in node_modules.\n' +
|
||||
'You should not need to recompile .ts files there, but if you really want to, use the allowTsInNodeModules option.\n' +
|
||||
'See: https://github.com/Microsoft/TypeScript/issues/12358'
|
||||
: '';
|
||||
throw new Error(`TypeScript emitted no output for ${filePath}.${additionalGuidance}`);
|
||||
}
|
||||
const { sourceMap, output } = makeSourceMap(sourceMapText, outputText, filePath, contents, loaderContext);
|
||||
// _module.meta is not available inside happypack
|
||||
if (!options.happyPackMode && loaderContext._module.buildMeta !== undefined) {
|
||||
// Make sure webpack is aware that even though the emitted JavaScript may be the same as
|
||||
// a previously cached version the TypeScript may be different and therefore should be
|
||||
// treated as new
|
||||
loaderContext._module.buildMeta.tsLoaderFileVersion = fileVersion;
|
||||
}
|
||||
callback(null, output, sourceMap);
|
||||
}
|
||||
/**
|
||||
* either retrieves loader options from the cache
|
||||
* or creates them, adds them to the cache and returns
|
||||
*/
|
||||
function getLoaderOptions(loaderContext) {
|
||||
// differentiate the TypeScript instance based on the webpack instance
|
||||
let webpackIndex = webpackInstances.indexOf(loaderContext._compiler);
|
||||
if (webpackIndex === -1) {
|
||||
webpackIndex = webpackInstances.push(loaderContext._compiler) - 1;
|
||||
}
|
||||
const loaderOptions = loaderUtils.getOptions(loaderContext) ||
|
||||
{};
|
||||
const instanceName = webpackIndex + '_' + (loaderOptions.instance || 'default');
|
||||
if (!loaderOptionsCache.hasOwnProperty(instanceName)) {
|
||||
loaderOptionsCache[instanceName] = new WeakMap();
|
||||
}
|
||||
const cache = loaderOptionsCache[instanceName];
|
||||
if (cache.has(loaderOptions)) {
|
||||
return cache.get(loaderOptions);
|
||||
}
|
||||
validateLoaderOptions(loaderOptions);
|
||||
const options = makeLoaderOptions(instanceName, loaderOptions);
|
||||
cache.set(loaderOptions, options);
|
||||
return options;
|
||||
}
|
||||
const validLoaderOptions = [
|
||||
'silent',
|
||||
'logLevel',
|
||||
'logInfoToStdOut',
|
||||
'instance',
|
||||
'compiler',
|
||||
'context',
|
||||
'configFile',
|
||||
'transpileOnly',
|
||||
'ignoreDiagnostics',
|
||||
'errorFormatter',
|
||||
'colors',
|
||||
'compilerOptions',
|
||||
'appendTsSuffixTo',
|
||||
'appendTsxSuffixTo',
|
||||
'onlyCompileBundledFiles',
|
||||
'happyPackMode',
|
||||
'getCustomTransformers',
|
||||
'reportFiles',
|
||||
'experimentalWatchApi',
|
||||
'allowTsInNodeModules',
|
||||
'experimentalFileCaching',
|
||||
'projectReferences',
|
||||
'resolveModuleName',
|
||||
'resolveTypeReferenceDirective'
|
||||
];
|
||||
/**
|
||||
* Validate the supplied loader options.
|
||||
* At present this validates the option names only; in future we may look at validating the values too
|
||||
* @param loaderOptions
|
||||
*/
|
||||
function validateLoaderOptions(loaderOptions) {
|
||||
const loaderOptionKeys = Object.keys(loaderOptions);
|
||||
// tslint:disable-next-line:prefer-for-of
|
||||
for (let i = 0; i < loaderOptionKeys.length; i++) {
|
||||
const option = loaderOptionKeys[i];
|
||||
const isUnexpectedOption = validLoaderOptions.indexOf(option) === -1;
|
||||
if (isUnexpectedOption) {
|
||||
throw new Error(`ts-loader was supplied with an unexpected loader option: ${option}
|
||||
|
||||
Please take a look at the options you are supplying; the following are valid options:
|
||||
${validLoaderOptions.join(' / ')}
|
||||
`);
|
||||
}
|
||||
}
|
||||
if (loaderOptions.context !== undefined &&
|
||||
!path.isAbsolute(loaderOptions.context)) {
|
||||
throw new Error(`Option 'context' has to be an absolute path. Given '${loaderOptions.context}'.`);
|
||||
}
|
||||
}
|
||||
function makeLoaderOptions(instanceName, loaderOptions) {
|
||||
const options = Object.assign({}, {
|
||||
silent: false,
|
||||
logLevel: 'WARN',
|
||||
logInfoToStdOut: false,
|
||||
compiler: 'typescript',
|
||||
configFile: 'tsconfig.json',
|
||||
context: undefined,
|
||||
transpileOnly: false,
|
||||
compilerOptions: {},
|
||||
appendTsSuffixTo: [],
|
||||
appendTsxSuffixTo: [],
|
||||
transformers: {},
|
||||
happyPackMode: false,
|
||||
colors: true,
|
||||
onlyCompileBundledFiles: false,
|
||||
reportFiles: [],
|
||||
// When the watch API usage stabilises look to remove this option and make watch usage the default behaviour when available
|
||||
experimentalWatchApi: false,
|
||||
allowTsInNodeModules: false,
|
||||
experimentalFileCaching: true
|
||||
}, loaderOptions);
|
||||
options.ignoreDiagnostics = utils_1.arrify(options.ignoreDiagnostics).map(Number);
|
||||
options.logLevel = options.logLevel.toUpperCase();
|
||||
options.instance = instanceName;
|
||||
// happypack can be used only together with transpileOnly mode
|
||||
options.transpileOnly = options.happyPackMode ? true : options.transpileOnly;
|
||||
return options;
|
||||
}
|
||||
/**
|
||||
* Either add file to the overall files cache or update it in the cache when the file contents have changed
|
||||
* Also add the file to the modified files
|
||||
*/
|
||||
function updateFileInCache(filePath, contents, instance) {
|
||||
let fileWatcherEventKind;
|
||||
// Update file contents
|
||||
let file = instance.files.get(filePath);
|
||||
if (file === undefined) {
|
||||
file = instance.otherFiles.get(filePath);
|
||||
if (file !== undefined) {
|
||||
instance.otherFiles.delete(filePath);
|
||||
instance.files.set(filePath, file);
|
||||
}
|
||||
else {
|
||||
if (instance.watchHost !== undefined) {
|
||||
fileWatcherEventKind = instance.compiler.FileWatcherEventKind.Created;
|
||||
}
|
||||
file = { version: 0 };
|
||||
instance.files.set(filePath, file);
|
||||
}
|
||||
instance.changedFilesList = true;
|
||||
}
|
||||
if (instance.watchHost !== undefined && contents === undefined) {
|
||||
fileWatcherEventKind = instance.compiler.FileWatcherEventKind.Deleted;
|
||||
}
|
||||
if (file.text !== contents) {
|
||||
file.version++;
|
||||
file.text = contents;
|
||||
instance.version++;
|
||||
if (instance.watchHost !== undefined &&
|
||||
fileWatcherEventKind === undefined) {
|
||||
fileWatcherEventKind = instance.compiler.FileWatcherEventKind.Changed;
|
||||
}
|
||||
}
|
||||
if (instance.watchHost !== undefined && fileWatcherEventKind !== undefined) {
|
||||
instance.hasUnaccountedModifiedFiles = true;
|
||||
instance.watchHost.invokeFileWatcher(filePath, fileWatcherEventKind);
|
||||
instance.watchHost.invokeDirectoryWatcher(path.dirname(filePath), filePath);
|
||||
}
|
||||
// push this file to modified files hash.
|
||||
if (instance.modifiedFiles === null || instance.modifiedFiles === undefined) {
|
||||
instance.modifiedFiles = new Map();
|
||||
}
|
||||
instance.modifiedFiles.set(filePath, file);
|
||||
return file.version;
|
||||
}
|
||||
function getEmit(rawFilePath, filePath, instance, loaderContext) {
|
||||
const outputFiles = instances_1.getEmitOutput(instance, filePath);
|
||||
loaderContext.clearDependencies();
|
||||
loaderContext.addDependency(rawFilePath);
|
||||
const allDefinitionFiles = [...instance.files.keys()].filter(defFilePath => defFilePath.match(constants.dtsDtsxOrDtsDtsxMapRegex));
|
||||
// Make this file dependent on *all* definition files in the program
|
||||
const addDependency = loaderContext.addDependency.bind(loaderContext);
|
||||
allDefinitionFiles.forEach(addDependency);
|
||||
// Additionally make this file dependent on all imported files
|
||||
const fileDependencies = instance.dependencyGraph[filePath];
|
||||
const additionalDependencies = fileDependencies === undefined
|
||||
? []
|
||||
: fileDependencies.map(({ resolvedFileName, originalFileName }) => {
|
||||
const projectReference = utils_1.getAndCacheProjectReference(resolvedFileName, instance);
|
||||
// In the case of dependencies that are part of a project reference,
|
||||
// the real dependency that webpack should watch is the JS output file.
|
||||
return projectReference !== undefined
|
||||
? utils_1.getAndCacheOutputJSFileName(resolvedFileName, projectReference, instance)
|
||||
: originalFileName;
|
||||
});
|
||||
if (additionalDependencies.length > 0) {
|
||||
additionalDependencies.forEach(addDependency);
|
||||
}
|
||||
loaderContext._module.buildMeta.tsLoaderDefinitionFileVersions = allDefinitionFiles
|
||||
.concat(additionalDependencies)
|
||||
.map(defFilePath => defFilePath +
|
||||
'@' +
|
||||
(instance.files.get(defFilePath) || { version: '?' }).version);
|
||||
const outputFile = outputFiles
|
||||
.filter(file => file.name.match(constants.jsJsx))
|
||||
.pop();
|
||||
const outputText = outputFile === undefined ? undefined : outputFile.text;
|
||||
const sourceMapFile = outputFiles
|
||||
.filter(file => file.name.match(constants.jsJsxMap))
|
||||
.pop();
|
||||
const sourceMapText = sourceMapFile === undefined ? undefined : sourceMapFile.text;
|
||||
return { outputText, sourceMapText };
|
||||
}
|
||||
/**
|
||||
* Transpile file
|
||||
*/
|
||||
function getTranspilationEmit(fileName, contents, instance, loaderContext) {
|
||||
const { outputText, sourceMapText, diagnostics } = instance.compiler.transpileModule(contents, {
|
||||
compilerOptions: Object.assign({}, instance.compilerOptions, { rootDir: undefined }),
|
||||
transformers: instance.transformers,
|
||||
reportDiagnostics: true,
|
||||
fileName
|
||||
});
|
||||
// _module.errors is not available inside happypack - see https://github.com/TypeStrong/ts-loader/issues/336
|
||||
if (!instance.loaderOptions.happyPackMode) {
|
||||
const errors = utils_1.formatErrors(diagnostics, instance.loaderOptions, instance.colors, instance.compiler, { module: loaderContext._module }, loaderContext.context);
|
||||
loaderContext._module.errors.push(...errors);
|
||||
}
|
||||
return { outputText, sourceMapText };
|
||||
}
|
||||
function makeSourceMap(sourceMapText, outputText, filePath, contents, loaderContext) {
|
||||
if (sourceMapText === undefined) {
|
||||
return { output: outputText, sourceMap: undefined };
|
||||
}
|
||||
return {
|
||||
output: outputText.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''),
|
||||
sourceMap: Object.assign(JSON.parse(sourceMapText), {
|
||||
sources: [loaderUtils.getRemainingRequest(loaderContext)],
|
||||
file: filePath,
|
||||
sourcesContent: [contents]
|
||||
})
|
||||
};
|
||||
}
|
||||
module.exports = loader;
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const chalk_1 = require("chalk");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const after_compile_1 = require("./after-compile");
|
||||
const compilerSetup_1 = require("./compilerSetup");
|
||||
const config_1 = require("./config");
|
||||
const constants_1 = require("./constants");
|
||||
const logger = require("./logger");
|
||||
const servicesHost_1 = require("./servicesHost");
|
||||
const utils_1 = require("./utils");
|
||||
const watch_run_1 = require("./watch-run");
|
||||
const instances = {};
|
||||
/**
|
||||
* The loader is executed once for each file seen by webpack. However, we need to keep
|
||||
* a persistent instance of TypeScript that contains all of the files in the program
|
||||
* along with definition files and options. This function either creates an instance
|
||||
* or returns the existing one. Multiple instances are possible by using the
|
||||
* `instance` property.
|
||||
*/
|
||||
function getTypeScriptInstance(loaderOptions, loader) {
|
||||
if (instances.hasOwnProperty(loaderOptions.instance)) {
|
||||
const instance = instances[loaderOptions.instance];
|
||||
utils_1.ensureProgram(instance);
|
||||
return { instance: instances[loaderOptions.instance] };
|
||||
}
|
||||
const colors = new chalk_1.default.constructor({ enabled: loaderOptions.colors });
|
||||
const log = logger.makeLogger(loaderOptions, colors);
|
||||
const compiler = compilerSetup_1.getCompiler(loaderOptions, log);
|
||||
if (compiler.errorMessage !== undefined) {
|
||||
return { error: utils_1.makeError(colors.red(compiler.errorMessage), undefined) };
|
||||
}
|
||||
return successfulTypeScriptInstance(loaderOptions, loader, log, colors, compiler.compiler, compiler.compilerCompatible, compiler.compilerDetailsLogMessage);
|
||||
}
|
||||
exports.getTypeScriptInstance = getTypeScriptInstance;
|
||||
function successfulTypeScriptInstance(loaderOptions, loader, log, colors, compiler, compilerCompatible, compilerDetailsLogMessage) {
|
||||
const configFileAndPath = config_1.getConfigFile(compiler, colors, loader, loaderOptions, compilerCompatible, log, compilerDetailsLogMessage);
|
||||
if (configFileAndPath.configFileError !== undefined) {
|
||||
const { message, file } = configFileAndPath.configFileError;
|
||||
return {
|
||||
error: utils_1.makeError(colors.red('error while reading tsconfig.json:' + constants_1.EOL + message), file)
|
||||
};
|
||||
}
|
||||
const { configFilePath, configFile } = configFileAndPath;
|
||||
const basePath = loaderOptions.context || path.dirname(configFilePath || '');
|
||||
const configParseResult = config_1.getConfigParseResult(compiler, configFile, basePath);
|
||||
if (configParseResult.errors.length > 0 && !loaderOptions.happyPackMode) {
|
||||
const errors = utils_1.formatErrors(configParseResult.errors, loaderOptions, colors, compiler, { file: configFilePath }, loader.context);
|
||||
loader._module.errors.push(...errors);
|
||||
return {
|
||||
error: utils_1.makeError(colors.red('error while parsing tsconfig.json'), configFilePath)
|
||||
};
|
||||
}
|
||||
const compilerOptions = compilerSetup_1.getCompilerOptions(configParseResult);
|
||||
const files = new Map();
|
||||
const otherFiles = new Map();
|
||||
const appendTsTsxSuffixesIfRequired = loaderOptions.appendTsSuffixTo.length > 0 ||
|
||||
loaderOptions.appendTsxSuffixTo.length > 0
|
||||
? (filePath) => utils_1.appendSuffixesIfMatch({
|
||||
'.ts': loaderOptions.appendTsSuffixTo,
|
||||
'.tsx': loaderOptions.appendTsxSuffixTo
|
||||
}, filePath)
|
||||
: (filePath) => filePath;
|
||||
// same strategy as https://github.com/s-panferov/awesome-typescript-loader/pull/531/files
|
||||
let { getCustomTransformers: customerTransformers } = loaderOptions;
|
||||
let getCustomTransformers = Function.prototype;
|
||||
if (typeof customerTransformers === 'function') {
|
||||
getCustomTransformers = customerTransformers;
|
||||
}
|
||||
else if (typeof customerTransformers === 'string') {
|
||||
try {
|
||||
customerTransformers = require(customerTransformers);
|
||||
}
|
||||
catch (err) {
|
||||
throw new Error(`Failed to load customTransformers from "${loaderOptions.getCustomTransformers}": ${err.message}`);
|
||||
}
|
||||
if (typeof customerTransformers !== 'function') {
|
||||
throw new Error(`Custom transformers in "${loaderOptions.getCustomTransformers}" should export a function, got ${typeof getCustomTransformers}`);
|
||||
}
|
||||
getCustomTransformers = customerTransformers;
|
||||
}
|
||||
if (loaderOptions.transpileOnly) {
|
||||
// quick return for transpiling
|
||||
// we do need to check for any issues with TS options though
|
||||
const program = configParseResult.projectReferences !== undefined
|
||||
? compiler.createProgram({
|
||||
rootNames: configParseResult.fileNames,
|
||||
options: configParseResult.options,
|
||||
projectReferences: configParseResult.projectReferences
|
||||
})
|
||||
: compiler.createProgram([], compilerOptions);
|
||||
// happypack does not have _module.errors - see https://github.com/TypeStrong/ts-loader/issues/336
|
||||
if (!loaderOptions.happyPackMode) {
|
||||
const diagnostics = program.getOptionsDiagnostics();
|
||||
const errors = utils_1.formatErrors(diagnostics, loaderOptions, colors, compiler, { file: configFilePath || 'tsconfig.json' }, loader.context);
|
||||
loader._module.errors.push(...errors);
|
||||
}
|
||||
instances[loaderOptions.instance] = {
|
||||
compiler,
|
||||
compilerOptions,
|
||||
appendTsTsxSuffixesIfRequired,
|
||||
loaderOptions,
|
||||
files,
|
||||
otherFiles,
|
||||
program,
|
||||
dependencyGraph: {},
|
||||
reverseDependencyGraph: {},
|
||||
transformers: getCustomTransformers(program),
|
||||
colors
|
||||
};
|
||||
return { instance: instances[loaderOptions.instance] };
|
||||
}
|
||||
// Load initial files (core lib files, any files specified in tsconfig.json)
|
||||
let normalizedFilePath;
|
||||
try {
|
||||
const filesToLoad = loaderOptions.onlyCompileBundledFiles
|
||||
? configParseResult.fileNames.filter(fileName => constants_1.dtsDtsxOrDtsDtsxMapRegex.test(fileName))
|
||||
: configParseResult.fileNames;
|
||||
filesToLoad.forEach(filePath => {
|
||||
normalizedFilePath = path.normalize(filePath);
|
||||
files.set(normalizedFilePath, {
|
||||
text: fs.readFileSync(normalizedFilePath, 'utf-8'),
|
||||
version: 0
|
||||
});
|
||||
});
|
||||
}
|
||||
catch (exc) {
|
||||
return {
|
||||
error: utils_1.makeError(colors.red(`A file specified in tsconfig.json could not be found: ${normalizedFilePath}`), normalizedFilePath)
|
||||
};
|
||||
}
|
||||
// if allowJs is set then we should accept js(x) files
|
||||
const scriptRegex = configParseResult.options.allowJs === true
|
||||
? /\.tsx?$|\.jsx?$/i
|
||||
: /\.tsx?$/i;
|
||||
const instance = (instances[loaderOptions.instance] = {
|
||||
compiler,
|
||||
compilerOptions,
|
||||
appendTsTsxSuffixesIfRequired,
|
||||
loaderOptions,
|
||||
files,
|
||||
otherFiles,
|
||||
languageService: null,
|
||||
version: 0,
|
||||
transformers: {},
|
||||
dependencyGraph: {},
|
||||
reverseDependencyGraph: {},
|
||||
modifiedFiles: null,
|
||||
colors
|
||||
});
|
||||
if (!loader._compiler.hooks) {
|
||||
throw new Error("You may be using an old version of webpack; please check you're using at least version 4");
|
||||
}
|
||||
if (loaderOptions.experimentalWatchApi && compiler.createWatchProgram) {
|
||||
log.logInfo('Using watch api');
|
||||
// If there is api available for watch, use it instead of language service
|
||||
instance.watchHost = servicesHost_1.makeWatchHost(scriptRegex, log, loader, instance, configParseResult.projectReferences);
|
||||
instance.watchOfFilesAndCompilerOptions = compiler.createWatchProgram(instance.watchHost);
|
||||
instance.program = instance.watchOfFilesAndCompilerOptions
|
||||
.getProgram()
|
||||
.getProgram();
|
||||
instance.transformers = getCustomTransformers(instance.program);
|
||||
}
|
||||
else {
|
||||
const servicesHost = servicesHost_1.makeServicesHost(scriptRegex, log, loader, instance, loaderOptions.experimentalFileCaching, configParseResult.projectReferences);
|
||||
instance.languageService = compiler.createLanguageService(servicesHost.servicesHost, compiler.createDocumentRegistry());
|
||||
if (servicesHost.clearCache !== null) {
|
||||
loader._compiler.hooks.watchRun.tap('ts-loader', servicesHost.clearCache);
|
||||
}
|
||||
instance.transformers = getCustomTransformers(instance.languageService.getProgram());
|
||||
}
|
||||
loader._compiler.hooks.afterCompile.tapAsync('ts-loader', after_compile_1.makeAfterCompile(instance, configFilePath));
|
||||
loader._compiler.hooks.watchRun.tapAsync('ts-loader', watch_run_1.makeWatchRun(instance));
|
||||
return { instance };
|
||||
}
|
||||
function getEmitOutput(instance, filePath) {
|
||||
const program = utils_1.ensureProgram(instance);
|
||||
if (program !== undefined) {
|
||||
const outputFiles = [];
|
||||
const writeFile = (fileName, text, writeByteOrderMark) => outputFiles.push({ name: fileName, writeByteOrderMark, text });
|
||||
const sourceFile = program.getSourceFile(filePath);
|
||||
// The source file will be undefined if it’s part of an unbuilt project reference
|
||||
if (sourceFile !== undefined || !utils_1.isUsingProjectReferences(instance)) {
|
||||
program.emit(sourceFile, writeFile,
|
||||
/*cancellationToken*/ undefined,
|
||||
/*emitOnlyDtsFiles*/ false, instance.transformers);
|
||||
}
|
||||
return outputFiles;
|
||||
}
|
||||
else {
|
||||
// Emit Javascript
|
||||
return instance.languageService.getProgram().getSourceFile(filePath) ===
|
||||
undefined
|
||||
? []
|
||||
: instance.languageService.getEmitOutput(filePath).outputFiles;
|
||||
}
|
||||
}
|
||||
exports.getEmitOutput = getEmitOutput;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const console_1 = require("console");
|
||||
var LogLevel;
|
||||
(function (LogLevel) {
|
||||
LogLevel[LogLevel["INFO"] = 1] = "INFO";
|
||||
LogLevel[LogLevel["WARN"] = 2] = "WARN";
|
||||
LogLevel[LogLevel["ERROR"] = 3] = "ERROR";
|
||||
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
|
||||
const stderrConsole = new console_1.Console(process.stderr);
|
||||
const stdoutConsole = new console_1.Console(process.stdout);
|
||||
const doNothingLogger = (_message) => { };
|
||||
const makeLoggerFunc = (loaderOptions) => loaderOptions.silent
|
||||
? (_whereToLog, _message) => { }
|
||||
: (whereToLog, message) =>
|
||||
// tslint:disable-next-line:no-console
|
||||
console.log.call(whereToLog, message);
|
||||
const makeExternalLogger = (loaderOptions, logger) => (message) => logger(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, message);
|
||||
const makeLogInfo = (loaderOptions, logger, green) => LogLevel[loaderOptions.logLevel] <= LogLevel.INFO
|
||||
? (message) => logger(loaderOptions.logInfoToStdOut ? stdoutConsole : stderrConsole, green(message))
|
||||
: doNothingLogger;
|
||||
const makeLogError = (loaderOptions, logger, red) => LogLevel[loaderOptions.logLevel] <= LogLevel.ERROR
|
||||
? (message) => logger(stderrConsole, red(message))
|
||||
: doNothingLogger;
|
||||
const makeLogWarning = (loaderOptions, logger, yellow) => LogLevel[loaderOptions.logLevel] <= LogLevel.WARN
|
||||
? (message) => logger(stderrConsole, yellow(message))
|
||||
: doNothingLogger;
|
||||
function makeLogger(loaderOptions, colors) {
|
||||
const logger = makeLoggerFunc(loaderOptions);
|
||||
return {
|
||||
log: makeExternalLogger(loaderOptions, logger),
|
||||
logInfo: makeLogInfo(loaderOptions, logger, colors.green),
|
||||
logWarning: makeLogWarning(loaderOptions, logger, colors.yellow),
|
||||
logError: makeLogError(loaderOptions, logger, colors.red)
|
||||
};
|
||||
}
|
||||
exports.makeLogger = makeLogger;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
// tslint:disable-next-line:no-submodule-imports
|
||||
const node = require('enhanced-resolve/lib/node');
|
||||
function makeResolver(options) {
|
||||
return node.create.sync(options.resolve);
|
||||
}
|
||||
exports.makeResolver = makeResolver;
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const constants = require("./constants");
|
||||
const resolver_1 = require("./resolver");
|
||||
const utils_1 = require("./utils");
|
||||
/**
|
||||
* Create the TypeScript language service
|
||||
*/
|
||||
function makeServicesHost(scriptRegex, log, loader, instance, enableFileCaching, projectReferences) {
|
||||
const { compiler, compilerOptions, appendTsTsxSuffixesIfRequired, files, loaderOptions: { resolveModuleName: customResolveModuleName, resolveTypeReferenceDirective: customResolveTypeReferenceDirective } } = instance;
|
||||
const newLine = compilerOptions.newLine === constants.CarriageReturnLineFeedCode
|
||||
? constants.CarriageReturnLineFeed
|
||||
: compilerOptions.newLine === constants.LineFeedCode
|
||||
? constants.LineFeed
|
||||
: constants.EOL;
|
||||
// make a (sync) resolver that follows webpack's rules
|
||||
const resolveSync = resolver_1.makeResolver(loader._compiler.options);
|
||||
const readFileWithFallback = (filePath, encoding) => compiler.sys.readFile(filePath, encoding) || utils_1.readFile(filePath, encoding);
|
||||
const fileExists = (filePathToCheck) => compiler.sys.fileExists(filePathToCheck) ||
|
||||
utils_1.readFile(filePathToCheck) !== undefined;
|
||||
const moduleResolutionHost = {
|
||||
fileExists,
|
||||
readFile: readFileWithFallback,
|
||||
realpath: compiler.sys.realpath,
|
||||
directoryExists: compiler.sys.directoryExists
|
||||
};
|
||||
const clearCache = enableFileCaching ? addCache(moduleResolutionHost) : null;
|
||||
// loader.context seems to work fine on Linux / Mac regardless causes problems for @types resolution on Windows for TypeScript < 2.3
|
||||
const getCurrentDirectory = () => loader.context;
|
||||
const resolvers = makeResolvers(compiler, compilerOptions, moduleResolutionHost, customResolveTypeReferenceDirective, customResolveModuleName, resolveSync, appendTsTsxSuffixesIfRequired, scriptRegex, instance);
|
||||
const servicesHost = {
|
||||
getProjectVersion: () => `${instance.version}`,
|
||||
getProjectReferences: () => projectReferences,
|
||||
getScriptFileNames: () => [...files.keys()].filter(filePath => filePath.match(scriptRegex)),
|
||||
getScriptVersion: (fileName) => {
|
||||
fileName = path.normalize(fileName);
|
||||
const file = files.get(fileName);
|
||||
return file === undefined ? '' : file.version.toString();
|
||||
},
|
||||
getScriptSnapshot: (fileName) => {
|
||||
// This is called any time TypeScript needs a file's text
|
||||
// We either load from memory or from disk
|
||||
fileName = path.normalize(fileName);
|
||||
let file = files.get(fileName);
|
||||
if (file === undefined) {
|
||||
const text = utils_1.readFile(fileName);
|
||||
if (text === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
file = { version: 0, text };
|
||||
files.set(fileName, file);
|
||||
}
|
||||
return compiler.ScriptSnapshot.fromString(file.text);
|
||||
},
|
||||
/**
|
||||
* getDirectories is also required for full import and type reference completions.
|
||||
* Without it defined, certain completions will not be provided
|
||||
*/
|
||||
getDirectories: compiler.sys.getDirectories,
|
||||
/**
|
||||
* For @types expansion, these two functions are needed.
|
||||
*/
|
||||
directoryExists: moduleResolutionHost.directoryExists,
|
||||
useCaseSensitiveFileNames: () => compiler.sys.useCaseSensitiveFileNames,
|
||||
realpath: moduleResolutionHost.realpath,
|
||||
// The following three methods are necessary for @types resolution from TS 2.4.1 onwards see: https://github.com/Microsoft/TypeScript/issues/16772
|
||||
fileExists: moduleResolutionHost.fileExists,
|
||||
readFile: moduleResolutionHost.readFile,
|
||||
readDirectory: compiler.sys.readDirectory,
|
||||
getCurrentDirectory,
|
||||
getCompilationSettings: () => compilerOptions,
|
||||
getDefaultLibFileName: (options) => compiler.getDefaultLibFilePath(options),
|
||||
getNewLine: () => newLine,
|
||||
trace: log.log,
|
||||
log: log.log,
|
||||
// used for (/// <reference types="...">) see https://github.com/Realytics/fork-ts-checker-webpack-plugin/pull/250#issuecomment-485061329
|
||||
resolveTypeReferenceDirectives: resolvers.resolveTypeReferenceDirectives,
|
||||
resolveModuleNames: resolvers.resolveModuleNames,
|
||||
getCustomTransformers: () => instance.transformers
|
||||
};
|
||||
return { servicesHost, clearCache };
|
||||
}
|
||||
exports.makeServicesHost = makeServicesHost;
|
||||
function makeResolvers(compiler, compilerOptions, moduleResolutionHost, customResolveTypeReferenceDirective, customResolveModuleName, resolveSync, appendTsTsxSuffixesIfRequired, scriptRegex, instance) {
|
||||
const resolveTypeReferenceDirective = makeResolveTypeReferenceDirective(compiler, compilerOptions, moduleResolutionHost, customResolveTypeReferenceDirective);
|
||||
const resolveTypeReferenceDirectives = (typeDirectiveNames, containingFile, _redirectedReference) => typeDirectiveNames.map(directive => resolveTypeReferenceDirective(directive, containingFile)
|
||||
.resolvedTypeReferenceDirective);
|
||||
const resolveModuleName = makeResolveModuleName(compiler, compilerOptions, moduleResolutionHost, customResolveModuleName);
|
||||
const resolveModuleNames = (moduleNames, containingFile, _reusedNames, _redirectedReference) => {
|
||||
const resolvedModules = moduleNames.map(moduleName => resolveModule(resolveSync, resolveModuleName, appendTsTsxSuffixesIfRequired, scriptRegex, moduleName, containingFile));
|
||||
populateDependencyGraphs(resolvedModules, instance, containingFile);
|
||||
return resolvedModules;
|
||||
};
|
||||
return {
|
||||
resolveTypeReferenceDirectives,
|
||||
resolveModuleNames
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Create the TypeScript Watch host
|
||||
*/
|
||||
function makeWatchHost(scriptRegex, log, loader, instance, projectReferences) {
|
||||
const { compiler, compilerOptions, appendTsTsxSuffixesIfRequired, files, otherFiles, loaderOptions: { resolveModuleName: customResolveModuleName, resolveTypeReferenceDirective: customResolveTypeReferenceDirective } } = instance;
|
||||
const newLine = compilerOptions.newLine === constants.CarriageReturnLineFeedCode
|
||||
? constants.CarriageReturnLineFeed
|
||||
: compilerOptions.newLine === constants.LineFeedCode
|
||||
? constants.LineFeed
|
||||
: constants.EOL;
|
||||
// make a (sync) resolver that follows webpack's rules
|
||||
const resolveSync = resolver_1.makeResolver(loader._compiler.options);
|
||||
const readFileWithFallback = (filePath, encoding) => compiler.sys.readFile(filePath, encoding) || utils_1.readFile(filePath, encoding);
|
||||
const moduleResolutionHost = {
|
||||
fileExists,
|
||||
readFile: readFileWithFallback,
|
||||
realpath: compiler.sys.realpath
|
||||
};
|
||||
// loader.context seems to work fine on Linux / Mac regardless causes problems for @types resolution on Windows for TypeScript < 2.3
|
||||
const getCurrentDirectory = () => loader.context;
|
||||
const watchedFiles = {};
|
||||
const watchedDirectories = {};
|
||||
const watchedDirectoriesRecursive = {};
|
||||
const resolvers = makeResolvers(compiler, compilerOptions, moduleResolutionHost, customResolveTypeReferenceDirective, customResolveModuleName, resolveSync, appendTsTsxSuffixesIfRequired, scriptRegex, instance);
|
||||
const watchHost = {
|
||||
rootFiles: getRootFileNames(),
|
||||
options: compilerOptions,
|
||||
useCaseSensitiveFileNames: () => compiler.sys.useCaseSensitiveFileNames,
|
||||
getNewLine: () => newLine,
|
||||
getCurrentDirectory,
|
||||
getDefaultLibFileName: options => compiler.getDefaultLibFilePath(options),
|
||||
fileExists,
|
||||
readFile: readFileWithCachingText,
|
||||
directoryExists: dirPath => compiler.sys.directoryExists(path.normalize(dirPath)),
|
||||
getDirectories: dirPath => compiler.sys.getDirectories(path.normalize(dirPath)),
|
||||
readDirectory: (dirPath, extensions, exclude, include, depth) => compiler.sys.readDirectory(path.normalize(dirPath), extensions, exclude, include, depth),
|
||||
realpath: dirPath => compiler.sys.resolvePath(path.normalize(dirPath)),
|
||||
trace: logData => log.log(logData),
|
||||
watchFile,
|
||||
watchDirectory,
|
||||
// used for (/// <reference types="...">) see https://github.com/Realytics/fork-ts-checker-webpack-plugin/pull/250#issuecomment-485061329
|
||||
resolveTypeReferenceDirectives: resolvers.resolveTypeReferenceDirectives,
|
||||
resolveModuleNames: resolvers.resolveModuleNames,
|
||||
invokeFileWatcher,
|
||||
invokeDirectoryWatcher,
|
||||
updateRootFileNames: () => {
|
||||
instance.changedFilesList = false;
|
||||
if (instance.watchOfFilesAndCompilerOptions !== undefined) {
|
||||
instance.watchOfFilesAndCompilerOptions.updateRootFileNames(getRootFileNames());
|
||||
}
|
||||
},
|
||||
createProgram: projectReferences === undefined
|
||||
? compiler.createAbstractBuilder
|
||||
: createBuilderProgramWithReferences
|
||||
};
|
||||
return watchHost;
|
||||
function getRootFileNames() {
|
||||
return [...files.keys()].filter(filePath => filePath.match(scriptRegex));
|
||||
}
|
||||
function readFileWithCachingText(fileName, encoding) {
|
||||
fileName = path.normalize(fileName);
|
||||
const file = files.get(fileName) || otherFiles.get(fileName);
|
||||
if (file !== undefined) {
|
||||
return file.text;
|
||||
}
|
||||
const text = readFileWithFallback(fileName, encoding);
|
||||
if (text === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
otherFiles.set(fileName, { version: 0, text });
|
||||
return text;
|
||||
}
|
||||
function fileExists(fileName) {
|
||||
const filePath = path.normalize(fileName);
|
||||
return files.has(filePath) || compiler.sys.fileExists(filePath);
|
||||
}
|
||||
function invokeWatcherCallbacks(callbacks, fileName, eventKind) {
|
||||
if (callbacks !== undefined) {
|
||||
// The array copy is made to ensure that even if one of the callback removes the callbacks,
|
||||
// we dont miss any callbacks following it
|
||||
const cbs = callbacks.slice();
|
||||
for (const cb of cbs) {
|
||||
cb(fileName, eventKind);
|
||||
}
|
||||
}
|
||||
}
|
||||
function invokeFileWatcher(fileName, eventKind) {
|
||||
fileName = path.normalize(fileName);
|
||||
invokeWatcherCallbacks(watchedFiles[fileName], fileName, eventKind);
|
||||
}
|
||||
function invokeDirectoryWatcher(directory, fileAddedOrRemoved) {
|
||||
directory = path.normalize(directory);
|
||||
invokeWatcherCallbacks(watchedDirectories[directory], fileAddedOrRemoved);
|
||||
invokeRecursiveDirectoryWatcher(directory, fileAddedOrRemoved);
|
||||
}
|
||||
function invokeRecursiveDirectoryWatcher(directory, fileAddedOrRemoved) {
|
||||
directory = path.normalize(directory);
|
||||
invokeWatcherCallbacks(watchedDirectoriesRecursive[directory], fileAddedOrRemoved);
|
||||
const basePath = path.dirname(directory);
|
||||
if (directory !== basePath) {
|
||||
invokeRecursiveDirectoryWatcher(basePath, fileAddedOrRemoved);
|
||||
}
|
||||
}
|
||||
function createWatcher(file, callbacks, callback) {
|
||||
file = path.normalize(file);
|
||||
const existing = callbacks[file];
|
||||
if (existing === undefined) {
|
||||
callbacks[file] = [callback];
|
||||
}
|
||||
else {
|
||||
existing.push(callback);
|
||||
}
|
||||
return {
|
||||
close: () => {
|
||||
// tslint:disable-next-line:no-shadowed-variable
|
||||
const existing = callbacks[file];
|
||||
if (existing !== undefined) {
|
||||
utils_1.unorderedRemoveItem(existing, callback);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
function watchFile(fileName, callback, _pollingInterval) {
|
||||
return createWatcher(fileName, watchedFiles, callback);
|
||||
}
|
||||
function watchDirectory(fileName, callback, recursive) {
|
||||
return createWatcher(fileName, recursive === true ? watchedDirectoriesRecursive : watchedDirectories, callback);
|
||||
}
|
||||
function createBuilderProgramWithReferences(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
|
||||
const program = compiler.createProgram({
|
||||
rootNames: rootNames,
|
||||
options: options,
|
||||
host,
|
||||
oldProgram: oldProgram && oldProgram.getProgram(),
|
||||
configFileParsingDiagnostics,
|
||||
projectReferences
|
||||
});
|
||||
const builderProgramHost = host;
|
||||
return compiler.createAbstractBuilder(program, builderProgramHost, oldProgram, configFileParsingDiagnostics);
|
||||
}
|
||||
}
|
||||
exports.makeWatchHost = makeWatchHost;
|
||||
function makeResolveTypeReferenceDirective(compiler, compilerOptions, moduleResolutionHost, customResolveTypeReferenceDirective) {
|
||||
if (customResolveTypeReferenceDirective === undefined) {
|
||||
return (directive, containingFile) => compiler.resolveTypeReferenceDirective(directive, containingFile, compilerOptions, moduleResolutionHost);
|
||||
}
|
||||
return (directive, containingFile) => customResolveTypeReferenceDirective(directive, containingFile, compilerOptions, moduleResolutionHost, compiler.resolveTypeReferenceDirective);
|
||||
}
|
||||
function isJsImplementationOfTypings(resolvedModule, tsResolution) {
|
||||
return (resolvedModule.resolvedFileName.endsWith('js') &&
|
||||
/\.d\.ts$/.test(tsResolution.resolvedFileName));
|
||||
}
|
||||
function resolveModule(resolveSync, resolveModuleName, appendTsTsxSuffixesIfRequired, scriptRegex, moduleName, containingFile) {
|
||||
let resolutionResult;
|
||||
try {
|
||||
const originalFileName = resolveSync(undefined, path.normalize(path.dirname(containingFile)), moduleName);
|
||||
const resolvedFileName = appendTsTsxSuffixesIfRequired(originalFileName);
|
||||
if (resolvedFileName.match(scriptRegex) !== null) {
|
||||
resolutionResult = { resolvedFileName, originalFileName };
|
||||
}
|
||||
// tslint:disable-next-line:no-empty
|
||||
}
|
||||
catch (e) { }
|
||||
const tsResolution = resolveModuleName(moduleName, containingFile);
|
||||
if (tsResolution.resolvedModule !== undefined) {
|
||||
const resolvedFileName = path.normalize(tsResolution.resolvedModule.resolvedFileName);
|
||||
const tsResolutionResult = {
|
||||
originalFileName: resolvedFileName,
|
||||
resolvedFileName,
|
||||
isExternalLibraryImport: tsResolution.resolvedModule.isExternalLibraryImport
|
||||
};
|
||||
return resolutionResult === undefined ||
|
||||
resolutionResult.resolvedFileName ===
|
||||
tsResolutionResult.resolvedFileName ||
|
||||
isJsImplementationOfTypings(resolutionResult, tsResolutionResult)
|
||||
? tsResolutionResult
|
||||
: resolutionResult;
|
||||
}
|
||||
return resolutionResult;
|
||||
}
|
||||
function makeResolveModuleName(compiler, compilerOptions, moduleResolutionHost, customResolveModuleName) {
|
||||
if (customResolveModuleName === undefined) {
|
||||
return (moduleName, containingFile) => compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost);
|
||||
}
|
||||
return (moduleName, containingFile) => customResolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost, compiler.resolveModuleName);
|
||||
}
|
||||
function populateDependencyGraphs(resolvedModules, instance, containingFile) {
|
||||
resolvedModules = resolvedModules.filter(mod => mod !== null && mod !== undefined);
|
||||
instance.dependencyGraph[path.normalize(containingFile)] = resolvedModules;
|
||||
resolvedModules.forEach(resolvedModule => {
|
||||
if (instance.reverseDependencyGraph[resolvedModule.resolvedFileName] ===
|
||||
undefined) {
|
||||
instance.reverseDependencyGraph[resolvedModule.resolvedFileName] = {};
|
||||
}
|
||||
instance.reverseDependencyGraph[resolvedModule.resolvedFileName][path.normalize(containingFile)] = true;
|
||||
});
|
||||
}
|
||||
const cacheableFunctions = [
|
||||
'fileExists',
|
||||
'directoryExists',
|
||||
'realpath'
|
||||
];
|
||||
function addCache(servicesHost) {
|
||||
const clearCacheFunctions = [];
|
||||
cacheableFunctions.forEach((functionToCache) => {
|
||||
const originalFunction = servicesHost[functionToCache];
|
||||
if (originalFunction !== undefined) {
|
||||
const cache = createCache(originalFunction);
|
||||
servicesHost[functionToCache] = cache.getCached;
|
||||
clearCacheFunctions.push(cache.clear);
|
||||
}
|
||||
});
|
||||
return () => clearCacheFunctions.forEach(clear => clear());
|
||||
}
|
||||
function createCache(originalFunction) {
|
||||
const cache = new Map();
|
||||
return {
|
||||
clear: () => {
|
||||
cache.clear();
|
||||
},
|
||||
getCached: (arg) => {
|
||||
let res = cache.get(arg);
|
||||
if (res !== undefined) {
|
||||
return res;
|
||||
}
|
||||
res = originalFunction(arg);
|
||||
cache.set(arg, res);
|
||||
return res;
|
||||
}
|
||||
};
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import * as webpack from 'webpack';
|
||||
import { TSInstance } from './interfaces';
|
||||
export declare function makeAfterCompile(instance: TSInstance, configFilePath: string | undefined): (compilation: webpack.compilation.Compilation, callback: () => void) => void;
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
import * as typescript from 'typescript';
|
||||
import { LoaderOptions } from './interfaces';
|
||||
import * as logger from './logger';
|
||||
export declare function getCompiler(loaderOptions: LoaderOptions, log: logger.Logger): {
|
||||
compiler: typeof typescript | undefined;
|
||||
compilerCompatible: boolean;
|
||||
compilerDetailsLogMessage: string | undefined;
|
||||
errorMessage: string | undefined;
|
||||
};
|
||||
export declare function getCompilerOptions(configParseResult: typescript.ParsedCommandLine): typescript.CompilerOptions;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { Chalk } from 'chalk';
|
||||
import * as typescript from 'typescript';
|
||||
import * as webpack from 'webpack';
|
||||
import { LoaderOptions, WebpackError } from './interfaces';
|
||||
import * as logger from './logger';
|
||||
interface ConfigFile {
|
||||
config?: any;
|
||||
error?: typescript.Diagnostic;
|
||||
}
|
||||
export declare function getConfigFile(compiler: typeof typescript, colors: Chalk, loader: webpack.loader.LoaderContext, loaderOptions: LoaderOptions, compilerCompatible: boolean, log: logger.Logger, compilerDetailsLogMessage: string): {
|
||||
configFilePath: string | undefined;
|
||||
configFile: ConfigFile;
|
||||
configFileError: WebpackError | undefined;
|
||||
};
|
||||
export declare function getConfigParseResult(compiler: typeof typescript, configFile: ConfigFile, basePath: string): typescript.ParsedCommandLine;
|
||||
export {};
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
export declare const EOL: string;
|
||||
export declare const CarriageReturnLineFeed = "\r\n";
|
||||
export declare const LineFeed = "\n";
|
||||
export declare const CarriageReturnLineFeedCode = 0;
|
||||
export declare const LineFeedCode = 1;
|
||||
export declare const extensionRegex: RegExp;
|
||||
export declare const tsxRegex: RegExp;
|
||||
export declare const tsTsxRegex: RegExp;
|
||||
export declare const dtsDtsxOrDtsDtsxMapRegex: RegExp;
|
||||
export declare const dtsTsTsxRegex: RegExp;
|
||||
export declare const dtsTsTsxJsJsxRegex: RegExp;
|
||||
export declare const tsTsxJsJsxRegex: RegExp;
|
||||
export declare const jsJsx: RegExp;
|
||||
export declare const jsJsxMap: RegExp;
|
||||
export declare const jsonRegex: RegExp;
|
||||
export declare const nodeModules: RegExp;
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import * as webpack from 'webpack';
|
||||
import { LoaderOptions } from './interfaces';
|
||||
/**
|
||||
* The entry point for ts-loader
|
||||
*/
|
||||
declare function loader(this: webpack.loader.LoaderContext, contents: string): void;
|
||||
export = loader;
|
||||
/**
|
||||
* expose public types via declaration merging
|
||||
*/
|
||||
declare namespace loader {
|
||||
interface Options extends LoaderOptions {
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
import * as typescript from 'typescript';
|
||||
import * as webpack from 'webpack';
|
||||
import { LoaderOptions, TSInstance, WebpackError } from './interfaces';
|
||||
/**
|
||||
* The loader is executed once for each file seen by webpack. However, we need to keep
|
||||
* a persistent instance of TypeScript that contains all of the files in the program
|
||||
* along with definition files and options. This function either creates an instance
|
||||
* or returns the existing one. Multiple instances are possible by using the
|
||||
* `instance` property.
|
||||
*/
|
||||
export declare function getTypeScriptInstance(loaderOptions: LoaderOptions, loader: webpack.loader.LoaderContext): {
|
||||
instance?: TSInstance;
|
||||
error?: WebpackError;
|
||||
};
|
||||
export declare function getEmitOutput(instance: TSInstance, filePath: string): typescript.OutputFile[];
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
export { ModuleResolutionHost } from 'typescript';
|
||||
import * as typescript from 'typescript';
|
||||
import { Chalk } from 'chalk';
|
||||
export interface ErrorInfo {
|
||||
code: number;
|
||||
severity: Severity;
|
||||
content: string;
|
||||
file: string;
|
||||
line: number;
|
||||
character: number;
|
||||
context: string;
|
||||
}
|
||||
export declare type FileLocation = {
|
||||
line: number;
|
||||
character: number;
|
||||
};
|
||||
export interface WebpackError {
|
||||
module?: any;
|
||||
file?: string;
|
||||
message: string;
|
||||
location?: FileLocation;
|
||||
loaderSource: string;
|
||||
}
|
||||
export interface WebpackModule {
|
||||
resource: string;
|
||||
errors: WebpackError[];
|
||||
buildMeta: {
|
||||
tsLoaderFileVersion: number;
|
||||
tsLoaderDefinitionFileVersions: string[];
|
||||
};
|
||||
}
|
||||
export declare type ResolveSync = (context: string | undefined, path: string, moduleName: string) => string;
|
||||
export interface WatchHost extends typescript.WatchCompilerHostOfFilesAndCompilerOptions<typescript.BuilderProgram> {
|
||||
invokeFileWatcher(fileName: string, eventKind: typescript.FileWatcherEventKind): void;
|
||||
invokeDirectoryWatcher(directory: string, fileAddedOrRemoved: string): void;
|
||||
updateRootFileNames(): void;
|
||||
}
|
||||
export interface TSInstance {
|
||||
compiler: typeof typescript;
|
||||
compilerOptions: typescript.CompilerOptions;
|
||||
/** Used for Vue for the most part */
|
||||
appendTsTsxSuffixesIfRequired: (filePath: string) => string;
|
||||
loaderOptions: LoaderOptions;
|
||||
/**
|
||||
* a cache of all the files
|
||||
*/
|
||||
files: TSFiles;
|
||||
/**
|
||||
* contains the modified files - cleared each time after-compile is called
|
||||
*/
|
||||
modifiedFiles?: TSFiles | null;
|
||||
/**
|
||||
* Paths to project references that are missing source maps.
|
||||
* Cleared each time after-compile is called. Used to dedupe
|
||||
* warnings about source maps during a single compilation.
|
||||
*/
|
||||
projectsMissingSourceMaps?: Set<string>;
|
||||
languageService?: typescript.LanguageService | null;
|
||||
version?: number;
|
||||
dependencyGraph: DependencyGraph;
|
||||
reverseDependencyGraph: ReverseDependencyGraph;
|
||||
filesWithErrors?: TSFiles;
|
||||
transformers: typescript.CustomTransformers;
|
||||
colors: Chalk;
|
||||
otherFiles: TSFiles;
|
||||
watchHost?: WatchHost;
|
||||
watchOfFilesAndCompilerOptions?: typescript.WatchOfFilesAndCompilerOptions<typescript.BuilderProgram>;
|
||||
program?: typescript.Program;
|
||||
hasUnaccountedModifiedFiles?: boolean;
|
||||
changedFilesList?: boolean;
|
||||
}
|
||||
export interface LoaderOptionsCache {
|
||||
[name: string]: WeakMap<LoaderOptions, LoaderOptions>;
|
||||
}
|
||||
export interface TSInstances {
|
||||
[name: string]: TSInstance;
|
||||
}
|
||||
export interface DependencyGraph {
|
||||
[file: string]: ResolvedModule[] | undefined;
|
||||
}
|
||||
export interface ReverseDependencyGraph {
|
||||
[file: string]: {
|
||||
[file: string]: boolean;
|
||||
} | undefined;
|
||||
}
|
||||
export declare type LogLevel = 'INFO' | 'WARN' | 'ERROR';
|
||||
export declare type ResolveModuleName = (moduleName: string, containingFile: string, compilerOptions: typescript.CompilerOptions, moduleResolutionHost: typescript.ModuleResolutionHost) => typescript.ResolvedModuleWithFailedLookupLocations;
|
||||
export declare type CustomResolveModuleName = (moduleName: string, containingFile: string, compilerOptions: typescript.CompilerOptions, moduleResolutionHost: typescript.ModuleResolutionHost, parentResolver: ResolveModuleName) => typescript.ResolvedModuleWithFailedLookupLocations;
|
||||
export declare type CustomResolveTypeReferenceDirective = (typeDirectiveName: string, containingFile: string, compilerOptions: typescript.CompilerOptions, moduleResolutionHost: typescript.ModuleResolutionHost, parentResolver: typeof typescript.resolveTypeReferenceDirective) => typescript.ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
|
||||
export interface LoaderOptions {
|
||||
silent: boolean;
|
||||
logLevel: LogLevel;
|
||||
logInfoToStdOut: boolean;
|
||||
instance: string;
|
||||
compiler: string;
|
||||
configFile: string;
|
||||
context: string;
|
||||
transpileOnly: boolean;
|
||||
ignoreDiagnostics: number[];
|
||||
reportFiles: string[];
|
||||
errorFormatter: (message: ErrorInfo, colors: Chalk) => string;
|
||||
onlyCompileBundledFiles: boolean;
|
||||
colors: boolean;
|
||||
compilerOptions: typescript.CompilerOptions;
|
||||
appendTsSuffixTo: RegExp[];
|
||||
appendTsxSuffixTo: RegExp[];
|
||||
happyPackMode: boolean;
|
||||
getCustomTransformers: string | ((program: typescript.Program) => typescript.CustomTransformers | undefined);
|
||||
experimentalWatchApi: boolean;
|
||||
allowTsInNodeModules: boolean;
|
||||
experimentalFileCaching: boolean;
|
||||
projectReferences: boolean;
|
||||
resolveModuleName: CustomResolveModuleName;
|
||||
resolveTypeReferenceDirective: CustomResolveTypeReferenceDirective;
|
||||
}
|
||||
export interface TSFile {
|
||||
text?: string;
|
||||
version: number;
|
||||
projectReference?: {
|
||||
/**
|
||||
* Undefined here means we’ve already checked and confirmed there is no
|
||||
* project reference for the file. Don’t bother checking again.
|
||||
*/
|
||||
project?: typescript.ResolvedProjectReference;
|
||||
outputFileName?: string;
|
||||
};
|
||||
}
|
||||
/** where key is filepath */
|
||||
export declare type TSFiles = Map<string, TSFile>;
|
||||
export interface ResolvedModule {
|
||||
originalFileName: string;
|
||||
resolvedFileName: string;
|
||||
resolvedModule?: ResolvedModule;
|
||||
isExternalLibraryImport?: boolean;
|
||||
}
|
||||
export declare type Severity = 'error' | 'warning';
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { Chalk } from 'chalk';
|
||||
import { LoaderOptions } from './interfaces';
|
||||
declare type LoggerFunc = (message: string) => void;
|
||||
export interface Logger {
|
||||
log: LoggerFunc;
|
||||
logInfo: LoggerFunc;
|
||||
logWarning: LoggerFunc;
|
||||
logError: LoggerFunc;
|
||||
}
|
||||
export declare enum LogLevel {
|
||||
INFO = 1,
|
||||
WARN = 2,
|
||||
ERROR = 3
|
||||
}
|
||||
export declare function makeLogger(loaderOptions: LoaderOptions, colors: Chalk): Logger;
|
||||
export {};
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import * as webpack from 'webpack';
|
||||
import { ResolveSync } from './interfaces';
|
||||
export declare function makeResolver(options: webpack.Configuration): ResolveSync;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import * as typescript from 'typescript';
|
||||
import * as webpack from 'webpack';
|
||||
import { TSInstance, WatchHost } from './interfaces';
|
||||
import * as logger from './logger';
|
||||
export declare type Action = () => void;
|
||||
export interface ServiceHostWhichMayBeCacheable {
|
||||
servicesHost: typescript.LanguageServiceHost;
|
||||
clearCache: Action | null;
|
||||
}
|
||||
/**
|
||||
* Create the TypeScript language service
|
||||
*/
|
||||
export declare function makeServicesHost(scriptRegex: RegExp, log: logger.Logger, loader: webpack.loader.LoaderContext, instance: TSInstance, enableFileCaching: boolean, projectReferences?: ReadonlyArray<typescript.ProjectReference>): ServiceHostWhichMayBeCacheable;
|
||||
/**
|
||||
* Create the TypeScript Watch host
|
||||
*/
|
||||
export declare function makeWatchHost(scriptRegex: RegExp, log: logger.Logger, loader: webpack.loader.LoaderContext, instance: TSInstance, projectReferences?: ReadonlyArray<typescript.ProjectReference>): WatchHost;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { Chalk } from 'chalk';
|
||||
import * as typescript from 'typescript';
|
||||
import * as webpack from 'webpack';
|
||||
import { DependencyGraph, LoaderOptions, ReverseDependencyGraph, TSInstance, WebpackError, WebpackModule } from './interfaces';
|
||||
/**
|
||||
* Take TypeScript errors, parse them and format to webpack errors
|
||||
* Optionally adds a file name
|
||||
*/
|
||||
export declare function formatErrors(diagnostics: ReadonlyArray<typescript.Diagnostic> | undefined, loaderOptions: LoaderOptions, colors: Chalk, compiler: typeof typescript, merge: {
|
||||
file?: string;
|
||||
module?: WebpackModule;
|
||||
}, context: string): WebpackError[];
|
||||
export declare function readFile(fileName: string, encoding?: string | undefined): string | undefined;
|
||||
export declare function makeError(message: string, file: string | undefined, location?: {
|
||||
line: number;
|
||||
character: number;
|
||||
}): WebpackError;
|
||||
export declare function appendSuffixIfMatch(patterns: RegExp[], filePath: string, suffix: string): string;
|
||||
export declare function appendSuffixesIfMatch(suffixDict: {
|
||||
[suffix: string]: RegExp[];
|
||||
}, filePath: string): string;
|
||||
export declare function unorderedRemoveItem<T>(array: T[], item: T): boolean;
|
||||
/**
|
||||
* Recursively collect all possible dependants of passed file
|
||||
*/
|
||||
export declare function collectAllDependants(reverseDependencyGraph: ReverseDependencyGraph, fileName: string, collected?: {
|
||||
[file: string]: boolean;
|
||||
}): string[];
|
||||
/**
|
||||
* Recursively collect all possible dependencies of passed file
|
||||
*/
|
||||
export declare function collectAllDependencies(dependencyGraph: DependencyGraph, filePath: string, collected?: {
|
||||
[file: string]: boolean;
|
||||
}): string[];
|
||||
export declare function arrify<T>(val: T | T[]): T[];
|
||||
export declare function ensureProgram(instance: TSInstance): typescript.Program | undefined;
|
||||
export declare function supportsProjectReferences(instance: TSInstance): true | undefined;
|
||||
export declare function isUsingProjectReferences(instance: TSInstance): boolean;
|
||||
/**
|
||||
* Gets the project reference for a file from the cache if it exists,
|
||||
* or gets it from TypeScript and caches it otherwise.
|
||||
*/
|
||||
export declare function getAndCacheProjectReference(filePath: string, instance: TSInstance): typescript.ResolvedProjectReference | undefined;
|
||||
export declare function validateSourceMapOncePerProject(instance: TSInstance, loader: webpack.loader.LoaderContext, jsFileName: string, project: typescript.ResolvedProjectReference): void;
|
||||
/**
|
||||
* Gets the output JS file path for an input file governed by a composite project.
|
||||
* Pulls from the cache if it exists; computes and caches the result otherwise.
|
||||
*/
|
||||
export declare function getAndCacheOutputJSFileName(inputFileName: string, projectReference: typescript.ResolvedProjectReference, instance: TSInstance): string;
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
import * as webpack from 'webpack';
|
||||
import { TSInstance } from './interfaces';
|
||||
/**
|
||||
* Make function which will manually update changed files
|
||||
*/
|
||||
export declare function makeWatchRun(instance: TSInstance): (compiler: webpack.Compiler, callback: () => void) => void;
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs = require("fs");
|
||||
const micromatch = require("micromatch");
|
||||
const path = require("path");
|
||||
const typescript = require("typescript");
|
||||
const constants = require("./constants");
|
||||
/**
|
||||
* The default error formatter.
|
||||
*/
|
||||
function defaultErrorFormatter(error, colors) {
|
||||
const messageColor = error.severity === 'warning' ? colors.bold.yellow : colors.bold.red;
|
||||
return (colors.grey('[tsl] ') +
|
||||
messageColor(error.severity.toUpperCase()) +
|
||||
(error.file === ''
|
||||
? ''
|
||||
: messageColor(' in ') +
|
||||
colors.bold.cyan(`${error.file}(${error.line},${error.character})`)) +
|
||||
constants.EOL +
|
||||
messageColor(` TS${error.code}: ${error.content}`));
|
||||
}
|
||||
/**
|
||||
* Take TypeScript errors, parse them and format to webpack errors
|
||||
* Optionally adds a file name
|
||||
*/
|
||||
function formatErrors(diagnostics, loaderOptions, colors, compiler, merge, context) {
|
||||
return diagnostics === undefined
|
||||
? []
|
||||
: diagnostics
|
||||
.filter(diagnostic => {
|
||||
if (loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) !== -1) {
|
||||
return false;
|
||||
}
|
||||
if (loaderOptions.reportFiles.length > 0 &&
|
||||
diagnostic.file !== undefined) {
|
||||
const relativeFileName = path.relative(context, diagnostic.file.fileName);
|
||||
const matchResult = micromatch([relativeFileName], loaderOptions.reportFiles);
|
||||
if (matchResult.length === 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map(diagnostic => {
|
||||
const file = diagnostic.file;
|
||||
const position = file === undefined
|
||||
? undefined
|
||||
: file.getLineAndCharacterOfPosition(diagnostic.start);
|
||||
const errorInfo = {
|
||||
code: diagnostic.code,
|
||||
severity: compiler.DiagnosticCategory[diagnostic.category].toLowerCase(),
|
||||
content: compiler.flattenDiagnosticMessageText(diagnostic.messageText, constants.EOL),
|
||||
file: file === undefined ? '' : path.normalize(file.fileName),
|
||||
line: position === undefined ? 0 : position.line + 1,
|
||||
character: position === undefined ? 0 : position.character + 1,
|
||||
context
|
||||
};
|
||||
const message = loaderOptions.errorFormatter === undefined
|
||||
? defaultErrorFormatter(errorInfo, colors)
|
||||
: loaderOptions.errorFormatter(errorInfo, colors);
|
||||
const error = makeError(message, merge.file === undefined ? errorInfo.file : merge.file, position === undefined
|
||||
? undefined
|
||||
: { line: errorInfo.line, character: errorInfo.character });
|
||||
return Object.assign(error, merge);
|
||||
});
|
||||
}
|
||||
exports.formatErrors = formatErrors;
|
||||
function readFile(fileName, encoding = 'utf8') {
|
||||
fileName = path.normalize(fileName);
|
||||
try {
|
||||
return fs.readFileSync(fileName, encoding);
|
||||
}
|
||||
catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
exports.readFile = readFile;
|
||||
function makeError(message, file, location) {
|
||||
return {
|
||||
message,
|
||||
location,
|
||||
file,
|
||||
loaderSource: 'ts-loader'
|
||||
};
|
||||
}
|
||||
exports.makeError = makeError;
|
||||
function appendSuffixIfMatch(patterns, filePath, suffix) {
|
||||
if (patterns.length > 0) {
|
||||
for (const regexp of patterns) {
|
||||
if (filePath.match(regexp) !== null) {
|
||||
return filePath + suffix;
|
||||
}
|
||||
}
|
||||
}
|
||||
return filePath;
|
||||
}
|
||||
exports.appendSuffixIfMatch = appendSuffixIfMatch;
|
||||
function appendSuffixesIfMatch(suffixDict, filePath) {
|
||||
let amendedPath = filePath;
|
||||
for (const suffix in suffixDict) {
|
||||
amendedPath = appendSuffixIfMatch(suffixDict[suffix], amendedPath, suffix);
|
||||
}
|
||||
return amendedPath;
|
||||
}
|
||||
exports.appendSuffixesIfMatch = appendSuffixesIfMatch;
|
||||
function unorderedRemoveItem(array, item) {
|
||||
for (let i = 0; i < array.length; i++) {
|
||||
if (array[i] === item) {
|
||||
// Fill in the "hole" left at `index`.
|
||||
array[i] = array[array.length - 1];
|
||||
array.pop();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
exports.unorderedRemoveItem = unorderedRemoveItem;
|
||||
/**
|
||||
* Recursively collect all possible dependants of passed file
|
||||
*/
|
||||
function collectAllDependants(reverseDependencyGraph, fileName, collected = {}) {
|
||||
const result = {};
|
||||
result[fileName] = true;
|
||||
collected[fileName] = true;
|
||||
const dependants = reverseDependencyGraph[fileName];
|
||||
if (dependants !== undefined) {
|
||||
Object.keys(dependants).forEach(dependantFileName => {
|
||||
if (!collected[dependantFileName]) {
|
||||
collectAllDependants(reverseDependencyGraph, dependantFileName, collected).forEach(fName => (result[fName] = true));
|
||||
}
|
||||
});
|
||||
}
|
||||
return Object.keys(result);
|
||||
}
|
||||
exports.collectAllDependants = collectAllDependants;
|
||||
/**
|
||||
* Recursively collect all possible dependencies of passed file
|
||||
*/
|
||||
function collectAllDependencies(dependencyGraph, filePath, collected = {}) {
|
||||
const result = {};
|
||||
result[filePath] = true;
|
||||
collected[filePath] = true;
|
||||
const directDependencies = dependencyGraph[filePath];
|
||||
if (directDependencies !== undefined) {
|
||||
directDependencies.forEach(dependencyModule => {
|
||||
if (!collected[dependencyModule.originalFileName]) {
|
||||
collectAllDependencies(dependencyGraph, dependencyModule.resolvedFileName, collected).forEach(depFilePath => (result[depFilePath] = true));
|
||||
}
|
||||
});
|
||||
}
|
||||
return Object.keys(result);
|
||||
}
|
||||
exports.collectAllDependencies = collectAllDependencies;
|
||||
function arrify(val) {
|
||||
if (val === null || val === undefined) {
|
||||
return [];
|
||||
}
|
||||
return Array.isArray(val) ? val : [val];
|
||||
}
|
||||
exports.arrify = arrify;
|
||||
function ensureProgram(instance) {
|
||||
if (instance && instance.watchHost) {
|
||||
if (instance.hasUnaccountedModifiedFiles) {
|
||||
if (instance.changedFilesList) {
|
||||
instance.watchHost.updateRootFileNames();
|
||||
}
|
||||
if (instance.watchOfFilesAndCompilerOptions) {
|
||||
instance.program = instance.watchOfFilesAndCompilerOptions
|
||||
.getProgram()
|
||||
.getProgram();
|
||||
}
|
||||
instance.hasUnaccountedModifiedFiles = false;
|
||||
}
|
||||
return instance.program;
|
||||
}
|
||||
if (instance.languageService) {
|
||||
return instance.languageService.getProgram();
|
||||
}
|
||||
return instance.program;
|
||||
}
|
||||
exports.ensureProgram = ensureProgram;
|
||||
function supportsProjectReferences(instance) {
|
||||
const program = ensureProgram(instance);
|
||||
return program && !!program.getProjectReferences;
|
||||
}
|
||||
exports.supportsProjectReferences = supportsProjectReferences;
|
||||
function isUsingProjectReferences(instance) {
|
||||
if (instance.loaderOptions.projectReferences &&
|
||||
supportsProjectReferences(instance)) {
|
||||
const program = ensureProgram(instance);
|
||||
return Boolean(program && program.getProjectReferences());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
exports.isUsingProjectReferences = isUsingProjectReferences;
|
||||
/**
|
||||
* Gets the project reference for a file from the cache if it exists,
|
||||
* or gets it from TypeScript and caches it otherwise.
|
||||
*/
|
||||
function getAndCacheProjectReference(filePath, instance) {
|
||||
const file = instance.files.get(filePath);
|
||||
if (file !== undefined && file.projectReference) {
|
||||
return file.projectReference.project;
|
||||
}
|
||||
const projectReference = getProjectReferenceForFile(filePath, instance);
|
||||
if (file !== undefined) {
|
||||
file.projectReference = { project: projectReference };
|
||||
}
|
||||
return projectReference;
|
||||
}
|
||||
exports.getAndCacheProjectReference = getAndCacheProjectReference;
|
||||
function getResolvedProjectReferences(program) {
|
||||
const getProjectReferences = program.getResolvedProjectReferences ||
|
||||
program.getProjectReferences;
|
||||
if (getProjectReferences) {
|
||||
return getProjectReferences();
|
||||
}
|
||||
return;
|
||||
}
|
||||
function getProjectReferenceForFile(filePath, instance) {
|
||||
if (isUsingProjectReferences(instance)) {
|
||||
const program = ensureProgram(instance);
|
||||
return (program &&
|
||||
getResolvedProjectReferences(program).find(ref => (ref &&
|
||||
ref.commandLine.fileNames.some(file => path.normalize(file) === filePath)) ||
|
||||
false));
|
||||
}
|
||||
return;
|
||||
}
|
||||
function validateSourceMapOncePerProject(instance, loader, jsFileName, project) {
|
||||
const { projectsMissingSourceMaps = new Set() } = instance;
|
||||
if (!projectsMissingSourceMaps.has(project.sourceFile.fileName)) {
|
||||
instance.projectsMissingSourceMaps = projectsMissingSourceMaps;
|
||||
projectsMissingSourceMaps.add(project.sourceFile.fileName);
|
||||
const mapFileName = jsFileName + '.map';
|
||||
if (!instance.compiler.sys.fileExists(mapFileName)) {
|
||||
const [relativeJSPath, relativeProjectConfigPath] = [
|
||||
path.relative(loader.rootContext, jsFileName),
|
||||
path.relative(loader.rootContext, project.sourceFile.fileName)
|
||||
];
|
||||
loader.emitWarning(new Error('Could not find source map file for referenced project output ' +
|
||||
`${relativeJSPath}. Ensure the 'sourceMap' compiler option ` +
|
||||
`is enabled in ${relativeProjectConfigPath} to ensure Webpack ` +
|
||||
'can map project references to the appropriate source files.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.validateSourceMapOncePerProject = validateSourceMapOncePerProject;
|
||||
/**
|
||||
* Gets the output JS file path for an input file governed by a composite project.
|
||||
* Pulls from the cache if it exists; computes and caches the result otherwise.
|
||||
*/
|
||||
function getAndCacheOutputJSFileName(inputFileName, projectReference, instance) {
|
||||
const file = instance.files.get(inputFileName);
|
||||
if (file && file.projectReference && file.projectReference.outputFileName) {
|
||||
return file.projectReference.outputFileName;
|
||||
}
|
||||
const outputFileName = getOutputJavaScriptFileName(inputFileName, projectReference);
|
||||
if (file !== undefined) {
|
||||
file.projectReference = file.projectReference || {
|
||||
project: projectReference
|
||||
};
|
||||
file.projectReference.outputFileName = outputFileName;
|
||||
}
|
||||
return outputFileName;
|
||||
}
|
||||
exports.getAndCacheOutputJSFileName = getAndCacheOutputJSFileName;
|
||||
// Adapted from https://github.com/Microsoft/TypeScript/blob/45101491c0b077c509b25830ef0ee5f85b293754/src/compiler/tsbuild.ts#L305
|
||||
function getOutputJavaScriptFileName(inputFileName, projectReference) {
|
||||
const { options } = projectReference.commandLine;
|
||||
const projectDirectory = options.rootDir || path.dirname(projectReference.sourceFile.fileName);
|
||||
const relativePath = path.relative(projectDirectory, inputFileName);
|
||||
const outputPath = path.resolve(options.outDir || projectDirectory, relativePath);
|
||||
const newExtension = constants.jsonRegex.test(inputFileName)
|
||||
? '.json'
|
||||
: constants.tsxRegex.test(inputFileName) &&
|
||||
options.jsx === typescript.JsxEmit.Preserve
|
||||
? '.jsx'
|
||||
: '.js';
|
||||
return outputPath.replace(constants.extensionRegex, newExtension);
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path = require("path");
|
||||
const constants = require("./constants");
|
||||
const utils_1 = require("./utils");
|
||||
/**
|
||||
* Make function which will manually update changed files
|
||||
*/
|
||||
function makeWatchRun(instance) {
|
||||
// Called Before starting compilation after watch
|
||||
const lastTimes = new Map();
|
||||
const startTime = 0;
|
||||
return (compiler, callback) => {
|
||||
if (null === instance.modifiedFiles) {
|
||||
instance.modifiedFiles = new Map();
|
||||
}
|
||||
// startTime = startTime || watching.startTime;
|
||||
const times = compiler.fileTimestamps;
|
||||
for (const [filePath, date] of times) {
|
||||
if (date > (lastTimes.get(filePath) || startTime) &&
|
||||
filePath.match(constants.tsTsxJsJsxRegex) !== null) {
|
||||
continue;
|
||||
}
|
||||
lastTimes.set(filePath, date);
|
||||
updateFile(instance, filePath);
|
||||
}
|
||||
// On watch update add all known dts files expect the ones in node_modules
|
||||
// (skip @types/* and modules with typings)
|
||||
for (const filePath of instance.files.keys()) {
|
||||
if (filePath.match(constants.dtsDtsxOrDtsDtsxMapRegex) !== null &&
|
||||
filePath.match(constants.nodeModules) === null) {
|
||||
updateFile(instance, filePath);
|
||||
}
|
||||
}
|
||||
callback();
|
||||
};
|
||||
}
|
||||
exports.makeWatchRun = makeWatchRun;
|
||||
function updateFile(instance, filePath) {
|
||||
const nFilePath = path.normalize(filePath);
|
||||
const file = instance.files.get(nFilePath) || instance.otherFiles.get(nFilePath);
|
||||
if (file !== undefined) {
|
||||
file.text = utils_1.readFile(nFilePath) || '';
|
||||
file.version++;
|
||||
instance.version++;
|
||||
instance.modifiedFiles.set(nFilePath, file);
|
||||
if (instance.watchHost !== undefined) {
|
||||
instance.watchHost.invokeFileWatcher(nFilePath, instance.compiler.FileWatcherEventKind.Changed);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
var loader = require('./dist');
|
||||
|
||||
module.exports = loader;
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
{
|
||||
"_from": "ts-loader@^5.3.3",
|
||||
"_id": "ts-loader@5.4.5",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-XYsjfnRQCBum9AMRZpk2rTYSVpdZBpZK+kDh0TeT3kxmQNBDVIeUjdPjY5RZry4eIAb8XHc4gYSUiUWPYvzSRw==",
|
||||
"_location": "/ts-loader",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "ts-loader@^5.3.3",
|
||||
"name": "ts-loader",
|
||||
"escapedName": "ts-loader",
|
||||
"rawSpec": "^5.3.3",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^5.3.3"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#DEV:/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/ts-loader/-/ts-loader-5.4.5.tgz",
|
||||
"_shasum": "a0c1f034b017a9344cef0961bfd97cc192492b8b",
|
||||
"_spec": "ts-loader@^5.3.3",
|
||||
"_where": "/home/daniel/development/repos/fw-vendor/rpclib",
|
||||
"author": {
|
||||
"name": "John Reilly",
|
||||
"email": "johnny_reilly@hotmail.com",
|
||||
"url": "https://blog.johnnyreilly.com"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/TypeStrong/ts-loader/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "John Reilly",
|
||||
"email": "johnny_reilly@hotmail.com",
|
||||
"url": "https://blog.johnnyreilly.com"
|
||||
},
|
||||
{
|
||||
"name": "James Brantly",
|
||||
"email": "james@jbrantly.com",
|
||||
"url": "http://www.jbrantly.com/"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"chalk": "^2.3.0",
|
||||
"enhanced-resolve": "^4.0.0",
|
||||
"loader-utils": "^1.0.2",
|
||||
"micromatch": "^3.1.4",
|
||||
"semver": "^5.0.1"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "TypeScript loader for webpack",
|
||||
"devDependencies": {
|
||||
"@types/micromatch": "^3.1.0",
|
||||
"@types/node": "*",
|
||||
"@types/semver": "^5.4.0",
|
||||
"@types/webpack": "^4.4.29",
|
||||
"babel": "^6.0.0",
|
||||
"babel-core": "^6.0.0",
|
||||
"babel-loader": "^7.0.0",
|
||||
"babel-polyfill": "^6.16.0",
|
||||
"babel-preset-es2015": "^6.0.0",
|
||||
"babel-preset-es2016": "^6.16.0",
|
||||
"babel-preset-react": "^6.0.0",
|
||||
"escape-string-regexp": "^1.0.3",
|
||||
"fs-extra": "^7.0.0",
|
||||
"glob": "^7.1.1",
|
||||
"html-webpack-plugin": "^3.2.0",
|
||||
"husky": "^1.0.0",
|
||||
"jasmine-core": "^3.0.0",
|
||||
"karma": "^3.0.0",
|
||||
"karma-chrome-launcher": "^2.2.0",
|
||||
"karma-jasmine": "^2.0.0",
|
||||
"karma-mocha-reporter": "^2.0.0",
|
||||
"karma-sourcemap-loader": "^0.3.6",
|
||||
"karma-webpack": "^4.0.0-rc.5",
|
||||
"lint-staged": "^7.0.0",
|
||||
"mkdirp": "^0.5.1",
|
||||
"mocha": "^5.0.0",
|
||||
"prettier": "^1.11.1",
|
||||
"rimraf": "^2.6.2",
|
||||
"tslint": "^5.11.0",
|
||||
"tslint-config-prettier": "^1.15.0",
|
||||
"typescript": "^3.1.1",
|
||||
"webpack": "^4.5.0",
|
||||
"webpack-cli": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.11.5"
|
||||
},
|
||||
"homepage": "https://github.com/TypeStrong/ts-loader",
|
||||
"husky": {
|
||||
"hooks": {
|
||||
"pre-commit": "lint-staged"
|
||||
}
|
||||
},
|
||||
"keywords": [
|
||||
"ts-loader",
|
||||
"typescript-loader",
|
||||
"webpack",
|
||||
"loader",
|
||||
"typescript",
|
||||
"ts"
|
||||
],
|
||||
"license": "MIT",
|
||||
"lint-staged": {
|
||||
"src/**/*.{ts,md}": [
|
||||
"prettier --write",
|
||||
"git add"
|
||||
]
|
||||
},
|
||||
"main": "index.js",
|
||||
"name": "ts-loader",
|
||||
"peerDependencies": {
|
||||
"typescript": "*"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/TypeStrong/ts-loader.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc --version && tsc --project \"./src\"",
|
||||
"comparison-tests": "tsc --project \"./test/comparison-tests\" && npm link ./test/comparison-tests/testLib && node test/comparison-tests/run-tests.js",
|
||||
"comparison-tests-generate": "node test/comparison-tests/stub-new-version.js",
|
||||
"docker:build": "docker build -t ts-loader .",
|
||||
"execution-tests": "node test/execution-tests/run-tests.js",
|
||||
"lint": "tslint --project \"./src\"",
|
||||
"postdocker:build": "docker run -it ts-loader yarn test",
|
||||
"test": "node test/run-tests.js"
|
||||
},
|
||||
"types": "dist/types/index.d.ts",
|
||||
"version": "5.4.5"
|
||||
}
|
||||
+5157
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user