How to import dotenv data and npm modules in script.js

Viewed 833

import * as dotenv from "dotenv";

ACCESS_TOKEN_KEY = dotenv.ACCESS_TOKEN_KEY

I tried to import data from .env and this error is thrown

"Uncaught SyntaxError: Cannot use import statement outside a module"

The same thing happened when I installed some npm packages and tried to import them

I've added an type attribute of module to my script tag

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

and now I get this error

"Uncaught TypeError: Failed to resolve module specifier "dotenv". Relative references must start with either "/", "./", or "../"."

If I use "/" or "./" to change the import path I get a new error

net::ERR_ABORTED 404 (Not Found)

Does enyone know what I'm doing wrong and how I can fix it?

2 Answers

As far as i know , you can initialize a script on package.json after you npm init. But you cant initialize npm on a script. In my point of view it doesnt make sense But for more info you can always read NPM DOCS

You do not need to require and load dotenv in your application code when you are using the ES module. Instead of using import, you need to use this solution.

$ node -r dotenv/config script.js

where -r means --require

Related