Coder Social home page Coder Social logo

awesome-typescript-loader's Introduction

TypeScript loader for Webpack

Join the chat at https://gitter.im/s-panferov/awesome-typescript-loader Build Status

See also:

  1. tsdoc.io — TypeScript documentation portal (backed by tygen).

Installation

npm install awesome-typescript-loader --save-dev

Performance issues

Please note that ATL works the same way as a TypeScript compiler as much as possible. So please be careful with your files/exclude/include sections.

ADVICE: Turn on useCache option.

ADVICE: Typically you want your files section to include only entry points.

ADVICE: The loader works faster if you use isolatedModules or forceIsolatedModules options.

ADVICE: The loader works faster if you will use reportFiles to restrict checking scope.

ADVICE: Use the loader together with hard-source-webpack-plugin

The world is changing, other solutions are evolving and ATL may work slower for some workloads. Feel free to try ts-loader with HappyPack or thread-loader and hard-source-webpack-plugin.

Differences between ts-loader

awesome-typescript-loader loader was created mostly to speed-up compilation in my own projects. Some of them are quite big and I wanted to have full control on how my files are compiled. There are two major points:

  1. atl has first-class integration with Babel and enables caching possibilities. This can be useful for those who use Typescript with Babel. When useBabel and useCache flags are enabled, typescript's emit will be transpiled with Babel and cached. So next time if source file (+environment) has the same checksum we can totally skip typescript's and babel's transpiling. This significantly reduces build time in this scenario.

  2. atl is able to fork type-checker and emitter to a separate process, which also speeds-up some development scenarios (e.g. react with react-hot-loader) So your webpack compilation will end earlier and you can explore compiled version in your browser while your files are typechecked.

Configuration

  1. Add .ts as a resolvable extension.
  2. Configure all files with a .ts extension to be handled by awesome-typescript-loader.

webpack.config.js

// `CheckerPlugin` is optional. Use it if you want async error reporting.
// We need this plugin to detect a `--watch` mode. It may be removed later
// after https://github.com/webpack/webpack/issues/3460 will be resolved.
const { CheckerPlugin } = require('awesome-typescript-loader')

module.exports = {

  // Currently we need to add '.ts' to the resolve.extensions array.
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.jsx']
  },

  // Source maps support ('inline-source-map' also works)
  devtool: 'source-map',

  // Add the loader for .ts files.
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader'
      }
    ]
  },
  plugins: [
      new CheckerPlugin()
  ]
};

After that, you will be able to build TypeScript files with webpack.

NodeJS versions

The loader supports NodeJS 4 and newer.

tsconfig.json

You can use the tsconfig.json file to configure your compiler and loader:

{
    "compilerOptions": {
        "noImplicitAny": true,
        "removeComments": true
    },
    "awesomeTypescriptLoaderOptions": {
        /* ... */
    }
}

Supported TypeScript

[email protected] aims to support only [email protected] and webpack@2x, if you need old compilers please use 1.x or 0.x versions.

Advanced path resolution in TypeScript 2.0

If you want to use new paths and baseUrl feature of TS 2.0 please include TsConfigPathsPlugin. This feature is available only for [email protected].

const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { configFileName, compiler } */)
    ]
}

Loader options

silent (boolean) (default=false)

No logging from the checker. Please note that this option disables async error reporting because this option bans console.log() usage.

compiler (string) (default='typescript')

Allows use of TypeScript compilers other than the official one. Must be set to the NPM name of the compiler, e.g. ntypescript or the path to a package folder. Note that the compiler must be installed in your project. You can also use nightly versions.

useTranspileModule (boolean) (default=false)*

Use fast transpileModule emit mode. Disables automatically when you set compilerOption declaration: true (reference).

instance (string) (default='at-loader')

Allows the use of several TypeScript compilers with different settings in one app. Override instance to initialize another instance.

configFileName (string) (default='tsconfig.json')

Specifies the path to a TS config file. This is useful when you have multiple config files. This setting is useless inside a TS config file.

transpileOnly (boolean)

Use this setting to disable type checking, enabling this will nullify the CheckerPlugin usage in your webpack configuration.

errorsAsWarnings (boolean)

Emit all typescript errors as warnings.

forceIsolatedModules (boolean)

Use this setting to disable dependent module recompilation.

ignoreDiagnostics (number[]) (default=[])

You can squelch certain TypeScript errors by specifying an array of diagnostic codes to ignore. For example, you can transpile stage 1 properties from *.js using "ignoreDiagnostics": [8014].

useBabel (boolean) (default=false)

Invoke Babel to transpile files. Useful with ES6 target. Please see useCache option which can improve warm-up time.

If you're using babelOptions, anything in .babelrc will take precedence. This breaks expected usage for scenarios where you need two sets of Babel configs (example: one for Webpack, one for your build tools).

You may want to "babelrc": false to disable .babelrc if you don't want it:

{
    "useBabel": true,
    "babelOptions": {
        "babelrc": false, /* Important line */
        "presets": [
            ["@babel/preset-env", { "targets": "last 2 versions, ie 11", "modules": false }]
        ]
    },
    "babelCore": "@babel/core", // needed for Babel v7
}

babelCore (string) (default=undefined)

Override the path used to find babel-core. Useful if node_modules is installed in a non-standard place or webpack is being invoked from a directory not at the root of the project.

For Babel 7, this should be set to "@babel/core".

babelOptions (object) (default=null)

Use this option to pass some options to Babel (e.g. presets). Please note that .babelrc file is more universal way to do this.

useCache (boolean) (default=false)

Use internal file cache. This is useful with Babel, when processing takes a long time to complete. Improves warm-up time.

usePrecompiledFiles (boolean) (default=false)

Use pre-compiled files if any. Files must be named as {filename}.js and {filename}.map.

cacheDirectory (string) (default='.awcache')

Directory where cache is stored.

reportFiles (string[])

Specify globs to report file diagnostics. ALL OTHER ERRORS WILL NOT BE REPORTED. Example:

reportFiles: [
    "src/**/*.{ts,tsx}"
]

getCustomTransformers (string | ((program: ts.Program) => ts.CustomTransformers | undefined)) (default=undefined)

Provide custom transformers, TypeScript 2.4.1+. Example:

const styledComponentsTransformer = require('typescript-plugin-styled-components').default;
const keysTransformer = require('ts-transformer-keys/transformer').default;

// ...
rules: [
    {
        test: /\.tsx?$/,
        loader: 'awesome-typescript-loader',
        options: {
            // ... other loader's options
            getCustomTransformers: program => ({
                before: [
                    styledComponentsTransformer(),
                    keysTransformer(program)
                ]
            })
        }
    }
]

Compiler options

You can pass compiler options inside the loader query string or in a TS config file.

awesome-typescript-loader's People

Contributors

