Lær det grundlæggende i JavaScript-modulsystemet, og opbyg dit eget bibliotek

På det seneste har vi alle hørt meget om “JavaScript-moduler”. Alle undrer sig sandsynligvis over, hvad de skal gøre med dem, og hvordan spiller de endda en vigtig rolle i vores daglige liv ...?

Så hvad pokker er JS-modulsystemet? ?

Da JavaScript-udviklingen bliver mere og mere udbredt, bliver navneområder og afhængigheder meget sværere at håndtere. Der er udviklet forskellige løsninger til at håndtere dette problem i form af modulsystemer.

Hvorfor er det vigtigt at forstå JS-modulsystemet?

Lad mig fortælle dig en historie.

At fortælle historier er lige så grundlæggende for mennesker som at spise. Mere faktisk, for mens mad får os til at leve, er historier det, der gør vores liv værd at leve - Richard Kearney

Hvorfor taler jeg endda om alle disse ting?

Så mit daglige job er at designe og arkitektprojekter, og jeg indså hurtigt, at der var mange almindelige funktioner, der kræves på tværs af projekter. Jeg endte altid med at kopiere og indsætte disse funktionaliteter i nye projekter igen og igen.

Problemet var, at når et stykke kode ændrede sig, var jeg nødt til manuelt at synkronisere disse ændringer på tværs af alle mine projekter. For at undgå alle disse kedelige manuelle opgaver besluttede jeg at udtrække de almindelige funktioner og komponere en npm-pakke ud af dem. På denne måde ville andre på holdet kunne genbruge dem som afhængigheder og simpelthen opdatere dem, hver gang en ny udgivelse blev rullet ud.

Denne tilgang havde nogle fordele:

  • Hvis der var en eller anden ændring i kernebiblioteket, skulle der kun foretages en ændring ét sted uden at omformulere alle applikationernes kode til den samme ting.
  • Alle applikationer forblev synkroniseret. Hver gang der blev foretaget en ændring, var alle applikationer bare nødvendige for at køre kommandoen "npm update".

Så næste skridt var at udgive biblioteket. Ret? ?

Dette var den sværeste del, fordi der var en masse ting, der hoppede rundt i mit hoved, som:

  1. Hvordan får jeg træet til at ryste?
  2. Hvilke JS-modulsystemer skal jeg målrette mod (commonjs, amd, harmoni).
  3. Skal jeg transponere kilden?
  4. Skal jeg samle kilden?
  5. Hvilke filer skal jeg udgive?

Alle af os har haft denne slags spørgsmål boblende i hovedet, mens vi oprettede et bibliotek. Ret?

Jeg vil prøve at adressere alle ovenstående spørgsmål nu.

Forskellige typer JS-modulsystemer?

1. CommonJS

  • Implementeret af node
  • Bruges til serversiden, når du har moduler installeret
  • Ingen indlæsning af runtime / async-modul
  • import via “ kræve
  • eksporter via “ module.exports
  • Når du importerer, får du et objekt tilbage
  • Intet træ ryster, for når du importerer, får du et objekt
  • Ingen statisk analyse, da du får et objekt, så ejendomssøgning er ved kørsel
  • Du får altid en kopi af et objekt, så ingen live ændringer i selve modulet
  • Dårlig cyklisk afhængighedsstyring
  • Enkel syntaks

2. AMD: Definition af Async-modul

  • Implementeret af RequireJs
  • Bruges til klientsiden (browser), når du ønsker dynamisk indlæsning af moduler
  • Import via "kræv"
  • Kompleks syntaks

3. UMD: Definition af universalt modul

  • Kombination af CommonJs + AMD (dvs. syntaks for CommonJs + asynkronisering af AMD)
  • Kan bruges til begge AMD / CommonJs- miljøer
  • UMD skaber hovedsagelig en måde at bruge en af ​​de to på, samtidig med at den understøtter den globale variabeldefinition. Som et resultat er UMD-moduler i stand til at arbejde på både klient og server .

4. ECMAScript Harmony (ES6)

  • Anvendes til både server / klient side
  • Kørselstid / statisk indlæsning af moduler, der understøttes
  • Når du importerer, får du bindingsværdien tilbage (faktisk værdi)
  • Import via "import" og eksport via "eksport"
  • Statisk analyse - Du kan bestemme import og eksport på kompileringstidspunktet (statisk) - du skal kun se på kildekoden, du behøver ikke at udføre den
  • Rysteligt træ på grund af statisk analyse understøttet af ES6
  • Få altid en faktisk værdi, så live ændringer i selve modulet
  • Bedre cyklisk afhængighedsstyring end CommonJS

