mithelan
mithelan

Reputation: 190

When I run a JavaScript file in WebStorm, says as cannot import statement outside module

Error says as this **import React, {Component} from 'react';

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
    at internal/main/run_enter code heremain_module.js:17:11**

Upvotes: 2

Views: 3249

Answers (2)

lena
lena

Reputation: 93908

Looks as if you are trying to run your React application with Node.js, by right-clicking your component .js file is choosing Run. This is not supposed to work; you have to transpile/build your application, start a server it's hosted on and then open the server URL in browser. For applications created with create-react-app, please follow the instructions from https://www.jetbrains.com/help/webstorm/2020.1/react.html#react_running_and_debugging

Upvotes: 4

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

I am assuming you are trying to create your react app from scratch without using create-react-app cli. In that case, the ES6 imports and exports won't work because node.js doesn't support these imports/exports out of the box. They currently follow CommonJS module system. For you to achieve ES6 imports/exports you have to use babel to transpile your code from ES6 to ES5. Or according to your node version (newer version typically), there might be couple of things you can try, as mentioned in the following excellent answer on stackoverflow itself:-

https://stackoverflow.com/a/39436580/8130690

Upvotes: 1

Related Questions