1999 avatar abergs avatar amilajack avatar andreasonny83 avatar argonalex avatar astorije avatar asvetliakov avatar awk34 avatar babakmn avatar benelliottgsa avatar brianmanden avatar christiantinauer avatar cspotcode avatar danielfallon avatar davidmiani avatar defaude avatar domoritz avatar frederickfogerty avatar gfx avatar hackerrdave avatar karabur avatar layfonweller avatar mindlink-luke avatar onigoetz avatar s-panferov avatar sheetalkamat avatar sod avatar stevenross avatar texastoland avatar zspecza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

awesome-typescript-loader's Issues

Impossible to import class and extend it

I must be dense cause I'm trying to do something that I thought was simple but no matter how I do it I can't get it to compile:

app.ts

import AppController from 'AppController'

var app = new AppController();

AppController.ts

import AbstractController from 'AbstractController'

export default class AppController extends AbstractController {
  constructor() {
    super();
    console.log(this.name);
  }
}

AbstractController.ts

export default class AbstractController {
  name = 'test';
}

If I try this I get Cannot resolve module 'AppController' in /resources/assets/ts. I pretty much get an error no matter what I try:

With extension

import AppController from 'AppController.ts =>

ERROR in ./resources/assets/ts/app.ts
Module build failed: Cannot resolve module 'AppController.ts' in /webpack-typescript
    Required in /webpack-typescript/app.ts

Path and extension

import AppController from './AppController.ts' =>

ERROR in /webpack-typescript/AppController.ts:1:31
Cannot find external module './AbstractController.ts'.

ERROR in /webpack-typescript/AppController.ts:5:8
'super' can only be referenced in a derived class.

Same with require

import AppController = require('AppController'); =>

ERROR in ./resources/assets/ts/app.ts
Module build failed: Cannot resolve module 'AppController' in /webpack-typescript
    Required in /webpack-typescript/app.ts

import AppController = require('AppController.ts'); =>

ERROR in ./resources/assets/ts/app.ts
Module build failed: Cannot resolve module 'AppController.ts' in /webpack-typescript
    Required in /webpack-typescript/app.ts

import AppController = require('./AppController.ts'); =>

ERROR in /webpack-typescript/AppController.ts:1:36
Cannot find external module './AbstractController.ts'.

ERROR in /webpack-typescript/AppController.ts:5:8
'super' can only be referenced in a derived class.

ERROR in /webpack-typescript/AppController.ts:7:25
Property 'name' does not exist on type 'AppController'.

ERROR in /webpack-typescript/app.ts:1:31
Cannot find external module './AppController.ts'.

import AppController = require('./AppController'); =>

ERROR in ./resources/assets/ts/app.ts
Module not found: Error: Cannot resolve 'file' or 'directory' ./AppController in /webpack-typescript
 @ ./resources/assets/ts/app.ts 1:20-46

ERROR in /webpack-typescript/AppController.ts:1:36
Cannot find external module './AbstractController.ts'.

ERROR in /webpack-typescript/AppController.ts:5:8
'super' can only be referenced in a derived class.

ERROR in /webpack-typescript/AppController.ts:7:25
Property 'name' does not exist on type 'AppController'.

ERROR in /webpack-typescript/app.ts:4:8
Cannot use 'new' with an expression whose type lacks a call or construct signature.

Is there some combination that I missed or something? How are you supposed to use this loader for imports? Going kind of crazy over here

Unable to import node_modules

Hi,

I've given your plugin a try and managed to use the new es6 import syntax to import other source files and use webpack to bundle it. This loads without issue and has nice sourcemap support.

The problem came up when I tried to bring in a new module. A simple example would be uuid.

So the steps are as follows:

  • npm install uuid
  • fetch the d.ts file from definitely typed and a reference to it to my index.ts file (as an example) typescript then determines that you can import this e.g. import * as uuid from 'uuid';
  • call the imported file and log to the console (basic example).

