8
votes

My project is written in TypeScript and uses webpack to bundle scripts. All .ts files go through the TypeScript loader in order to transpile them to JavaScript; what I am trying to figure out how to do is to have some some specific imports go through a custom webpack loader. Something like:

import widget from 'myCustomLoader!./widget';

Of course, this doesn't work because TypeScript has no idea how to interpret webpack's loader syntax. Ideally TypeScript would just ignore everything before the ! and just look at './widget' for the purposes of type checking.

Another possibility I considered is to have all .ts files go through myCustomLoader by specifying it in webpack.config, and then using some sort of querystring to signal it to do it's work. For example:

import widget from './widget?myCustomLoader=true';

But TypeScript still can't handle that. Obviously using require directly will work:

var widget = require('myCustomLoader!./widget');

...but then I've lost all the type safety that TypeScript offers. Can anyone suggest a way to specify (or otherwise interact with) a custom webpack loader and still keep the type safety benefits of TypeScript import syntax?

1
What type of content is your widget? Regular JavaScript? TypeScript? What's the extension of the files? Could you describe the use case for having a custom loader here? - Andreas Jägle

1 Answers

0
votes

Did you consider configuring two loaders in your webpack configuration for the different cases? There are possibilities to define includes and excludes for each loader configuration. This could be a way to tackle your problem by just defining two entries, one for ts-loader only and one for custom-loader.

{
  module: {
    loaders: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, "app/src/special/widgets")
        ],
        loader: "custom-loader"
      },
      {
        test: /\.ts$/,
        exclude: [
          path.resolve(__dirname, "app/src/special/widgets")
        ],
        loader: "ts-loader"
      }
    ]
  }
}

This allows to just `import widget from './widget' when the path matches.

Another option would be to add a special test on the widget if you can match it easily with a regular expression.

If your widget also needs to be processed by the ts-loader (because you wrote it as an typescript file), you can chain the loaders in your configuration, too. This would look something like loader: "ts-loader!custom-loader" if the code must be processed by the custom loader before it goes into the ts-loader.

Please check the webpack docs on module loaders for more information.