0

I'm trying to import wellknown in to my JavaScript file by doing import * as *wellknown* from "node/querystring"; but I keep getting this error:

Cannot use import statement outside a module

I have tried to change import to require, and I even added type module to my package.json file, but nothing helped.

I did my npm install in my console and it says up to date. I even tried to put it in to an <script>, but I couldn't figure out the src. I tried something like this:

<script type="module" src="node_modules/wellknown/wellknown.js"></script>.

How can I fix it?

This is my package.json file:

{
 "name": "app",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "node": "^17.7.2",
    "wellknown": "^0.5.0"
  }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hasbullah
  • 45
  • 5
  • Maybe it's my fault, but I entered your package.json and created an app.js with `import * as wellknown from "node/querystring";` did `npm install` and `node app.js` and I get `Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/root/app/node_modules/node/querystring' imported from /root/app/app.js`. So perhaps your instructions to reproduce can be adjusted so that I can easily reproduce your issue. – Wyck Apr 06 '22 at 13:46
  • @Wyck I think u need to npm install wellknown – hasbullah Apr 06 '22 at 13:48
  • `wellknown` is named in your package.json so `npm install` will install it. – Wyck Apr 06 '22 at 13:52

1 Answers1

0

Are you trying to access your wellknown dependency? If so, the way to do that would be var wellknown = require('wellknown');

import * as wellknown from "node/querystring"; will import every module in querystring as wellknown. The query string is legacy and won't likely work with new code.

For the script tag, the source has to be either a CDN version of the code needed, or you need to serve or expose your node_modules folder at root domain '/' for this approach to work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I'm just trying to use wkt function that is in the wellknown libIary and If do require I get the error message: "Uncaught ReferenceError: require is not defined at map.js:1:13" and when I go on top of require and hit alt enter I get a suggestion to change it into import – hasbullah Apr 06 '22 at 13:41
  • @hasbullah how are you trying to access this node module ? is it through vanilla js or a framework such as node or react? – Aayush Garg Apr 06 '22 at 13:43
  • @hasbullah by default require is not a valid command in client side javascript, i suggest you look into https://requirejs.org/ or some alternative. – Aayush Garg Apr 06 '22 at 13:44
  • its through vanilla js – hasbullah Apr 06 '22 at 13:44