Search code examples
typescriptwebpacksource-maps

Webpack use existing source map from previous build step


I have .ts files compiled to .js and .js.map files by my editor and am bundling the .js files using webpack. (I don't want webpack to be responsible for compiling the .ts because then the errors won't appear properly in the editor.)

If I feed the compiled .js files to webpack it doesn't pick up the existing .js.map files (via //# sourceMappingURL=... in each file), and so the resulting bundle.js.map points to the .js files, but not to the original .ts files.

How can I get webpack to hold onto the existing .js.map files so the resulting bundle.js.map points right back to the original .ts files?


Solution

  • It turns out an extra webpack "preLoader" called source-map-loader does the trick:

    $ npm install source-map-loader --save
    

    Then in webpack.config.js:

    module.exports = {
      devtool: 'source-map',
      module:  {
        preLoaders: [
          {
            test:   /\.js$/,
            loader: 'source-map-loader'
          }
        ]
      }
    };
    

    Update for Webpack 2+

    module.exports = {
      devtool: 'source-map',
      module: {
        rules: [
          {
            test: /\.js$/,
            use: ["source-map-loader"],
            enforce: "pre"
          }
        ]
      }
    };