Why do I get an error with importing React

eugen :

I am learning React.js and I converted this line into pure JavaScript using Babel's online converter:

const element = <div tabIndex="0"></div>;

became:

"use strict";


import { React } from "react";
var element = React.createElement("div", {
    tabIndex: "0"
});

console.log(element)

But when I run it in Webstorm, I get an exception:

import { React } from "react";
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:1072:16)
    at Module._compile (internal/modules/cjs/loader.js:1122:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
Silviu-Marian :

First of all, let's make it clear that WebStorm is going to act as a wrapper around a JS interpreter (any interpreter you chose) and pipe any output back to you.

I'm going to stick to node 12.x.x for this example based on the ESM imports error you're getting, but you can also run Chrome in headless mode, phantomjs or anything else really, although it will be some work to pipe output.

Secondly, you will need to have installed react, either globally or accessible by node's module resolution scheme (node_modules as sibling, or any parent folder).

Finally, you need to pick a modules standard. There's an official one suitable for the browser where module resolution (importing react) is different, and also node's own, which has plenty of reading around it over here. Since we're using node, we can't pick the first one, but can only emulate it via esm or babel.

The line is gray with all this but we're still in vanilla JS territory here alright.

Now, we need to tell the interpreter that we want to be in a module scope with all our code, not send all exports to global. In the browser this is <script type="module">, but in node we either emulate it all with esm or babel, or we do this:

"C:\Program Files\nodejs\node.exe" --experimental-modules C:\Users\me\.WebStorm2019.3\config\scratches\scratch_4.mjs

Notice here that the file extension absolutely needs to be mjs. If it's not, that's a SyntaxError because we cannot use import statement outside a module.

If you choose esm, in my opinion that's a tad better because it also allows the .js extension:

"C:\Program Files\nodejs\node.exe" -r esm C:\Users\me\.WebStorm2019.3\config\scratches\scratch_4.js

With all the homework now done here is the configuration summary for WebStorm

configuration summary for WebStorm

sample output

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=301903&siteId=1