0

I have a slight problem with a basic Node.JS method. When I'm trying to use "require()' method to import any downloaded (with 'npm install ..) module/library, I get a Visual Studio Code message that asks 'to convert 'require'(which is a Common JS module) into ES. If I do it, it transforms 'require()' into 'import..' though I want keep using 'require()'. Why is it so ? I read somewhere that Common JS is already included in the Node.JS environment though.

Then, when trying to compile my index.js file (with 'node index.js'), I obviously get an error about 'require' not recognized method.

Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users...index.js from C:\Users...index.js not supported.

I tried then to install Webpack to fix this issue, but nothing change. I also kind of installed CommonJS (npm i common-js)..
Another common answer was to remove 'type':'module' from package.json file which normally should allow to use 'require', but I don't even have such a line in the file.

On top of that I've recently read that 'require' is not compatible with browser development tools (it's ok). But I'm trying to import a downloaded module/npm package in VSC terminal, not even in a browser.

As you understand I'm new to Node.JS, but I don't really get what's going on in this case...

vladix
  • 1
  • 1
  • 1. Webpack is used to build browser libraries, you don't need it. 2. *I get a Visual Studio Code message that asks...* it sounds like an option, you don't have to do that. 3. *I obviously get an error about 'require' not recognized method.* - it recognized `require`, the module you are trying to import just doesn't support it. `require` is older and libraries move to esm now – Konrad Dec 05 '22 at 18:32
  • thanks, I got it. I'm trying to import library 'chalk' now, import { chalk } from 'chalk' but I get an error 'SyntaxError: The requested module 'chalk' does not provide an export named 'chalk'. But I found in chalk module folder, in its index.js file that there is a line 'export default chalk', so basically it should work. – vladix Dec 05 '22 at 18:54
  • `export default` means that you have to import like that: `import chalk from 'chalk'`. Just `export` is imported like `import {chalk} from 'chalk'` https://stackoverflow.com/a/58103685/5089567 – Konrad Dec 05 '22 at 18:56
  • 1
    Thank you. It finally works ! Didn't know about this difference. – vladix Dec 05 '22 at 19:40

0 Answers0