Så nu ved du alt om forskellige typer JS-modulsystemer, og hvordan de har udviklet sig.

Selvom ES Harmony- modulsystemet understøttes af alle værktøjer og moderne browsere, ved vi aldrig, når vi udgiver biblioteker, hvordan vores forbrugere kan bruge dem. Så vi skal altid sikre, at vores biblioteker fungerer i alle miljøer.

Lad os dykke dybere ned og designe et prøvebibliotek for at besvare alle de spørgsmål, der er relateret til udgivelse af et bibliotek på den rigtige måde.

I’ve built a small UI library (you can find the source code on GitHub), and I’ll share all my experiences and explorations for transpiling, bundling, and publishing it.

Here we have a small UI library which has 3 components: Button, Card, and NavBar. Let’s transpile and publish it step by step.

Best practices before publishing ?

  1. Tree Shaking ?
  • Tree shaking is a term commonly used in the context of JavaScript for dead-code elimination. It relies on the static structure of ES2015 module syntax, that is, import and export. The name and concept have been popularized by the ES2015 module bundler rollup.
  • Webpack and Rollup both support Tree Shaking, meaning we need to keep certain things in mind so that our code is tree shakeable.

2. Publish all module variants

  • We should publish all the module variants, like UMD and ES, because we never know which browser/webpack versions our consumers might use this library/package in.
  • Even though all the bundlers like Webpack and Rollupunderstand ES modules, if our consumer is using Webpack 1.x, then it cannot understand the ES module.
// package.json
{"name": "js-module-system","version": "0.0.1",...
"main": "dist/index.js","module": "dist/index.es.js",
...}
  • The main field of the package.json file is usually used to point to the UMD version of the library/package.
  • You might be wondering — how can I release the ES version of my library/package? ?

    M- odule feltet på p ackage.json bruges til at pege på E- S versionen af ​​biblioteket / pakken. Tidligere blev mange felter brugt som j s:next og j s:main , men m odule er nu standardiseret og bruges af bundlere som et opslag til S vbiblioteks- / pakkeversionen.

Mindre velkendt faktum: Webpack bruger resolution.mainfields til at bestemme, hvilke felter der package.jsoner markeret. Tip til ydeevne: Prøv altid at offentliggøre ESversionen af ​​dit bibliotek / pakke også, for alle moderne browsere understøtter nu ESmoduler. Så du kan transportere mindre, og i sidste ende vil du ende med at sende mindre kode til dine brugere. Dette øger din applikations ydeevne.

Så hvad er nu det næste? Transpilation eller bundling? Hvilke værktøjer skal vi bruge?

Ah, here comes the trickiest part! Let’s dive in. ?

Webpack vs Rollup vs Babel?

These are all the tools we use in our day to day lives to ship our applications/libraries/packages. I cannot imagine modern web development without them — #blessed. Therefore, we cannot compare them, so that would be the wrong question to ask! ❌

Each tool has it’s own benefits and serves different purpose based on your needs.

Let’s look at each of these tools now:

Webpack

Webpack is a great module bundler ? that is widely accepted and mostly used for building SPAs. It gives you all the features out of the box like code splitting, async loading of bundles, tree shaking, and so on. It uses the CommonJS module system.

PS: Webpack-4.0.0 alpha is already out ?. Hopefully with the stable release it will become the universal bundler for all types of module systems.

RollupJS

Rollup is also a module bundler similar to Webpack. However, the main advantage of rollup is that it follows new standardized formatting for code modules included in the ES6 revision, so you can use it to bundle the ES module variant of your library/package. It doesn’t support async loading of bundles.

Babel

Babel is a transpiler for JavaScript best known for its ability to turn ES6 code into code that runs in your browser (or on your server) today. Remember that it just transpiles and doesn’t bundle your code.

My advice: use Rollup for libraries and Webpack for apps.

Transpile (Babel-ify) the source or Bundle it

Again there’s a story behind this one. ?

I spent most of my time trying to figure out the answer to this question when I was building this library. I started digging out my node_modules to lookup all the great libraries and check out their build systems.

After looking at the build output for different libraries/packages, I got a clear picture of what different strategies the authors of these libraries might have had in mind before publishing. Below are my observations.

As you can see in the above image, I’ve divided these libraries/packages into two groups based on their characteristics:

  1. UI Libraries (styled-components, material-ui)
  2. Core Packages (react, react-dom)

