在ES6应用程序中对库源映射进行网络打包时出错,可在ES5应用程序中使用

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

本文关键字:应用程序 出错 包时 可在 ES5 ES6 映射 网络      更新时间:2023-09-26

我使用这个webpack.config.js 分发了一个ES6库,并将其转换为ES5

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'
};

正如Webpack的devtool文档中所暗示的那样我使用source-map-loader使库源映射在使用该库的ES5应用程序中可用。它与这个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'
};

问题是,当库的使用者是ES6应用程序时,具有以下webpack.config.js,它只是将babel加载程序添加到适用于ES5应用程序的配置文件中

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'
};

然后,当运行webpack时,会出现类似的错误

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}
...

为什么当消费者是一个ES5应用程序,而当它是一个用Babel移植的ES6应用程序时,这个源映射配置就不起作用了?如何在ES6应用程序中提供库源地图?

Babel在获取库的源映射时一定会遇到一些问题,由于您有test: /'.js$/,,因此Babel将处理您的repo中的每一个JS文件,包括node_modules

我建议将test限制为只匹配您希望Babel处理的文件,这可能足以避免这种情况,尽管它不能解决根本问题。

相关文章: