2

I am trying to import redom library but keep getting this error:

Uncaught TypeError: Cannot read property 'nodeType' of null

My code is listed below:

<!DOCTYPE html>
<html>
<head>
    <script src='test.js'></script>
    <script src="libraries/redom.min.js" type='text/javascript'></script>
    <script>
      const { el, mount } = redom;
      const hello = el('h1', 'Hello World');
      mount(document.body, hello);
    </script>

</head>
<body>
</body>
</html>

If I change const { el, mount } = redom; to import { el, mount } from 'redom', I get Uncaught SyntaxError: Unexpected token import.

The path is correct, and redom.min.js is not broken.

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
  • I'm not familiar with `redom`, but perhaps the error is because the script is called before the DOM is loaded? Try putting it in a `window.onload` handler? – Jonathan Lam Oct 29 '17 at 16:39
  • And yes, the `import` statement is [barely supported in web browsers right now](https://stackoverflow.com/a/44086319/2397327). – Jonathan Lam Oct 29 '17 at 16:42
  • @LambdaNinja window.onload worked! Thanks. But do I need to use onload handler everytime I use redom? The redom documentation was not even talking about onload handler. – Masaki Minamide Oct 29 '17 at 16:52
  • I'm glad I helped! AFAIK the convention for most JavaScript is to wrap the whole JavaScript code in a `window.onload` (or a jQuery `$(document).ready()`) so that all runs after the page loads and there are no errors with the DOM. – Jonathan Lam Oct 29 '17 at 20:07

2 Answers2

0

Adding attribute type="module" to the script which loads redom may fix problem ( if you use latest Chrome ) :

<script src="libraries/redom.min.js" type="module"></script>

However the exception is expected as the import statement isn't supported by majority of the browsers, see quote:

Note: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel, Rollup or Webpack.

Source: import - JavaScript | MDN

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

If you want to try ES2015, you can also use:

<!DOCTYPE html>
<html>
  <body>
    <script type="module">
      import { el, mount } from 'https://redom.js.org/redom.es.min.js';

      const hello = el('h1', 'Hello RE:DOM!');

      mount(document.body, hello);
    </script>
  </body>
</html>

(you need a modern browser, like the latest Chrome)

user229044
  • 232,980
  • 40
  • 330
  • 338