You can destructure when the export is an object.
// file1.js
export { foo, bar };
// index.js
import { foo } from './file1';You cannot destructure when the export is an object, and the export is the default:
// file1.js
export default { foo, bar };
// index.js
import { foo } from './file1'; // does not workWhen compiling a library written in ES6 into CommonJS (with Webpack or Rollup), and that library will eventually be imported into an ES6 module, you can use either export or export default.
// library.js
export default { modOne, modTwo }; // will be compiled to CJS
// otherLibrary.js
export { modOne, modTwo }; // will be compiled to CJS
// myfile.js
import { modOne } from 'library.js'; // works
import { modOne } from 'otherLibrary.js'; // worksWhen importing an ES6 library into a CommonJS module, the ES6 library should always use export instead of export default. That's so you can avoid having to reference the default key.
// library.js
export default { modOne, modTwo };
// otherLibrary.js
export { modOne, modTwo };
// myfile.js
import { modOne } from 'library.js'; // does not work
import { modOne } from 'otherLibrary.js'; // works
import library from 'library.js';
const { modOne } = library.default; // worksWhen a CommonJS module's exports is set to a single function or value, you must reference it in an ES6 module as if it's the default.
// library.js
function fooBar() {
console.log('hey');
}
module.exports = fooBar;
// myfile.js
import fooBar from 'library.js'; // works
import { fooBar } from 'library.js'; // does not workWhen compiling a library written in ES6 to CommonJS, do not use export default in addition to export. Consumers of the library will have to reference it using the default key.
// library.js
export default function modOne() { // will be compiled to CJS
console.log('hey');
}
export function modTwo() { // will be compiled to CJS
console.log('ho');
}
// myfile.js
const lib = require('./dist/bundle');
const { modTwo } = lib;
lib.default();
modTwo();When compiling a library written in ES6 to CommonJS, and the library has a single export default, you can reference it in CommonJS without curly braces.
// library.js
export default function modOne() { // will be compiled to CJS
console.log('hey');
}
// myfile.js
const lib = require('./dist/bundle');
lib();