Webpack + React + Typescript

11

是否可以使用webpack与React和TypeScript并将它们打包成一个Web捆绑包,但仍能够调试原始的TypeScript和React代码?在webpack中,我正在使用ts-loader和ts-jsx-loader以及devtool:“source-map”,但是当我尝试进行浏览器调试时,我看不到原始的ts代码,而是看到已经被webpack更改过的代码。

我的当前基本webpack.config.js文件:

var webpack = require('webpack');
module.exports = {
  entry: ['./app/main.ts'],
  output: {
    path: './build',
    filename: 'bundle.js'
  },
  debug: true,
  devtool: 'source-map',
  plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.UglifyJsPlugin()
  ],
  resolve: {
    extensions: ['', '.ts', '.js']
  },
  module: {
    loaders: [
      {
        test: /\.ts$/,
        loader: 'ts-loader!ts-jsx-loader'
      }
    ]
  }
};

tsconfig.json:

{
    "compileOnSave": false,
    "version": "1.5.0-alpha",
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "noLib": false,
        "sourceMap": true,
        "noImplicitAny": true,
        "removeComments": true
    },
    "files": [
        "./AppComponent.ts",
        "./libs/jsx.d.ts",
        "./libs/react.d.ts",
        "./libs/webpack-runtime.d.ts",
        "./main.ts"
    ]
}

例如-我的原始 .ts 文件如下:

import React = require('react');

class AppComponent extends React.Component<any, any> {
  render () {
    return React.jsx(`
      <h1>He world!</h1>
    `);
  }
};
export = AppComponent;

在 Chrome 调试器中它看起来像这样:

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var React = __webpack_require__(2);
var AppComponent = (function (_super) {
    __extends(AppComponent, _super);
    function AppComponent() {
        _super.apply(this, arguments);
    }
    AppComponent.prototype.render = function () {
        return (React.createElement("h1", null, "He world!"));
    };
    return AppComponent;
})(React.Component);
;
module.exports = AppComponent;


/*****************
 ** WEBPACK FOOTER
 ** ./app/AppComponent.ts
 ** module id = 158
 ** module chunks = 0
 **/
2个回答

2

您不需要使用ts-jsx-loader。

在您的tsconfig.json文件中,您只需要像这样:

{
  "compilerOptions": {
    "jsx": "react",
    "sourceMap": true,
    // ... other options
  }
}

当然,你仍然需要在webpack配置文件中添加devtool选项。

1

很可能您没有在tsconfig.json文件中指定sourceMap,因此TypeScript编译器未输出sourcemaps。


我已经在tsconfig.json中添加了sourceMap,但仍然无法工作。 - barylov
所以我刚刚使用了你的配置尝试了一下。唯一注意到的是,假设你正在使用Chrome,你需要在加载页面时保持devtools打开,否则sourcemap不会被加载。还要注意的是,原始的Javascript和TypeScript都显示在sources下面,而不仅仅是TypeScript。最后,为了确保一切正常,你应该检查你的bundle.js文件,确保它有一个sourceMappingURL,并且bundle.js.map文件看起来没问题(你应该能看到一些TypeScript)。 - James Brantly
谢谢你的帮助,但不幸的是它仍然无法工作。我已经发布了一些示例,展示了原始代码和调试器中的代码。 - barylov
你的输出中,是否有一个名为bundle.js.map的文件?(它应该与bundle.js文件在同一目录下) - James Brantly
@JamesBrantly 我遇到了与原始 SO 所有者类似的情况,并且我确实看到了一个 bundle.js.map 文件。然而,我仍然无法在 Chrome 中看到源映射。您认为还可能是什么问题? - wmock

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