Xavi
Xavi

Reputation: 603

Error webpacking library source maps in ES6 app, works in ES5 app

I distribute an ES6 library, transpiled to ES5, with source maps using this webpack.config.js

var webpack = require("webpack");

module.exports = {
  entry: ['./src/MyLib.js'],
  output: {
    path: __dirname,
    filename: 'dist/bundle.js',
    libraryTarget: 'umd',
    library: "MyLib"
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        query: { presets: ['es2015'] }
      },
      {
        test: /\.css$/,
        loader: "style-loader!css-loader"
      }
    ]
  },
  devtool: 'source-map'
};

As hinted in Webpack's devtool docs I use the source-map-loader to make the library source maps available in an ES5 app that uses the library. It works with this webpack.config.js

var path = require("path");

module.exports = {
  entry: './main.js',
  output: {
    filename: 'dist/bundle.js'
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map',
        include: /my-lib/
      }
    ]
  },
  resolveLoader: {
    root: path.join(__dirname, "node_modules"),
  },
  devtool: 'source-map'
};

The problem is that when the consumer of the library is an ES6 app, with the following webpack.config.js, which just adds the babel loader to the config file that works for the ES5 app,

var path = require("path");

module.exports = {
  entry: './main.js',
  output: {
    filename: 'dist/bundle.js'
  },
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'source-map',
        include: /my-lib/
      }
    ],
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        query: { presets: ['es2015'] }
      }
    ]
  },
  resolveLoader: {
    root: path.join(__dirname, "node_modules"),
  },
  devtool: 'source-map'
};

then, when running webpack, there's an error like

ERROR in ./~/my-lib/dist/bundle.js
Module build failed: Error: /Users/xavi/Development/my-lib/examples/es6/node_modules/my-lib/dist/bundle.js: Invalid mapping: {"generated":{"line":8,"column":0,"lastColumn":null},"source":null,"original":{"line":null,"column":null},"name":null}
...

Why this source maps configuration works when the consumer is an ES5 app but not when it's an ES6 app transpiled with Babel? How to make the library source maps available in the ES6 app?

Upvotes: 1

Views: 552

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161477

Babel must have some issues ingesting your library's sourcemaps, and since you have test: /\.js$/,, Babel will process every single JS file in your repo, including node_modules.

I'd recommend restricting that test to only match files you want Babel to process, and that will likely be enough to avoid this, though it doesn't resolve the underlying issue.

Upvotes: 2

Related Questions