Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use JSX with nodejs ESM module loader

I attempted to run a simple block of code featuring React "render" method , but the browser didn't display the text.

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(<h1>Hello World</h1>,document.getElementById('root'));

I'm using VS Code as editor therefore I typed the "Run and Debug Node.js" command. It came up with the warning below

(node:3004) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

Setting "type:module" in the package.json file solved the problem but on the other side another problem arised

(node:18968) ExperimentalWarning: The ESM module loader is experimental.    
warning.js:32
SyntaxError: Unexpected token '<'
 at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)
 at async link (internal/modules/esm/module_job.js:37:21)

That won't allow me to write any tags whatsover. What am I missing and how can I solve it? Below is the index.html file and the file structure

<html>
    <head>
        <title> React Test</title>
    </head>

    <body>
        <div id="root"></div>
    </body>
</html>

The file structure

like image 954
X HOxha Avatar asked Jun 11 '20 16:06

X HOxha


People also ask

Does Nodejs support JSX?

That said, almost everyone uses node. js for development tooling and uses jsx. You can use any language for your api server, but you'll use a node. js server in development most of the time.

Does TypeScript support ESM?

The TypeScript team announced the release of TypeScript 4.8 beta and TypeScript 4.7, which introduces ES Module (ESM) support for Node. js, improved type inference and control flow analysis, and significant performance improvements.


1 Answers

JSX isn't a valid JavaScript syntax and it isn't part of any ECMAScript specification as well at the current time. NodeJS supporting ESM does not mean it supports JSX natively.

JSX are expected to be transpiled into a valid JavaScript on build/compile time using tools like babel. If you are using React, the most simple way to do this is to use babel with @babel/preset-react, which will transpile all JSX into React.createElement() calls. You can then run the code generated by babel using node.

To give you a clearer picture, here is a Babel online REPL that you can play with to see how your code are transpiled by babel.

A common setup for react apps that is going to be run on the browser is like:

  1. Use webpack to bundle your app
  2. Configure webpack to use babel-loader so it transpiles your code into something that browsers can run
  3. Use the generated javascript bundle on browser
like image 50
Jackyef Avatar answered Sep 20 '22 17:09

Jackyef