• Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Post job
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

141
Views
Move from CommonJS to ESM's export/import

It might has been fully discussed but I can't find a perfect answer from either here or here.

Basically

  • CommonJS uses the require('./xx') syntax, while
  • ESM uses the import {stuff} from './xx' syntax

Here is how I've been doing the require when using CommonJS

  • require('apackage') or
  • require('./myfile')

I.e., I don't need to specify their extensions for either case.

But moving to ESM import, the import {stuff} from './myfile' is giving me the error of:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module

In here it shows how to move from CommonJS and do ESM import:

from

const colors = require("colors");         // Obj w/ all export fields
const { red, blue } = require("colors");  // Select fields from export obj

to

import colors from "colors";          // _Only_ `default` export (`{ green }`)
import { red, blue } from "colors";   // Other named exports

But is it possible for me not to specify their extensions for my own files as well? Otherwise,

  • it will be inconsistent between importing 'apackage` or './myfile',
  • lots of unnecessary work for me to add their extensions to my current imports
  • and need to force me to change again if I decided to switch their extensions between js and mjs,
over 1 year ago ยท Juan Pablo Isaza
Answer question
Find remote jobs