Tuesday, January 19, 2021

When do we choose one export type vs another

Once you want to pull the logic into another file, you have to decide how you want to import it. There are a few options for how you want to import it:


ES6 Imports - if you want to use import AnimalApi from 'animal-api'

animal-api.js

export default {

    getDog: () => ....

    getCat: () => ....

    getGoat: () => ....

}


ES6 Destructured Import - if you want to use import { getDog, getCat, getGoat } from 'animal-api'


animal-api.js

export const getCat = () => ....

export const getDog = () => ....

export const getGoat = () => ....



CommonJS - if you want to use const AnimalApi = require('animal-api')

animal-api.js


module.exports = {

    getDog, getCat, getGoat

}


When would you choose one over the other?

If your app only needs to work in a browser, and only in the context of React (or Angular2+ or environment that uses ES6 modules), then you're fine with using an ES6 import.


If your lib is meant to be used in the browser, and you need to include it in a vanilla JS HTML app, you need to use a bundler like webpack to bundle your app as a lib.


If you use webpack and take advantage of code splitting and tree shaking, you can use ES6 Destructured imports. What this means is rather than include all of lodash in your app, you can only include the functions you want and you'll have a smaller built app.


If you're writing an app or a library that needs to run in BOTH the browser, and in node, then you'll need to produce a few different versions of your library: one meant for the browser (as a script tag), one as an es6 module, and one for using in node.



References:

https://www.intricatecloud.io/2020/02/creating-a-simple-npm-library-to-use-in-and-out-of-the-browser/


No comments:

Post a Comment