Search code examples
javascriptnode.jsreactjsimportejs

How to use module type in ejs?


I want to import react in ejs it shows cannot use import statement outside module.

import React from react

When I execute this ^^^ I get error cannot use import statement outside module.

const {React} = require("react")

When I run this ^^^ it gives me error require is not defined...


Solution

  • You need to set your script type as module to be able to use import statement / ES Module :

    If you are using node.js, you have to edit your package.json and set :

    {
        "type": "module",
    }
    

    Else, if you import your js script from an html balise you have to set (almost the same thing) :

    <script src="app.js" type="module" ></script>
    

    This will enable the use of import inside app.js