Javascript: import/export vs require/exports

Javascript: import/export vs require/exports

In order to show the differences between ESM and CommonJS, I’ll be using 2 different files, that export the same variables and values.

esm.js

export default 'default_value';
export const foo = 'foo_value';
export let bar = 'bar_value';

cjs.js

module.exports = {
    default: 'default_value',
    foo: 'foo_value',
    bar: 'bar_value',
};

import * with ESM

As expected, this will import the entire ./test module, not just the default value. The default export will be present as a property on the Module object.

import * as all from './esm'

console.log(all)
// Object [Module] { foo: [Getter], bar: [Getter], default: 'default_export' }

import * with CJS

When using module.exports things get a little different. Instead of a Module object, we get a plain object.

import * as all from './cjs'

console.log(all)
// { default: 'default_export', foo: 'foo_value', bar: 'bar_value' }

import myvar with ESM

The result is just the default exported value.

import myvar from './esm'

console.log(myvar)
// default_export

import myvar with CJS

module.exports will not work with default exports, instead the entire module is returned as a plain object.

import myvar from './cjs' in this case does the same thing as import * as all from './cjs'.

import myvar from './cjs'

console.log(myvar)
// { default: 'default_export', foo: 'foo_value', bar: 'bar_value' }

import {foo} with ESM

import {foo} with CJS

Both methods yield the same thing.

import {foo, bar} from './esm'

console.log(foo, bar)
// foo_value bar_value
const {foo, bar} = require('./cjs')

console.log(foo, bar)
// foo_value bar_value

 

Leave a Reply

Your email address will not be published. Required fields are marked *