使用webpack将Typescript转换为Babel sourcemaps

10

从ts-loader的问题复制粘贴,因为在此可能更合适:

如何将typescript源映射传递给babel,以便最终的sourcemap指向原始文件而不是编译后的typescript文件?

这是我的开发设置示例:

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "jsx": "react",
    "noImplicitAny": false,
    "sourceMap": true
  },
  "exclude": ["node_modules", "gulpfile.js", "webpack.config.js", "server.js"]
}

webpack.dev.js

var path = require("path");
var webpack = require("webpack");

module.exports = {
  devtool: "eval",
  entry: [
    "webpack-hot-middleware/client",
    "./src/app/index",
  ],
  output: {
    path: path.join(__dirname, "build"),
    filename: "app.js",
    publicPath: "/static/"
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.ProvidePlugin({
      'window.fetch': 'exports?self.fetch!whatwg-fetch'
    })
  ],
  resolve: {
    extensions: ['', '.ts', '.tsx', '.js']
  },
  module: {
    noParse: [
      /\/sinon.js/
    ],
    preLoaders: [{
      test: /\.ts(x?)$/,
      loader: "tslint",
      exclude: /node_modules/
    }],
    loaders: [
      {
        test: /\.tsx?$/,
        loader: 'babel-loader!ts-loader',
        exclude: /node_modules/,
        include: path.join(__dirname, 'src')
      }
    ]
  }
};
2个回答

4
您可以使用webpack的source-map-loader。这是我的webpack.config.js文件:
module.exports = {
    entry: "./app.ts",
    output: {
        filename: "./bundle.js",
    },

    devtool: "source-map",

    resolve: {
        extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"]
    },

    module: {
        loaders: [
            // ts -> ES6 -> babel -> ES5
            { test: /\.tsx?$/, loaders: ["babel-loader", "ts-loader"] }
        ],

        preLoaders: [
            { test: /\.js$/, loader: "source-map-loader" }
        ]
    }
};

还有tsconfig.js文件:

{
    "compilerOptions": {
        "target": "es6",
        "sourceMap": true
    },
    "exclude": [
        "node_modules"
    ]
}

source in chrome devtools


我无法在 Babel 7 和 Webpack 4 上使其正常工作。生成的源映射反映了 TypeScript 编译器转译输出而不是源文件。 - Paul Turner

2

虽然这是一个老问题,但如果有人遇到了类似的情况,可以尝试在webpack配置中设置不同的devtool值,例如:

devtool: 'inline-cheap-module-source-map'

每个设置的预期输出结果可参考: https://webpack.js.org/configuration/devtool/#root


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接