0

I tried to use CommonJS + TypeScript and React, but I got stuck in the following problem in loading of the initial code:

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>

The loading file: 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;

Error: *Uncaught ReferenceError: require is not defined at index.tsx:1 import * as React from 'react';*

I do have the webpack installed, and I can create bundles, but honestly I do not want to do that, because this is for my development, and there is no reason to do that for my development.

I know that I can use AMD, but, boy! I got so mad on the AMD, after on the dev environment got me in so many problems.

Do I need to use any other loader? I use now, requirejs, that I know by default works / designed for AMD.

thanks in advance.

  • not use import to import react as a module library,just use as global library.and then compile the .ts into .js,add the – holi-java Mar 14 '17 at 08:40

1 Answers1

0

Yes - absolutely.

You can (and in my very humble opinion should) go without bundlers if there are no specific requirements to do otherwise.

As for now browsers do not support module loading out of the box so you will need a module loader. I recommend to use systemjs instead of requirejs. It has a wider spread and loads about anything you can throw at it. Here is an example of how to set things up, and somewhere similar question here. This will get you going.

As a side note. I would recommend you to use JSPM instead of directly working with SystemJS. Internally it is using systemjs but removes hassle of configuring it for all different modules out there. Have a look: example.

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54