【问题标题】:Can I use CommonJS + TypeScript and React without bundles?我可以在没有捆绑包的情况下使用 CommonJS + TypeScript 和 React 吗?
【发布时间】: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


【解决方案1】:

是的 - 绝对。

如果没有特定要求,您可以(并且在我非常拙见的意见中应该)不使用捆绑器。

目前浏览器不支持开箱即用的模块加载,因此您需要一个模块加载器。我建议使用 systemjs 而不是 requirejs。它的传播范围更广,并且可以加载任何您可以扔给它的东西。这是关于如何设置的example,以及类似的问题here。这会让你继续前进。

作为旁注。我建议您使用 JSPM 而不是直接使用 SystemJS。它在内部使用 systemjs,但消除了为所有不同模块配置它的麻烦。看看:example

【讨论】:

    猜你喜欢
    • 2016-08-11
    • 2022-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2018-05-22
    • 2018-06-23
    • 2020-12-07
    相关资源
    最近更新 更多