Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

TypeScript loader for webpack

License

NotificationsYou must be signed in to change notification settings

TypeStrong/ts-loader

Repository files navigation

npm versionbuild and testDownloadsnode versioncode style: prettier


ts-loader

This is the TypeScript loader for webpack.

Installation ·Report Bug ·Request Feature

Table of Contents

Getting Started

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, includingwebpack --watch andwebpack-dev-server, or through anotherbuild system using theNode.js API.

Examples

We have a number of example setups to accommodate different workflows. Our examples can be foundhere.

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"ts-loader
  • I want the fastest compilation that's available. Usefork-ts-checker-webpack-plugin. It performs type checking in a separate process withts-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 thetranspileOnly: true option, but doing so leaves you without type checking andwill 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 thefork-ts-checker-webpack-plugin.It runs the type checker on a separate process, so your build remains fast thanks totranspileOnly: true but you still have the type checking.

If you'd like to see a simple setup take a look atour example.

Yarn Plug’n’Play

ts-loader supportsYarn Plug’n’Play. The recommended way to integrate is using thepnp-webpack-plugin.

Babel

ts-loader works very well in combination withbabel andbabel-loader. There is anexample of this in the officialTypeScript Samples.

Compatibility

  • TypeScript: 3.6.3+
  • webpack: 5.x+ (please usets-loader 8.x if you need webpack 4 support)
  • node: 12.x+

A full test suite runs each night (and on each pull request). It runs both on Linux and Windows, testingts-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 updatewebpack.config.js like so:

    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"],// Add support for TypeScripts fully qualified ESM imports.extensionAlias:{".js":[".js",".ts"],".cjs":[".cjs",".cts"],".mjs":[".mjs",".mts"]}},module:{rules:[// all files with a `.ts`, `.cts`, `.mts` or `.tsx` extension will be handled by `ts-loader`{test:/\.([cm]?ts|tsx)$/,loader:"ts-loader"}]}};
  2. Add atsconfig.json file. (The one below is super simple; but you can tweak this to your hearts desire)

    {"compilerOptions": {"sourceMap":true  }}

Thetsconfig.json file controlsTypeScript-related options so that your IDE, thetsc command, and this loader all share thesame 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 withts-loader and webpack.

First, forts-loader to producesourcemaps, you will need to set thetsconfig.json option as"sourceMap": true.

Second, you need to set thedevtool option in yourwebpack.config.js to support the type of sourcemaps you want. To make your choice have a read of thedevtool webpack docs. 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: 'eval-cheap-module-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 thatyou have defined therequire function in adeclaration file.

