Andres Roget
Andres Roget

Reputation: 144

TypeScript compilation extremely slow > 12s

Just putting this out there to see if someone else is having this issue...

I have building an angular 2 app with typescript using webpack as my build tool, it all works well, however I have noticed typescript compilation is super super slow, I am at 12 seconds right now...., and its pretty clear that is all due to the typescript compilation process....

I have used ts-loader or awesome-typescript-loader with a similar result, if I comment out this loader, my build time drops to around 1 sec....

After some research it seems like its 'normal' to have 'slow' times when compiling typescript, but is 12secs the normal??

Old posts hinted it might be due to a node version conflict, I am currently running v4.4.2...

Any how below is my webpack code in case anyone spots something wrong there.. the commented code in the Uglify section is due to some 'bug' on the angular 2 side...

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');

const NpmInstallPlugin = require('npm-install-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TARGET = process.env.npm_lifecycle_event;

const PATHS = {
  app: path.join(__dirname, 'app'),
  dist: path.join(__dirname, 'dist')
};

const common = {
  entry: {
    vendor: ['./app/vendor.ts'],
    main: ['./app/boot.component.ts']
  },
  output: {
    filename: '[name].[hash].bundle.js',
    path: PATHS.dist
  },
  resolve: {
    extensions: ['', '.js', '.ts']
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Qarrot Performance',
      template: 'index.template.ejs',
      commonStyles: [
        '/public/styles/vendor/normalize.css',
        '/public/styles/main.css'
      ],
      commonScripts: [],
      baseHref: '/',
      unsupportedBrowser: true,
      mobile: true,
      appMountId: 'app'
    }),
  ],
  module: {
    loaders: [
      {
        test: /\.ts$/,
        exclude: /node_modules/,
        loaders: ['ts-loader']
      },
      {
        test: /\.scss$/,
        loader: 'raw-loader!sass-loader'
      },
      {
        test: /\.html$/,
        loader: "html"
      }
    ]
  }
}

// Dev Settings
if(TARGET === 'start' || !TARGET) {
  module.exports = merge(common, {
    devtool: 'eval-source-map',
    devServer: {
      contentBase: PATHS.build,
      historyApiFallback: true,
      hot: true,
      inline: true,
      progress: true,
      stats: 'errors-only',
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin(),
      new NpmInstallPlugin({
        save: true
      })
    ]
  });
}

// Prod Settings
if(TARGET === 'build') {
  module.exports = merge(common, {
    devtool: 'cheap-module-source-map',
    plugins: [
      // new webpack.optimize.UglifyJsPlugin({
      //   beautify: false,
      //   mangle: false,
      //   compress : { screw_ie8 : true },
      //   comments: false
      // }),
      new webpack.optimize.DedupePlugin(),
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"'
      }),
      new CopyWebpackPlugin([
            { from: 'public', to: 'public' }
      ]),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest']
      }),
    ]
  });
}

I am also on a Mac, running Angular 2 beta.15 and webpack version 1.12, below is my tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": false,
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Upvotes: 11

Views: 7728

Answers (3)

Daniel Kaplan
Daniel Kaplan

Reputation: 67514

There is now an official wiki suggesting best practices and ways to troubleshoot compiler performance. It's pages long, so there's lots of information to help. Here's one of many suggestions:

extendedDiagnostics

You can run TypeScript with --extendedDiagnostics to get a printout of where the compiler is spending its time.

Files:                         6
Lines:                     24906
Nodes:                    112200
Identifiers:               41097
Symbols:                   27972
Types:                      8298
Memory used:              77984K
Assignability cache size:  33123
Identity cache size:           2
Subtype cache size:            0
I/O Read time:             0.01s
Parse time:                0.44s
Program time:              0.45s
Bind time:                 0.21s
Check time:                1.07s
transformTime time:        0.01s
commentTime time:          0.00s
I/O Write time:            0.00s
printTime time:            0.01s
Emit time:                 0.01s
Total time:                1.75s

Note that Total time won't be the sum of all times preceding it, since there is some overlap and some work is not instrumented.

The most relevant information for most users is:

Field Meaning
Files the number of files that the program is including (use --listFilesOnly to see what they are).
I/O Read time time spent reading from the file system - this includes traversing include'd folders.
Parse time time spent scanning and parsing the program
Program time combined time spent performing reading from the file system, scanning and parsing the program, and other calculation of the program graph. These steps are intermingled and combined here because files need to be resolved and loaded once they're included via imports and exports.
Bind time Time spent building up various semantic information that is local to a single file.
Check time Time spent type-checking the program.
transformTime time Time spent rewriting TypeScript ASTs (trees that represent source files) into forms that work in older runtimes.
commentTime Time spent calculating comments in output files.
I/O Write time Time spent writing/updating files on disk.
printTime Time spent calculating the string representation of an output file and emitting it to disk.

Things that you might want to ask given this input:

  • Does the number of files/number of lines of code roughly correspond to the number of files in your project? Try running --listFiles if not.
  • Does Program time or I/O Read time seem fairly high? Ensure your include/exclude settings are configured correctly.
  • Do other times seem off? You might want to file an issue! Things you can do to help diagnose it might be
    • Running with emitDeclarationOnly if printTime is high.
    • Read up instructions on Reporting Compiler Performance Issues.

Upvotes: 0

kyranjamie
kyranjamie

Reputation: 1044

I would stick to the awesome-typescript-loader. It has some performance options you can enable: a caching option and a transpile only option:

"awesomeTypescriptLoaderOptions": {
  "useCache": true,
  "transpileOnly": true
}

Both of these had a significant improvement on compile times.

Upvotes: 6

basarat
basarat

Reputation: 276333

Please share you tsconfig.json. Most likely you have noEmitOnError set to true which means that the compiler is forced to typecheck the whole codebase before any emitting.

Please set that to false.

Upvotes: -1

Related Questions