我目前正在使用ReactJS
使用TypeScript
作为我定义组件的基础语言。
我在许多网站上看到,可以在页面中呈现此类组件(在我的情况下为cshtml
)。尤其是我试图完成的here。
要做到这一点,应该有:
<!-- ... -->
<body>
<div id="myTargetId"></div>
</body>
<!-- ... -->
<script src="@(Url.Content("~/Scripts/React/dist/commons.js"))"></script>
<script src="@(Url.Content("~/Scripts/React/dist/MyComponent.js"))"></script>
<script>
ReactDOM.render(React.createElement(MyComponent, {}), document.getElementById("targetId"));
</script>
目前我收到以下错误:
未捕获的ReferenceError:未定义MyComponent
这就是我MyComponent.tsx
的样子:
import * as React from "react";
export interface IMyComponentProps { }
export interface IMyComponentState { }
export class MyComponent extends React.Component<IMyComponentProps, IMyComponentState> {
render(): JSX.Element {
return (
<p>This comes from ReactJs</p>
);
}
}
要将所有内容打包在一起,我使用webpack
以及webpack.config.js
(简化):
const webpack = require("webpack");
module.exports = {
entry: {
MyComponent: "./Scripts/React/Modules/MyComponent.tsx"
},
output: {
path: path.join(__dirname, "./Scripts/React/dist/"),
filename: "[name].js"
},
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};
最后,这是发出的JavaScript
:
webpackJsonp([0],[
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = __webpack_require__(1);
class MyComponent extends React.Component {
render() {
return (React.createElement("p", null, "This comes from ReactJs"));
}
}
exports.MyComponent = MyComponent;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = React;
/***/ })
],[0]);
//# sourceMappingURL=MyComponent.js.map
我在这里缺少什么?
答案 0 :(得分:0)
未捕获的ReferenceError:未定义MyComponent
导入错误:
<script src="@(Url.Content("~/Scripts/React/dist/commons.js"))"></script>
<script src="@(Url.Content("~/Scripts/React/dist/MyComponent.js"))"></script>
您应该使用webpack构建bundle.js
。
互联网上许多快速入门之一https://basarat.gitbooks.io/typescript/docs/quick/browser.html