【发布时间】:2017-03-14 08:25:02
【问题描述】:
我尝试使用 CommonJS + TypeScript 和 React,但在加载初始代码时遇到以下问题:
Index.html
<script type="text/javascript">
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
loadScript('./Scripts/react.js');
loadScript('./Scripts/react-dom.js');
loadScript('./Scripts/require.js');
loadScript('./Scripts/index.js');
</script>
加载文件:index.ts
var rootElement;
function _onLoad() {
rootElement = rootElement || document.getElementById('root');
ReactDOM.render(React.createElement(DataSample, null), rootElement);
}
function _onUnload() {
if (rootElement) {
ReactDOM.unmountComponentAtNode(rootElement);
}
}
var isReady = document.readyState === 'interactive' || document.readyState === 'complete';
if (isReady) {
_onLoad();
}
else {
window.onload = _onLoad;
}
window.onunload = _onUnload;
错误: *Uncaught ReferenceError: require is not defined 在 index.tsx:1 导入 * as React from 'react';*
我确实安装了 webpack,并且可以创建 bundle,但老实说我不想这样做,因为这是为了我的开发,没有理由为我的开发这样做。
我知道我可以使用 AMD,但是,男孩!在开发环境给我带来了很多问题之后,我对 AMD 非常生气。
我需要使用任何其他加载器吗?我现在使用 requirejs,我知道默认情况下可以工作/专为 AMD 设计。
提前致谢。
【问题讨论】:
-
不使用 import 将 react 作为模块库导入,仅用作全局库。然后将 .ts 编译为 .js,添加
标签: javascript typescript requirejs amd commonjs