It should be really simple but just doesn't work. It complains that it cannot find the module. I've tried adding moduleDirectories to the resolve part of the config and specifying the full path to the node_modules folder and even tried defining resolveLoader with modulesDirectories (because another complaint is it can't resolve source-map-loader.

Is it possible to add an extra example that has a packages.json that brings in uuid and then references it using the new es6 syntax (i also tried require)?

Thanks!

Cannot load module in "multiple entry points" mode

Typescript 'external module' can not be loaded in 'multiple entry points' mode.
My config is below;

module.exports = {
  context: path.join(__dirname, '/src'),
  resolve: { extensions: ['', 'ts'] },
  watch: false,
  module: {
    loaders: [{
      test: /\.ts$/,
      exclude: /node_modules/,
      loader: 'awesome-typescript-loader'
    }]
  },
  entry: {
    app1: './app1/app1.ts',
    app2: './app2/app2.ts'
  },
  output: {
    filename: '[name].js'
  }
}

and my gulpfile is below;

var gulp = require('gulp');
var webpack = require('webpack-stream');
var path = require('path');

var sources = [
  'src/app1/app1.ts',
  'src/app2/app2.ts'
];

var option = require('./webpack.config');

gulp.task('build', function() {
  return gulp.src(sources)
    .pipe(webpack(option))
    .pipe(gulp.dest('dist'));
});

gulp.task('default', ['build']);

my project structure is;

gulpfile.js
src
    app1
        app1.ts
        sub1.ts
    app2
        app2.ts
        sub2.ts
dist

app1.ts;

import { sub } from './sub1';
sub('Hello');

sub1.ts;

export function sub(msg: string): void {
  console.log(msg + ' from sub1');
}

and output in console is below;

c:\dev\tmp>gulp
[18:08:21] Using gulpfile c:\dev\tmp\gulpfile.js
[18:08:21] Starting 'build'...
[18:08:24] Version: webpack 1.12.4
  Asset     Size  Chunks             Chunk Names
app1.js  1.63 kB       0  [emitted]  app1
app2.js  1.66 kB       1  [emitted]  app2

ERROR in ./src/app2/app2.ts
Module not found: Error: Cannot resolve 'file' or 'directory' ./sub2 in c:\dev\tmp\src\app2
 @ ./src/app2/app2.ts 1:13-30

ERROR in ./src/app1/app1.ts
Module not found: Error: Cannot resolve 'file' or 'directory' ./sub1 in c:\dev\tmp\src\app1
 @ ./src/app1/app1.ts 1:13-30
[18:08:24] Finished 'build' after 2.89 s
[18:08:24] Starting 'default'...
[18:08:24] Finished 'default' after 58 μs

I acturelly know that a possible solutions is using shama/vinyl-named, but I dont want to use this as much as possible.

Does not work with jsx-typescript

Hi, following the instructions in the README I installed jsx-typescript and set
loader: 'awesome-typescript-loader?compiler=jsx-typescript'

But webpack then produces the following stack trace:

ERROR in ./index.ts
Module build failed: TypeError: Cannot call method 'hasOwnProperty' of undefined
    at visit (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:187:42)
    at visitNode (c:\Users\banana\Documents\code\cc\node_modules\jsx-typescript\bin\typescriptServices.js:3986:20)
    at Object.forEachChild (c:\Users\banana\Documents\code\cc\node_modules\jsx-typescript\bin\typescriptServices.js:4145:95)
    at visit (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:199:22)
    at visitEachNode (c:\Users\banana\Documents\code\cc\node_modules\jsx-typescript\bin\typescriptServices.js:3997:30)
    at Object.forEachChild (c:\Users\banana\Documents\code\cc\node_modules\jsx-typescript\bin\typescriptServices.js:4094:24)
    at visit (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:199:22)
    at State.findImportDeclarations (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:201:9)
    at State.checkDependenciesInternal (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:155:33)
    at c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\dist\host.js:147:46
    at tryCatcher (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\util.js:24:31)
    at Promise._settlePromiseFromHandler (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:454:31)
    at Promise._settlePromiseAt (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:530:18)
    at Promise._settlePromises (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:646:14)
    at Async._drainQueue (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:175:16)
    at Async._drainQueues (c:\Users\banana\Documents\code\cc\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:185:10)

incremental compilation breaks

While developing an angular application with typescript I often get the following error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module abcApp due to: Error: [ng:areq] Argument 'directiveFactory' is required

When I stop my build task and rebuild everything again it works fine again. Also I cannot really reproduce the error, it happens in 8/10 cases, but sometimes I undo things, build incrementally and then redo the same things, build incremently again, sometimes it breaks, sometimes it doesn't. I don't have the error using ts-loader package.

Can I somehow disable the incremental compilation and always do a full compilation?

Cannot read property 'default' of undefined: if style/css loaders used

My config: https://github.com/develar/cloud-intellij/blob/0aec6770cf1996ba970c2f58dc8d7e8791c2ab09/web-client/webpack.config.js

Works fine if ExtractTextPlugin/style-loader are not used.

        var instance = compilation.compiler._tsInstances[instanceName];
                                                        ^
TypeError: Cannot read property 'default' of undefined
    at Tapable.<anonymous> (/Users/develar/Documents/cloud-intellij/web-client/node_modules/awesome-typescript-loader/dist/index.js:64:57)
    at Tapable.next (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:69:14)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/CachePlugin.js:40:4)
    at Tapable.applyPluginsAsync (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compiler.js:398:9)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:561:13)
    at Tapable.applyPluginsAsync (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:556:10)
    at Tapable.applyPluginsAsync (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:551:9)
    at Tapable.applyPluginsAsync (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:547:8)
    at Tapable.applyPluginsAsync (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Tapable.seal (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:511:7)
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compiler.js:395:15)
    at /usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/tapable/lib/Tapable.js:103:11
    at Tapable.<anonymous> (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:437:10)
    at /usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:409:12
    at /usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/lib/Compilation.js:324:10
    at done (/usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/async/lib/async.js:132:19)
    at /usr/local/lib/node_modules/webpack-dev-server/node_modules/webpack/node_modules/async/lib/async.js:32:16
    at process._tickCallback (node.js:355:11)```

watch webpack -w dont work

I use external modules import foo from './foo';

var path = require('path');
var webpack = require('webpack');
module.exports = {
    context: path.join(__dirname, './'),
    entry: './index.ts',
    output: {
        path: './dist/',
        filename: 'index.js'
    },

    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'awesome-typescript-loader?module=commonjs',
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx', '.ts']
    },
    devtool: 'inline-source-map',
};

require signature is incorrect

The current require signature is the following:

interface WebpackRequire {
    (id: string): any;
    ensure(ids: string[], callback: WebpackRequireEnsureCallback): void;
}

But this doesn't support AMD imports as documented here.

Error with loading modules in that are aliases

I'm using the latest awesome-typescript-loader and using aliases to shorten the import paths. My tsconfig is:

{
    "compilerOptions": {
        "noImplicitAny": false,
        "removeComments": false,
        "preserveConstEnums": true,
        "sourceMap": true,
        "noEmitOnError": true,
        "jsx": "react",
        "target": "es6"
    },
    "exclude": [
        "node_modules",
        "dist",
        "dev-server",
        "testHelpers"
    ],
    "files": [
        "typings/typings.d.ts"
    ]
}

I'm seeing the following error:

ERROR in ./src/app/services/connectivity.ts
Module not found: Error: Cannot resolve 'file' or 'directory' C:\source\project/lib/messaging/messaging in C:\source\projectsrc\app\services
 @ ./src/app/services/connectivity.ts 7:29-63

didn't work together with ts-jsx-loader

I just installed webpack because I would like jsx support with typescript.
Your plugin worked for making js bundles from TS, but adding !ts-jsx-loader didn't seem to do much.

        { test: /\.ts$/, loader: 'awesome-typescript-loader!ts-jsx-loader' }

When I switched to ts-loader it worked and the jsx got replaced:

        { test: /\.ts$/, loader: 'ts-loader!ts-jsx-loader' } 

This plugin do seem to give a bit more options than ts-loader, so it would be nice if it would work together with ts-jsx-loader

Using Handlebars with this loader

Hi, I'm using Webpack inside Gulp with two loaders: this one and handlebars-loader. Having the following webpack configuration...

    webpack({
        entry: './src/main.ts',
        output: {
            path: 'dist',
            filename: 'app.js'
        },
        resolve: {
            extensions: ['', '.hbs', '.ts', '.webpack.js', '.web.js', '.js']
        },
        module: {
            loaders: [
                {
                    test: /\.hbs$/,
                    exclude: /node_modules/,
                    loader: 'handlebars-loader'
                },
                {
                    test: /\.ts$/,
                    exclude: /node_modules/,
                    loader: 'awesome-typescript-loader?compiler=ntypescript&emitRequireType=false&library=es6&module=commonjs'
                }
            ]
        },
        plugins: plugins,
        devtool: '#source-map'
    }, function (err, stats) {
        // Some error handling logic
    });

... I'm facing the following errors while building 100% Typescript code:

ERROR in
File 'path/to/src/templates/myTemplate.hbs' has unsupported extension. The only supported extensions are '.tsx', '.ts', '.d.ts'.

ERROR in path/to/src/views/myView.ts:3:19
Cannot find module '../templates/myTemplate.hbs'.

Any idea how to fix this? What I tried:

  • My Handlebars templates are imported in myView.ts class like the following:
import myTemplate from '../templates/myTemplate.hbs';

// And somewhere later in the code I render this template:
myTemplate(context);
  • I installed d.ts files for all libraries except Handlebars (as I'm using handlebars loader) using tsd command and attached ./typings/tsd.d.ts to main.ts
  • Tried to add definitions for each view as described on the page

Incompatible to Typescript 1.6+

Any plans on supporting the latest Typescript 1.6 and up? Currently the loader cannot find the helpers due a path change, however fixing that myself only leads to further problems with the API such as ".text is undefined", or is this a problem on my end?

Cannot use node.d.ts reference file.

I tried to get your loader working, but I constantly get errors.

I am using awesome typescript loader at Version 0.3.0-rc.1 and webpack 1.8.9

This is my webpack.config.js:

module.exports = {
    entry: './ui/index.ts',
    output: {
        path: __dirname + '/build-ui',
        filename: 'app.js',
        publicPath: 'http://localhost:8090/assets'
    },
    module: {
        loaders: [
            {
                test: /\.jsx$/,
                loader: 'jsx-loader?insertPragma=React.DOM&harmony'
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader"
            },
            {
                test: /\.scss$/,
                loader: "style-loader!css-loader!sass-loader"
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url-loader?limit=8192'
            },
            {
                test: /\.ts$/,
                loader: 'awesome-typescript-loader'
            }
        ]
    },
    resolve: {
        extensions: ['', '.js', '.jsx', '.ts']
    }
};

When I run the webpack dev server and my index.ts looks like this:

alert('hello');

It states the following error:

ERROR in ./ui/index.ts
/Users/..../typings/node/node.d.ts:29:12 
Subsequent variable declarations must have the same type.  Variable 'require' must be of type 'WebpackRequire', but here has type '{ (id: string): any; resolve(id: string): string; cache: any; extensions: any; main: any; }'.

Same when I put in the reference path.

When I try to import the React.js via import React = require('react'); it states:

ERROR in ./ui/index.ts
Module build failed: Cannot resolve module 'child_process' in /..../typings/node
    Required in /..../typings/node/node.d.ts

I copied the node.d.ts file from your repo, still no luck. Any suggestions?

Error when using .tsx files

Please forgive me if I'm missing something obvious here:

main.ts:

/// <reference path='..\typings/react/react.d.ts' />
import React = require('react');
import temp = require('./components/uitest');
React.render(React.createElement(temp), document.getElementById('content'));

components\uitest.tsx:

/// <reference path="../../typings/react/react.d.ts" />
import * as React from 'react';
class MyComponent extends React.Component<any, any>
{
    render() {
        return <div>asdf</div>;
    }
}
export = MyComponent;

tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "listFiles": true,
        "jsx": "react"
    },
    "awesomeTypescriptLoaderOptions": {
        "compiler": "ntypescript"
    }
}

webpack.config.js:

var path = require('path');
module.exports = {
    entry: path.resolve(__dirname, 'app/main.ts'),
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js',
    },
    resolve: {
        extensions: ['', '.webpack.js', '.web.js', '.tsx',  '.ts', '.js']
    },
    module: {
        loaders: [
            {
                test: /\.ts(x?)$/,
                loader: 'awesome-typescript-loader'
            }
        ]
    }
};

Output from npm run build which simply calls webpack:

C:\MyProject\Reactor\Reactor>npm run build

> [email protected] build C:\MyProject\Reactor\Reactor
> webpack

Hash: 04f068e1dbdc71d85fd4
Version: webpack 1.10.1
Time: 1654ms
    Asset    Size  Chunks             Chunk Names
bundle.js  635 kB       0  [emitted]  main
    + 158 hidden modules

ERROR in ./app/components/uitest.tsx
Module build failed: Error: File C:/MyProject/Reactor/Reactor/app/components/uitest.tsx was not found in program
    at State.emit (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\dist\host.js:101:23)
    at C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\dist\index.js:208:22
    at tryCatcher (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\util.js:26:23)
    at Promise._settlePromiseFromHandler (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promis
e.js:489:31)
    at Promise._settlePromiseAt (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:565:
18)
    at Async._drainQueue (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:128:12)
    at Async._drainQueues (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:133:10)
    at Async.drainQueues (C:\MyProject\Reactor\Reactor\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:15:14)
    at process._tickCallback (node.js:415:13)
 @ ./app/main.ts 3:11-41

ERROR in
File 'C:/MyProject/Reactor/Reactor/app/components/uitest.tsx' must have extension '.ts' or '.d.ts'.

ERROR in C:/MyProject/Reactor/Reactor/app/main.ts:5:22
Cannot find external module './components/uitest'.

If I simply run ntsc it compiles correctly without issue, FWIW

Babel not found

Hi

I'm trying to use babel but even if I install it into my directory I keep receiveing:

Babel compiler cannot be found, please add it to your package.json file:
    npm install --save-dev babel

It definietlly exists in my package.json and is correctly installed.

Changes to separate the checker into another process causes issues with Gulp and Webpack

I am using Gulp with webpack. To signal that the webpack is done, it calls the callback method. It seems that the changes related to calling the checker in a separate process is causing webpack to call the callback method multiple times. This in turn causes the error "Error: task completion callback called too many times."

The task looks like:

gulp.task('webpack:production', function(callback) {
webpack(config, function(err, stats) {
logger(err, stats);
callback()
})
});

Suppress some diagnostics

I get the following output at the end of webpack build

ERROR in [default]
File 'src/layouts/application/AppLayout.hbs' has unsupported extension. The only supported extensions are '.ts', '.tsx', '.d.ts'.

ERROR in [default] src/app.ts:2:22
Cannot find module './layouts/application/AppLayout.ts'.

ERROR in [default] src/index.ts:3:16
Cannot find module './app.ts'.

ERROR in [default] src/layouts/application/AppLayout.ts:4:26
Cannot find module './AppLayout.hbs'.

All files actually have been successfully imported by webpack, but during typescript compilation it doesn't know about it and report errors.

Now it always written in console output and distracts from real errors. It would be nice to have ability to disable errors by its code.

These errors has following codes
TS2307 - Cannot find module
TS6054 -File has unsupported extension.

Errors not emptied on watch

Hello

I'm trying to setup a webpack workflow and am using that loader.
However, when running the webpack-dev-server errors accumulate in between runs ie on every filesave the same error gets pushed to an array I presume and I end up with one error for each time I saved the file.
Any way to cleanup the array or do some dedup?

WebpackDevServer doesn't work with awesome-typescript-loader, ExtractTextPlugin, and sass-loader

Using the dev server with awesome-typescript-loader, ExtractTextPlugin, and sass-loader results in a callback(): The callback was already called error. Not sure exactly what the issue is, but the issue is only triggered when all three plugins / loaders are present.

Related issues here:
webpack-contrib/extract-text-webpack-plugin#88
webpack-contrib/sass-loader#125

Complete repro here:
https://github.com/fongandrew/webpack-extract-sass-test/tree/master

Error after migration to 0.14.0 and typescript 1.6.2

After migration to [email protected] and [email protected] I'm getting this error:

ERROR in [default] C:/Users/tester/Desktop/testing/test/src/app.tsx:4:28 Cannot find module './view/popup/PopupNames'.

my config:

 { 
    entry: {
        app: ["./src/app.tsx"],
    },
    resolve: {
        extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    output: {
        path: path.join(__dirname, 'bin'),
        filename: '[name].bundle.js',
        publicPath: '/bin/'
    },
    module: {
        loaders: [
            {
                test: /\.tsx?$/,
                loaders: ['awesome-typescript-loader'],
                include: [path.resolve(__dirname, "src")]
            },
            {
                test: /\.json?$/,
                loaders: ['json-loader']
            }
        ]
    }

};

tsconfig:

  "compilerOptions": {
    "target": "es6",
    "sourceMap": true,
    "jsx": "react",
    "experimentalDecorators": true,
    "experimentalAsyncFunctions": true
  },
  "awesomeTypescriptLoaderOptions": {
    "useBabel": true,
    "useCache": true
  },
  "files": [
  "./src/app.tsx", "./typings/bundle-tsd.d.ts"
  ]
}

Cannot find module with transitive references

Hi there,
I created this issue for yeoman gulp-angular generator, which uses awesome-typescript-loader:
Swiip/generator-gulp-angular#846

And I'm having two issues here:

  1. The imports (import .. from ..;) don't work on Windows at all with TypeScript 1.6.*
  2. Transitive imports don't work on Windows not even with TypeScript 1.5.*

Detailed description can be seen in the link. I've seen other issues like this here but don't know what's the current status of them.
Thanks very much. Appreciate your work.
Lukas

are resolve.alias options supported?

hello!
to avoid messy relative references with many "../" parts to other classes I tried to use the alias feature of webpack but it seems to be incompatible with the loader.

so my structure looks like this

src/
  common/
    lib/
      util/
        constants.ts     
  ui-admin/
    app.ts

and my webpack config contains the following config for resolve:

resolve.alias:{
  common: "/src/common/lib" 
}

in app.ts I try to load the class Constant from constants.ts as follows:

import {Constants} from "common/util/constants";

but when compiling the files I get

  [14] ./src/common/lib/util/constants.ts 629 bytes {0} [built]

ERROR in _PATH_TO_PROJECT_/src/ui-admin/app.ts:22:24
Cannot find module 'common/util/constants'.

is the alias function not supported at all ? our could you please provide a small example how to use it correctly in combination with typescript?! :)

Version: v0.8.0-rc.0

Error thrown in alias example

I'm trying to figure out the source of this error. I git cloned your repo, npm installed in root directory, npm installed in examples/alias, installed webpack globally, npm installed "extract-text-webpack-plugin", then ran "webpack".

It seems to output the assets correctly but I get an error for whatever reason:

Hash: 7f7d83ef6470f948d29f
Version: webpack 1.11.0
Time: 965ms
         Asset     Size  Chunks             Chunk Names
    ./index.js  2.02 kB       0  [emitted]  index
./index.js.map  1.96 kB       0  [emitted]  index
   [0] multi index 28 bytes {0} [built]
   [1] ./index.ts 128 bytes {0} [built]
   [2] ./src/common/lib/util/constants.ts 198 bytes {0} [built]

ERROR in /Users/rich/Sites/awesome-typescript-loader/examples/alias/index.ts:1:26 
Cannot find module 'common/util/constants'.

Doesn't generate inline source maps

When I try to run with the following tsconfig.json:
"compilerOptions": {
"module": "commonjs",
"inlineSourceMap": true,
"inlineSources": false,
"sourceMap": false
},
I get

ERROR in ./test/HelloWorldSpec.ts
Module build failed: SyntaxError: Unexpected token u
    at Object.parse (native)
    at transform (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\dist\index.js:378:40)
    at c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\dist\index.js:407:24
    at tryCatcher (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\util.js:26:23)
    at Promise._settlePromiseFromHandler (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:507:31)
    at Promise._settlePromiseAt (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\promise.js:581:18)
    at Async._drainQueue (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:128:12)
    at Async._drainQueues (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:133:10)
    at Immediate.Async.drainQueues [as _onImmediate] (c:\Users\m.huber\_Projects\HelloWorldWebpack\node_modules\awesome-typescript-loader\node_modules\bluebird\js\main\async.js:15:14)
    at processImmediate [as _immediateCallback] (timers.js:367:17)

Turning inlinesourcemaps off and sourcemaps on works.
How can I get InlineSource Maps with this loader?

And sourceMaps don't seem to work with the source map loader at all.
https://github.com/webpack/source-map-loader
I get the error

WARNING in ./test/HelloWorldSpec.ts
Cannot find SourceMap 'HelloWorldSpec.js.map': Error: Cannot resolve 'file' or 'directory' ./HelloWorldSpec.js.map in c:\Users\m.huber\_Projects\HelloWorldWebpack\test

WARNING in ./src/hello-world.ts
Cannot find SourceMap 'hello-world.js.map': Error: Cannot resolve 'file' or 'directory' ./hello-world.js.map in c:\Users\m.huber\_Projects\HelloWorldWebpack\src

WARNING in ./src/goodbye-world.ts
Cannot find SourceMap 'goodbye-world.js.map': Error: Cannot resolve 'file' or 'directory' ./goodbye-world.js.map in c:\Users\m.huber\_Projects\HelloWorldWebpack\src

Hot Module Reload not working with my setup

Continuing on from my previous question, here is what I am working with and I am not seeing the module reload when I edit the code or the styles in the imported module/class (./components/App/App.tsx). When I edit the application facade (./app.tsx) I get reload with both code and style changes)

tsconfig.json

{
  "compilerOptions": {
    "target" : "ES5",
    "jsx" : "react",
    "sourceMap": true,
    "emitRequireType": false,
    "experimentalDecorators": false,
    "module" : "commonjs"
  },
  "exclude" : ["node_modules", "config", "dev_server.js"]
}

package.json

 "dependencies": {
    "async": "^1.5.0",
    "bcrypt": "^0.8.5",
    "boom": "^2.10.1",
    "breakpoint-sass": "^2.6.1",
    "btns": "^1.1.0",
    "classnames": "^2.2.0",
    "confidence": "^1.4.2",
    "crumb": "^4.0.4",
    "dateformat": "^1.0.11",
    "falcor": "^0.1.13",
    "falcor-hapi": "0.0.2",
    "flux": "^2.1.1",
    "glue": "^2.4.0",
    "hapi": "^11.1.0",
    "hapi-auth-basic": "^3.0.0",
    "hapi-auth-cookie": "^3.1.0",
    "hapi-mongo-models": "^3.0.0",
    "hapi-react-views": "^5.0.0",
    "isomorphic-fetch": "^2.2.0",
    "joi": "^7.0.0",
    "lodash": "^3.10.1",
    "lout": "^7.2.0",
    "mongodb": "^2.0.46",
    "normalize.css": "^3.0.3",
    "object-assign": "^4.0.1",
    "qs": "^5.2.0",
    "react": "^0.14.2",
    "react-dom": "^0.14.2",
    "react-picture": "0.0.4",
    "react-redux": "^4.0.0",
    "react-slick": "^0.9.1",
    "redux": "^3.0.4",
    "slick": "^1.12.2",
    "slick-carousel": "^1.5.8",
    "slug": "^0.9.1",
    "superagent": "^1.4.0",
    "susy": "^2.2.6",
    "vision": "^3.0.0",
    "visionary": "^3.0.1"
 },
  "devDependencies": {
    "autoprefixer": "^6.0.3",
    "awesome-typescript-loader": "^0.14.1",
    "babel": "^6.0.15",
    "babel-core": "^6.0.20",
    "babel-eslint": "^4.1.3",
    "babel-loader": "^6.0.1",
    "babel-plugin-rewire": "^0.1.22",
    "babel-plugin-syntax-jsx": "^6.0.14",
    "babel-plugin-transform-react-jsx": "^6.0.18",
    "babel-plugin-typecheck": "^3.0.0",
    "babel-polyfill": "^6.0.16",
    "babel-preset-es2015": "^6.0.15",
    "babel-preset-react": "^6.0.15",
    "babel-runtime": "^6.0.14",
    "command-line-args": "^2.0.2",
    "concurrently": "^0.1.1",
    "css-loader": "^0.20.2",
    "csslint": "^0.10.0",
    "csslint-loader": "^0.2.1",
    "eslint": "^1.7.3",
    "eslint-loader": "^1.1.1",
    "eslint-plugin-react": "^3.6.3",
    "esprima-fb": "^15001.1.0-dev-harmony-fb",
    "extract-text-webpack-plugin": "^0.8.2",
    "file-loader": "^0.8.4",
    "hapi-cors-headers": "^1.0.0",
    "hapi-webpack-plugin": "^1.1.0",
    "html-loader": "^0.3.0",
    "html-webpack-plugin": "^1.6.2",
    "inert": "^3.1.0",
    "jscs": "^2.5.0",
    "jsdoc": "^3.3.3",
    "jsdoc-babel": "^0.1.0",
    "json-loader": "^0.5.3",
    "jsx-loader": "^0.13.2",
    "node-sass": "^3.3.3",
    "opn": "^3.0.2",
    "postcss-loader": "^0.7.0",
    "react-hot-loader": "^1.3.0",
    "react-transform-hmr": "^1.0.1",
    "redux-logger": "^2.0.4",
    "redux-thunk": "^1.0.0",
    "rimraf": "^2.4.3",
    "sass-loader": "^3.0.0",
    "source-map": "^0.5.3",
    "style-loader": "^0.13.0",
    "ts-loader": "^0.6.0",
    "typescript": "^1.6.2",
    "webpack": "^1.12.3",
    "webpack-dev-server": "^1.12.1",
    "webpack-error-notification": "^0.1.4",
    "webpack-hot-middleware": "^2.4.1"
  }

webpack.config.client-hot.js (I've tried with and without react-hot)

module.exports = {
    devtool: 'source-map',
    debug: true,
    entry: [
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        /*path.resolve(__dirname, './app/views/Index'),*/
        path.resolve(__dirname, './src/global/client/app')
    ],
    output: {
        path: buildDir,
        filename: jsBundle,
        publicPath: "http://localhost:8080/"
    },
    plugins: [
        new ExtractTextPlugin(cssBundle, {
            allChunks: true,
            publicPath: 'http://localhost:8080/'
        }),
        new webpack.optimize.DedupePlugin(),
        new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: ['', '.js', '.json', '.jsx', '.ts', '.tsx'],
        root: ['${__dirname}/src/global/client/']
    },
    module: {
        loaders: [{
            test: /\.html$/,
            loader: htmlLoader
        }, {
            test: /\.css$/,
            loader: 'style!css'
        }, {
            test: /\.scss$/,
            loader: sassLoader
        }, {
            test: /\.jpe?g$|\.gif$|\.png$|\.ico|\.svg$|\.woff$|\.ttf$|\.eot$/,
            loader: fileLoader
        }, {
            test: /\.json$/,
            exclude: /node_modules/,
            loaders: jsonLoader
        }, {
            test: /\.(jsx|es6)$/,
            loaders: jsxLoader,
            exclude: /node_modules/
        }, {
            include: /\.js$/,
            loaders: ["babel-loader?stage=0&optional=runtime&plugins=typecheck"],
            exclude: /node_modules/
        }, {
            test: /\.ts(x?)$/,
            loader: 'awesome-typescript-loader',
            exclude: /node_modules/
        }]
    }
};

tsd.json

{
  "version": "v4",
  "repo": "borisyankov/DefinitelyTyped",
  "ref": "master",
  "path": "typings",
  "bundle": "typings/tsd.d.ts",
  "installed": {
    "react/react.d.ts": {
      "commit": "421d6610bdb09e1015b71f5991d7a68d079eca21"
    },
    "react-dom/react-dom.d.ts": {
      "commit": "af5b8275d1f2b92738b93fddabc461fc20c553a1"
    },
    "react-redux/react-redux.d.ts": {
      "commit": "af5b8275d1f2b92738b93fddabc461fc20c553a1"
    },
    "redux/redux.d.ts": {
      "commit": "af5b8275d1f2b92738b93fddabc461fc20c553a1"
    },
    "node/node.d.ts": {
      "commit": "421d6610bdb09e1015b71f5991d7a68d079eca21"
    },
    "react/react-global.d.ts": {
      "commit": "421d6610bdb09e1015b71f5991d7a68d079eca21"
    }
  }
}

./app.tsx

/// <reference path="../../../typings/tsd.d.ts" />

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { App } from './components/app/App';

import './scss/app.scss';

ReactDOM.render(<App />, document.getElementById('app'));

./components/App/App/tsx

/// <reference path="../../../../../typings/tsd.d.ts" />

import * as React from 'react';
import './_App.scss';

export class App extends React.Component<{}, {}> {
    public render(): React.ReactElement<{}> {
        return (<div className = "app">
            HELLO WORLD AGAIN
        </div>
        );
    }
}

moduleResolution "node" error

setting

{
    "compilerOptions": {
        "target": "ES6",
        "experimentalDecorators": true,
        "moduleResolution": "node"
    }
}

in tsconfig.json will result in the following error

Module build failed: TypeError: Cannot read property 'resolvedModule' of undefined
    at Host.resolveModuleNames (/node_modules/awesome-typescript-loader/dist/host.js:72:27)

I believe this is due to https://github.com/Microsoft/TypeScript/wiki/API-Breaking-Changes#compilerhost-interface-change-comparing-to-typescript-16-beta

deasync dependency alternative

deasync depencency is basically preventing Windows users from using it because it is a native component that requires some stuff to be configured (python, Visual Studio on top). Any alternative?

Doesn't seem to read tsconfig value from loader string?

I have this setup:
module: {
loaders: [
{test: /.ts$/, loader: 'awesome-typescript-loader?tsconfig=tsconfigwebpack.json', exclude: /node_modules/}
]
}

But it still uses the tsconfig.json instead of the one I have defined for compilation?

Hot Module Reload

Does this support HMR with internal modules? (Assuming what I am describing is considered an internal module)

For example (I can include more specifics if this is unclear)
./app.tsx is importing a module from ./components/App/App.tsx
When I edit App.tsx or _App.scss which is being imported into App.tsx, should I be seeing a reload for that module or styles in that sass file?

According to the README internal modules aren't supported and wanted to understand what that means.

Thanks! been trying to get this working with ts-loader and thought I'd see what else is out there:)

Cannot find external module

Given this directory structure:

/dist/data/app/script/classes/shared/item.ts
/dist/data/app/script/classes/shared/status.ts
/dist/data/app/script/classes/shared/tag.ts

/dist/data/app/script/classes/clientItem.ts
/dist/data/app/script/classes/clientTag.ts

And importing clientItem from main.js(traceured, not typescripted), leads to:

ERROR in ./dist/data/app/script/classes/clientItem.ts
...script/classes/clientTag.ts:0:50 
Cannot find external module './shared/tag'.

Any idea why it cannot find the module even though it is obviously right there?

This is the webpack configuration:

var webpackConfig = {
    devtool: 'source-map',
    resolve: {
        root: path.join(__dirname),
        extensions: ['', '.ts', '.js'],
        modulesDirectories: ['node_modules', 'bower_components']
    },
    resolveLoader: {
        root: path.join(__dirname, 'node_modules')
    },
    module: {loaders: [
        {
            test: /\.js$/,
            loader: 'webpack-traceur?runtime&sourceMaps&experimental',
            exclude: [/bower_components/, /node_modules/]
        },
        {
            test: /\.ts$/,
            loader: 'awesome-typescript-loader?target=ES5',
            exclude: [/bower_components/, /node_modules/]
        }
    ]},
    noParse: vendorModules,
    plugins: [
        new webpack.ResolverPlugin(
            new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('bower.json', ['main'])
        ),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ],
    entry: {
        app: path.join('dist', 'data', 'app', 'script', 'main.js'),
        vendor: vendorModules
    },
    output: {
        path: path.join(__dirname, 'dist', 'data', 'app', 'script'),
        filename: '[name].bundle.js',
        pathinfo: true
    }
};

Now that said, compiling those .ts files work as expected when compiling it without using any Webpack loaders.

JSX support

Please add jsx support.
The typescript-loader from andreypopp does work in combination with ts-jsx-loader which convertes template strings into JSX-JavaScript.
This does not work with awesome-typescript-loader anymore.

Does not work with ts-jsx-loader

I'm using this: https://github.com/jbrantly/ts-jsx-loader because it is the only valid way (to keep IDE support) to deal with JSX in TypeScript, but unfortunately I can't get it working with normal way:

webpack.config.js

module.exports = {
    resolve: {
        extensions: ['', '.ts', '.js']
    },
    devtool: 'source-map',
    module: {
        loaders: [{
            test: /\.ts$/,
            loader: 'awesome-typescript-loader!ts-jsx-loader'
        }]
    },
    entry: {
        index: ['./index.ts']
    },
    output: {
        path: '../',
        filename: './[name].js'
    }
};

It's as if ts-jsx-loader is never called. And the React.jsx entries are not transformed.

Manually triggering compiler#run does not build TS files correctly

I'm trying to create a Webpack workflow, where I don't use Webpack's built-in watch mechanism, and I would like to manually trigger the compilation process from a different watcher.

On the first trigger of the watch, I am creating an instance of the Webpack compiler, following the node.js api, then calling run(). Thereafter, and on subsequent triggers, I simply call the run() method again. Pretty much like this:

var webpackCompiler;

gulp.task('webpack', function() {
  webpackCompiler = webpackCompiler || webpack({ /* webpack config */ });

  webpackCompiler.run(function(error, stats) {
    // handle results
  });
});

The ts > js output is done correctly on the first compilation, but subsequent compilations don't touch the outputted .js. Interestingly, Webpack's output indicate that the changed file has been rebuilt.

First time run:

[webpack] Hash: 22d95a4baadbfa5ef83e
Version: webpack 1.12.2
Time: 2116ms
Asset       Size  Chunks             Chunk Names
geminga.js    1.09 MB       0  [emitted]  main
geminga.js.map    1.27 MB       0  [emitted]  main
index.html  193 bytes          [emitted]
chunk    {0} geminga.js, geminga.js.map (main) 1.06 MB [rendered]
    [0] ./src/geminga.ts 176 bytes {0} [built]
    [1] ./~/angular/index.js 48 bytes {0} [built]
    [2] ./~/angular/angular.js 1.06 MB {0} [built]
    [3] ./src/components/dashboard/dashboard.ts 389 bytes {0} [built]
    [4] ./src/components/dashboard/dashboard.controller.ts 484 bytes {0} [built]
    [5] ./src/components/dashboard/dashboard.tpl.html 205 bytes {0} [built]

Subsequent runs, following watch trigger:

Hash: 22d95a4baadbfa5ef83e
Version: webpack 1.12.2
Time: 9ms
         Asset       Size  Chunks             Chunk Names
    geminga.js    1.09 MB       0             main
geminga.js.map    1.27 MB       0             main
    index.html  193 bytes          [emitted]  
chunk    {0} geminga.js, geminga.js.map (main) 1.06 MB
    [0] ./src/geminga.ts 176 bytes {0}
    [1] ./~/angular/index.js 48 bytes {0}
    [2] ./~/angular/angular.js 1.06 MB {0}
    [3] ./src/components/dashboard/dashboard.ts 389 bytes {0} [built]
    [4] ./src/components/dashboard/dashboard.controller.ts 484 bytes {0}
    [5] ./src/components/dashboard/dashboard.tpl.html 205 bytes {0}

Notice the [built] tag after dashboard.ts, which is the file that was changed.

Initially I thought I was doing something wrong with the compiler (maybe I still am), but I've also tested changing a different type of file (e.g. .html) registered with a different loader, and that worked fine.

Is there some sort of cache that is causing this?

Compilation dose not work in watch mode

My configuration is

module.exports = {
  watch: true,
  resolve: {
    extensions: ['', '.ts']
  },
  module: {
    loaders: [{
      test: /\.ts$/,
      exclude: /node_modules/,
      loader: 'awesome-typescript-loader',
    }]
  }
};

and my gulpfile is

var gulp = require('gulp');
var path = require('path');
var webpack = require('webpack-stream');

var config = require('./webpack.config');

var sources = [
  path.join(__dirname, '/src/app1/app1.ts')
];
var dest = path.join(__dirname, '/dist');

gulp.task('build', function(callback) {
  return gulp.src(sources)
    .pipe(webpack(config))
    .pipe(gulp.dest(dest));
});

gulp.task('default', ['build']);

compilation only works in the first time execute gulp command.

 c:\work>gulp
[23:14:06] Using gulpfile c:\work\gulpfile.js
[23:14:06] Starting 'build'...
[23:14:09] Version: webpack 1.12.4
                  Asset     Size  Chunks             Chunk Names
ba333baa88334adf4b2d.js  1.69 kB       0  [emitted]  main
[23:14:09] webpack is watching for changes
[23:14:17] Version: webpack 1.12.4
[23:14:17] webpack is watching for changes
  • node v5.0.0
  • gulp v3.9.0
  • webpack v1.12.4
  • webpack-stream v2.1.1
  • awesome-typescript-loader v0.14.1

Does this work with ES6?

I'm trying to use ES6, and it's import syntax but it's throwing weird errors.

I use now:

loaders: [{
        test: /\.ts$/,
        loader: 'awesome-typescript-loader?target=es6&module=!ts-jsx-loader'
    }, ...]

I had to put module= since commonjs does not support es6 styled imports. Now I get:

ERROR in ./index.ts
Cannot find global type 'Iterable'.

ERROR in ./index.ts
Cannot find global type 'Symbol'.

ERROR in ./index.ts
Cannot find global value 'Symbol'.

and the list goes on...

And my index.ts is basically empty:

/// <reference path='./index.d.ts' />
/// <reference path='./typings/jquery/jquery.d.ts' />
/// <reference path='./typings/react/react.d.ts' />
/// <reference path='./node_modules/ts-jsx-loader/react-jsx.d.ts' />
/// <reference path='./node_modules/typed-react/typed-react.d.ts' />

import run from "./Application";
run();

Cannot resolve module 'awesome-typescript-loader'

Firstly, thanks for a great loader.

Previously I used typescript-loader but since we use Azure I switched to using awesome-typescript-loader after windows path bugs were fixed in this project. Now it works great to build on windows though I am using OS X and when I try to build my project locally I get following error

ERROR in multi main
Module not found: Error: Cannot resolve module 'awesome-typescript-loader' in /Users/Fredrik/path/to/project
 @ multi main

Any idea what might be wrong? I have all node_modules installed and even tried a clean npm install. Do I need to resolve the module manually in the config?

//webpack.config.js

var webpack = require("webpack");
var path = require('path');

module.exports = {
    entry: {
        main: ['./src/js/main']
    },

    output: {
        path: path.join(__dirname, "dist"),
        filename: "main.js",
        sourceMapFilename: "debug/[name].map"
    },

    // Source maps support (or 'inline-source-map' also works)
    devtool: 'source-map',

    resolve: {
        root: path.join(__dirname),
        // Allow to omit extensions when requiring these files
        extensions: ['', '.ts', '.webpack.js', '.web.js', '.js'],
        modulesDirectories: ['node_modules']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'awesome-typescript-loader'
            }
            ,{
                test: /\.css$/,
                loader: "style-loader!css-loader" }
            ,{
                test: /\.less$/,
                loader: "style!css!less"
            }
        ]
    }

};
// package.json

  "dependencies": {
    "crossroads": "^0.12.0",
    "css-loader": "^0.12.0",
    "exports-loader": "^0.6.2",
    "git-rev": "^0.2.1",
    "gulp": "^3.6.2",
    "gulp-clean": "^0.3.1",
    "gulp-deploy-azure-cdn": "~1.0.0",
    "gulp-header": "^1.2.2",
    "gulp-preprocess": "~1.2.0",
    "gulp-rename": "~1.2.0",
    "gulp-strip-debug": "~1.0.2",
    "gulp-tsc": "^0.9.3",
    "gulp-uglify": "^1.1.0",
    "gulp-util": "~3.0.4",
    "gulp-watch": "^4.2.4",
    "gulp-webpack": "^1.3.0",
    "html-loader": "^0.3.0",
    "knockout": "^3.3.0",
    "less-loader": "^2.2.0",
    "run-sequence": "^0.3.6",
    "strip-loader": "~0.1.0",
    "style-loader": "^0.12.2",
    "superagent": "^1.2.0",
    "webpack": "^1.7.3",
    "webpack-dev-server": "^1.7.0",
    "awesome-typescript-loader": "^0.3.0"
  },
  "engines": {
    "node": "0.10.x"
  }
}

Sourcemaps

Is there any secret sauce required to get typescript-sourcemaps that work correctly when you are not using webpack's built-in dev server?

Typescript 1.5.3 and commonjs

With Typescript 1.5.3 I'm getting the error:

Cannot compile modules unless the '--module' flag is provided.

How can I pass this flag to compiler?

tsx is not supported

Is there a way to get the built in jsx support of the typescript compiler to work? The only solution I found is to pipe the output to the babel-loader. It looks as if it worked at some point (around 0.6).

Module build failed: Error: File was not found in program

I tried to add this typescript loader to the following sample project:
https://github.com/iam4x/isomorphic-flux-boilerplate
I get an error while running "npm run dev". I'm not sure how to proceed from here. The path in the error seems correct.

ERROR in ./app/components/orderEdit.ts
Module build failed: Error: File C:\i\app\components\orderEdit.ts was not found
in program
at State.emit (C:\i\node_modules\awesome-typescript-loader\dist\host.js:120:
23)
at C:\i\node_modules\awesome-typescript-loader\dist\index.js:92:42
at tryCatcher (C:\i\node_modules\awesome-typescript-loader\node_modules\blue
bird\js\main\util.js:24:31)
at Promise._settlePromiseFromHandler (C:\i\node_modules\awesome-typescript-l
oader\node_modules\bluebird\js\main\promise.js:454:31)
at Promise._settlePromiseAt (C:\i\node_modules\awesome-typescript-loader\nod
e_modules\bluebird\js\main\promise.js:530:18)
at Async._drainQueue (C:\i\node_modules\awesome-typescript-loader\node_modul
es\bluebird\js\main\async.js:182:12)
at Async._drainQueues (C:\i\node_modules\awesome-typescript-loader\node_modu
les\bluebird\js\main\async.js:187:10)
at Immediate.Async.drainQueues [as _onImmediate](C:inode_modulesawesome-
typescript-loadernode_modulesbluebirdjsmainasync.js:15:14)
at processImmediate as _immediateCallback
@ ./app/routes.jsx 31:13-46

Is it possible to declare references to *.d.ts files only in tsconfig.json, not in *.ts files?

I found that awesome-typescript-loader fails on compiling *.ts files without special reference comments to external modules, but tsc command works well in this situation.

I assume that this is probably because I moved all references to tsconfig.json and for some reason awesome-typescript-loader doesn't use them.

If you need repro you can grab this repo https://github.com/Den-dp/webpacked-typescript-demo and run npm start to install all deps and run webpack.

Compilation with tsc works fine (even with commented reference https://github.com/Den-dp/webpacked-typescript-demo/blob/master/src/app.ts#L1 ), but compilation with webpack gives me the following error:

[[email protected]] C:\dev\webpacked-typescript-demo (master)
λ webpack
Hash: ed9338a38e248b532e37
Version: webpack 1.11.0
Time: 2214ms
        Asset    Size  Chunks             Chunk Names
    bundle.js  427 kB       0  [emitted]  main
bundle.js.map  506 kB       0  [emitted]  main
    + 4 hidden modules

ERROR in C:/dev/webpacked-typescript-demo/src/app.ts:4:20
Cannot find module 'lodash'.

Am I missing something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.