declarevarrequire:{<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 thewebpack documentation.

require("!style!css!./style.css");

The same basic process is required for code splitting. In this case, youimport modules you need but youdon't directly use them. Instead you require them atsplit points. Seethis example andthis example for more details.

TypeScript 2.4 provides support for ECMAScript's newimport() calls. These calls import a module and return a promise to that module. This is also supported in webpack - details on usage can be foundhere. Happy code splitting!

Declaration Files (.d.ts)

To output declaration files (.d.ts), you can set "declaration": true in your tsconfig and set "transpileOnly" to false.

If you use ts-loader with "transpileOnly": true along withfork-ts-checker-webpack-plugin, you will need to configure fork-ts-checker-webpack-plugin to output definition files, you can learn more on the plugin's documentation page:https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#typescript-options

To output a built .d.ts file, you can use theDeclarationBundlerPlugin in your webpack config.

Failing the build on TypeScript compilation error

The buildshould fail on TypeScript compilation errors as of webpack 2. If for some reason it does not, you can use thewebpack-fail-plugin.

For more background have a read ofthis issue.

baseUrl /paths module resolution

If you want to resolve modules according tobaseUrl andpaths in yourtsconfig.json then you can use thetsconfig-paths-webpack-plugin package. For details about this functionality, see themodule resolution documentation.

This feature requires webpack 2.1+ and TypeScript 2.0+. Use the config below or check thepackage for more information on usage.

constTsconfigPathsPlugin=require('tsconfig-paths-webpack-plugin');module.exports={  ...resolve:{plugins:[newTsconfigPathsPlugin({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 theoptions property in the webpack configuration:

module.exports={  ...module:{rules:[{test:/\.tsx?$/,use:[{loader:'ts-loader',options:{transpileOnly:true}}]}]}}

Loader Options

transpileOnly

TypeDefault Value
booleanfalse

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.transpileOnly willnot speed up compilation of project references.

It's advisable to usetranspileOnly alongside thefork-ts-checker-webpack-plugin to get full type checking again. To see what this looks like in practice then either take a look atour example.

Tip: When you add thefork-ts-checker-webpack-plugin to your webpack config, thetranspileOnly will default totrue, so you can skip that option.

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.ts1: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:

module.exports={  ...stats:{warningsFilter:/export.*wasnotfoundin/}}

happyPackMode

TypeDefault Value
booleanfalse

If you're usingHappyPack orthread-loader to parallelise your builds then you'll need to set this totrue. This implicitly sets*transpileOnly* totrue andWARNING! stops registeringall errors to webpack.

It's advisable to use this with thefork-ts-checker-webpack-plugin to get full type checking again.IMPORTANT: If you are using fork-ts-checker-webpack-plugin alongside HappyPack or thread-loader then ensure you set thesyntactic diagnostic option like so:

newForkTsCheckerWebpackPlugin({typescript:{diagnosticOptions:{semantic:true,syntactic:true,},},})

This will ensure that the plugin checks for both syntactic errors (egconst array = [{} {}];) and semantic errors (egconst x: number = '1';). By default the plugin only checks for semantic errors (as when used withts-loader intranspileOnly mode,ts-loader will still report syntactic errors).

Also, if you are usingthread-loader in watch mode, remember to setpoolTimeout: 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 ofts-loader - they exist to facilitate functionality such asYarn Plug’n’Play.

getCustomTransformers

Type
(program: Program, getProgram: () => Program) => { before?: TransformerFactory<SourceFile>[]; after?: TransformerFactory<SourceFile>[]; afterDeclarations?: TransformerFactory<SourceFile>[]; }

Provide custom transformers - only compatible with TypeScript 2.3+ (and 2.4 if usingtranspileOnly mode). For example usage take a look attypescript-plugin-styled-components or ourtest.

You can also pass a path string to locate a js module file which exports the function described above, this useful especially inhappyPackMode. (Because forked processes cannot serialize functions see more atrelated issue)

logInfoToStdOut

TypeDefault Value
booleanfalse

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

TypeDefault Value
stringwarn

Can beinfo,warn orerror 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

TypeDefault Value
booleanfalse

Iftrue, no console.log messages will be emitted. Note that most errormessages are emitted via webpack which is not affected by this flag.

ignoreDiagnostics

TypeDefault Value
number[][]

You can squelch certain TypeScript errors by specifying an array of diagnosticcodes to ignore.

reportFiles

TypeDefault Value
string[][]

Only report errors on files matching these glob patterns.

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

TypeDefault Value
string'typescript'

Allows use of TypeScript compilers other than the official one. Should beset to the NPM name of the compiler, egntypescript.

configFile

TypeDefault Value
string'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 thecontext option to avoid TypeScript issues (like TS18003).In this case theconfigFile should point to thetsconfig.json andcontext to the project root.

colors

TypeDefault Value
booleantrue

Iffalse, disables built-in colors in logger messages.

errorFormatter

TypeDefault Value
(message: ErrorInfo, colors: boolean) => stringundefined

By defaultts-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 theerrorFormatter option. Below is a template for a custom error formatter. Please note that thecolors parameter is an instance ofchalk which you can use to color your output. (This instance will respect thecolors option.)

functioncustomErrorFormatter(error,colors){constmessageColor=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:

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

TypeDefault Value
object{}

Allows overriding TypeScript options. Should be specified in the same formatas you would do for thecompilerOptions property in tsconfig.json.

instance

TypeDefault Value
stringTODO

Advanced option to force files to go through different instances of theTypeScript compiler. Can be used to force segregation between different partsof your code.

appendTsSuffixTo

TypeDefault Value
(RegExp | string)[][]

appendTsxSuffixTo

TypeDefault Value
(RegExp | string)[][]

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.If you're usingHappyPack orthread-loader withts-loader, you need use thestring type for the regular expressions, notRegExp object.

// change this:{appendTsSuffixTo:[/\.vue$/]}// to:{appendTsSuffixTo:['\\.vue$']}

This is useful for*.vuefile format for now. (Probably will benefit from the new single file format in the future.)

Example:

webpack.config.js:

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

<template><p>hello {{msg}}</p></template><script lang="ts">exportdefault {  data():Object {return {      msg:"world"    };  }};</script>

We can handle.tsx by quite similar way:

webpack.config.js:

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 (setjsx option topreserve to let babel handle jsx)

{"compilerOptions": {"jsx":"preserve"  }}

index.vue

<script lang="tsx">exportdefault {  functional:true,  render(h,c) {return (<div>Content</div>);  }}</script>

Or if you want to use only tsx, just use theappendTsxSuffixTo option only:

{test:/\.ts$/,loader:'ts-loader'}{test:/\.tsx$/,loader:'babel-loader!ts-loader',options:{appendTsxSuffixTo:[/\.vue$/]}}

onlyCompileBundledFiles

TypeDefault Value
booleanfalse

The default behavior ofts-loader is to act as a drop-in replacement for thetsc command,so it respects theinclude,files, andexclude options in yourtsconfig.json, loadingany files specified by those options. TheonlyCompileBundledFiles option modifies this behavior,loading only those files that are actually bundled by webpack, as well as any.d.ts files includedby thetsconfig.json settings..d.ts files are still included because they may be needed forcompilation without being explicitly imported, and therefore not picked up by webpack.

useCaseSensitiveFileNames

TypeDefault Value
booleandetermined by typescript based on platform

The default behavior ofts-loader is to act as a drop-in replacement for thetsc command,so it respects theuseCaseSensitiveFileNames set internally by typescript. TheuseCaseSensitiveFileNames option modifies this behavior,by changing the way in which ts-loader resolves file paths to compile. Setting this to true can have some performance benefits due to simplifying the file resolution codepath.

allowTsInNodeModules

TypeDefault Value
booleanfalse

By default,ts-loader will not compile.ts files innode_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 awhitelist - any modules you desire to import must be included inthe"files" or"include" block of your project'stsconfig.json.

See:microsoft/TypeScript#12358

// in webpack.config.js{test:/\.ts$/,loader:'ts-loader',options:{allowTsInNodeModules:true}}

And in yourtsconfig.json:

  {"include": ["node_modules/whitelisted_module.ts"    ],"files": ["node_modules/my_module/whitelisted_file.ts"    ]  }

context

TypeDefault Value
stringundefined

If set, will parse the TypeScript configuration file with givenabsolute path as base path.Per default the directory of the configuration file is used as base path. Relative paths in the configurationfile are resolved with respect to the base path when parsed. Optioncontext allows to set optionconfigFile to a path other than the project root (e.g. a NPM package), while the base path forts-loadercan remain the project root.

Keep in mind thatnot having atsconfig.json in your project root can cause different behaviour betweents-loader andtsc.When using editors likeVS Code it is advised to add atsconfig.json file to the root of the project and extend the config filereferenced in optionconfigFile. For more information pleaseread the PR thatis the base andread the PR that contributed this option.

webpack:

{loader:require.resolve('ts-loader'),options:{context:__dirname,configFile:require.resolve('ts-config-react-app')}}

Extendingtsconfig.json:

{"extends":"./node_modules/ts-config-react-app/index" }

Note that changes in the extending file while not be respected byts-loader. Its purpose is to satisfy the code editor.

experimentalFileCaching

TypeDefault Value
booleantrue

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 with example).In some cases it may produce performance degradation.

This flag enables caching for some FS-functions likefileExists,realpath anddirectoryExists for TypeScript compiler. Note that caches are cleared between compilations.

projectReferences

TypeDefault Value
booleanfalse

ts-loader has opt-in support forproject references. With this configuration option enabled,ts-loader will incrementally rebuild upstream projects the same waytsc --build does. Otherwise, source files in referenced projects will be treated as if they’re part of the root project.

In order to make use of this option your project needs to be correctly configured to build the project references and then to use them as part of the build. See theProject References Guide and the example code in the examples which can be foundhere.

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:

// for webpack 4plugins:[newwebpack.WatchIgnorePlugin([/\.js$/,/\.d\.[cm]?ts$/])],// for webpack 5plugins:[newwebpack.WatchIgnorePlugin({paths:[/\.js$/,/\.d\.[cm]ts$/]})],

It's worth noting that use of theLoaderOptionsPlugin isonly supposed to be a stopgap measure. You may want to look at removing it entirely.

Hot Module replacement

We do not support HMR as we did not yet work out a reliable way how to set it up.

If you want to givewebpack-dev-server HMR a try, follow the officialwebpack HMR guide, then tweak a few config options forts-loader:

  1. SettranspileOnly totrue (seetranspileOnly for config details and recommendations above).
  2. Inside your HMR acceptance callback function, maybe re-require the module that was replaced.

Contributing

This is your TypeScript loader! We want you to help make it even better. Please feel free to contribute; see thecontributor's guide to get started.

History

ts-loader was started byJames Brantly, since 2016John Reilly has been taking good care of it. If you're interested, you canread more about how that came to pass.

License

MIT License


[8]ページ先頭

©2009-2025 Movatter.jp