Prefer ES6-style exports over module.exports

JavaScript pattern

Converts CommonJS module.exports to ES6-style exports.


Apply with the Grit CLI
grit apply es6_exports

Transform direct exports

BEFORE
module.exports.king = '9';
AFTER
export const king = '9';

Transform default exports

BEFORE
async function createTeam() {
  console.log('cool');
}

const addTeamToOrgSubscription = () => console.log('cool');

module.exports = {
  createTeam,
  addTeamToOrgSubscription,
};
AFTER
export async function createTeam() {
  console.log('cool');
}

export const addTeamToOrgSubscription = () => console.log('cool');

Keep inline values intact

BEFORE
const king = '9';

module.exports = {
  king,
  queen: '8',
};
AFTER
export const king = '9';

export const queen = '8';

Transforms a mix of direct and default exports

BEFORE
const c1 = require('./mod1');
const c2 = require('./mod2');
const c3 = require('./mod3');
const myDefaultConst = require('./mod4').default;
const myRenamed = require('mod5').originalName;
const { sub1, sub2 } = require('mod5'); // not handled

module.exports = { c1, c2, c3, myDefaultConst, myRenamed, sub1, sub2 };
AFTER
export { default as c1 } from './mod1';
export { default as c2 } from './mod2';
export { default as c3 } from './mod3';
export { default as myDefaultConst } from './mod4';
export { originalName as myRenamed } from 'mod5';
const { sub1, sub2 } = require('mod5'); // not handled

export { sub1 };
export { sub2 };

Transforms method definition shorthand

BEFORE
const shorthand = 1;

module.exports = {
  shorthand,
  fn(args) {
    return 'impl';
  },
};
AFTER
export const shorthand = 1;

export function fn(args) {
  return 'impl';
}