Node.js module import help?

Question: I’m trying to organize my code so that objects are each in their own module. I got an error trying to use require (“require() of ES Module [my module path and filename] not supported. Instead change the require of [my module path and filename] to a dynamic import() which is available in all CommonJS modules.”) so I switched to using import and got another error (“To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.”). I’m already using the .mjs extension, but no worries, I added "type": "module" to package.json and that error also went away.

However, now I need to use an npm package. I’ve successfully installed the npm package, but when I try using require for that I’m getting this new error: “require is not defined in ES module scope, you can use import instead. This file is being treated as an ES module because it has a ‘.js’ file extension and [my package.json path and filename] contains “type”: “module”. To treat it as a CommonJS script, rename it to use the ‘.cjs’ file extension.”

I assume giving a different extension to an npm package file is probably off limits, so I guess I have to use import, but what is the right syntax for importing an npm package?

Repl link: https://replit.com/@joeyday/Cube-Solver

1 Like

Hey @joeyday welcome to the forums!

Lets say you are trying to import useState from react. Assuming you already installed the package from the shell you do it like this.

// Before ES6
const { useState } = require('react');
// After ES6
import useState from "react"
2 Likes

Amazing. I was trying import * as Cube from 'cubejs' and that wasn’t working. I also tried import { Cube } from 'cubejs' and that gave me a different weird error. The fix was indeed import Cube from 'cubejs'. Thanks so much for your help!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.