If you’re a good observer ? you might have figured out the difference between these two groups.

UI Libraries have a dist folder that has the bundled and minified version for ES and UMD/CJSmodule systems as a target. There is a lib folder that has the transpiled version of the library.

Core Packages havejust one folder which has the bundled and minified version for CJS or UMD module system as a target.

But why is there a difference in build output of UI libraries and Core Packages? ?

UI Libraries

Imagine if we just publish the bundled version of our library and host it on CDN. Our consumer will use it directly in a t/> tag. Now if my consumer wants to use jus t the <;Button/> component, they have to load the entire library. Also, in a browser, there is no bundler which will take care of tree shaking, and we’ll end up shipping the whole library code to our consumer. We don’t want this.

import {Button} from "//unpkg.com/uilibrary/index.js";

Now if we simply transpile the src into lib and host the lib on a CDN, our consumers can actually get whatever they want without any overhead. “Ship less, load faster”. ✅

import {Button} from "//unpkg.com/uilibrary/lib/button.js";

Core Packages

Core packages are never utilized via the t/> tag, as they need to be part of main application. So we can safely release the bundled ver sion (UMD, ES) for these kinds of packages and leave the build system up to the consumers.

For example, they can use the UMD variant but no tree shaking, or they can use the ES variant if the bundler is capable of identifying and getting the benefits of tree shaking.

// CJS requireconst Button = require("uilibrary/button");
// ES importimport {Button} from "uilibrary";

But…what about our question: should we transpile (Babelify) the source or bundle it? ?

For the UI Library, we need to transpile the source with Babel with the es module system as a target, and place it in lib. We can even host the lib on a CDN.

We should bundle and minifythe source using rollup for cjs/umd module system and es module system as a target. Modify the package.json to point to the proper target systems.

// package.json
{"name": "js-module-system","version": "0.0.1",...
"main": "dist/index.js", // for umd/cjs builds"module": "dist/index.es.js", // for es build
...}

For core packages, we don’t need the lib version.

We just need to bundle and minifythe source using rollup for cjs/umd module system and es module system as a target. Modify the package.json to point to the proper target systems, same as above.

Tip: We can host the dist folder on the CDN as well, for the consumers who are willing to download the whole library/package via t/> tag.

How should we build this?

We should have different scripts for each target system in package.json . You can find the rollup config in the GitHub repo.

// package.json
{..."scripts": {"clean": "rimraf dist","build": "run-s clean && run-p build:es build:cjs build:lib:es","build:es": "NODE_ENV=es rollup -c","build:cjs": "NODE_ENV=cjs rollup -c","build:lib:es": "BABEL_ENV=es babel src -d lib"}...}

What should we publish?

  • License
  • README
  • Changelog
  • Metadata(main , module, bin) — package.json
  • Control through package.jsonfiles property

In package.json , the "files" field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. If you name a folder in the array, then it will also include the files inside that folder.

We will include the lib and dist folders in "files" field in our case.

// package.json
{..."files": ["dist", "lib"]...}

Finally the library is ready to publish. Just type the npm run build command in the terminal, and you can see the following output. Closely look at the dist and lib folders. ?

Wrap up

Wow! Where does the time go? That was a wild ride, but I sincerely hope it gave you a better understanding of the JavaScript Module system and how you can create your own library and publish it.

Just make sure you take care of the following things:

  1. Make it Tree Shakeable. ?
  2. Target at least ES Harmony and CJS module systems. ?
  3. Use Babel and Bundlers for libraries. ?
  4. Use Bundlers for Core packages. ?
  5. Set the module field of package.json to point to the ES version of your module (PS: It helps in tree shaking). ?
  6. Publish the folders which have transpiled as well as bundled versions of you module. ?

Trending this week ?

  1. Webpack-V4 alpha released. ?
  2. ParcelJs: Blazing fast, zero configuration web application bundler. ?
  3. Turbo: 5x faster than Yarn & NPM, and runs natively in-browser ?

Thanks to Juho Vepsäläinen and Lakshya Ranganath for their reviews & feedback, Sean T. Larkin and Tobias Koppers for sharing the insights of webpack at ReactiveConf, Addy Osmani for sharing workings of different JS module Systems in “Writing Modular JavaScript With AMD, CommonJS & ES Harmony”.

P.S. If you like this, make sure to recommend (by clap? ) , follow me on twitter, and share this with your friends!?