Why publish Node.js packages to npm using Babel/Webpack?

By: (plus.google.com) +David Herron; Date: February 22, 2019

Tags: Node.JS » JavaScript

Babel and Webpack are widely used tools for front-end-engineering. Between the two you can code JavaScript using the latest ES2016/2017/2018/etc features, with multiple modules, and transpile it down to a simple JavaScript file using ES5 syntax. This is a big step forward in JavaScript tooling. But, since Node.js natively supports a huge fraction of ES2016/2017/2018/etc features, why do Node.js programmers even need to know Babel/Webpack? After reading a tutorial on using Babel/Webpack with Node.js modules, I have the beginning of an inkling for why.

For this post we'll be referring to the following Medium post, and associated Github repository. The tutorial breezes through using Babel and Webpack to publish a Node.js module to npm. This is a very helpful tutorial if, like me, Webpack is totally mystifying.

The tutorial contains a few ES6 modules that implement a couple simple functions inspired by a Python function. Because they're ES6 modules the code is written with import and export keywords rather than assigning functions to the module.exports object as we do with traditional Node.js/CommonJS modules.

All that's fine, and and Node.js programmers can directly use ES6 modules using import and export syntax. The problem is that Node.js does not support using require, the traditional Node.js way of consuming a module, to load an ES6 module.

To support that use-case, loading an ES6 module in a CommonJS module, look at: (www.npmjs.com) https://www.npmjs.com/package/esm -- While that module does the job it is not fair to the consumers of your Node.js module to require them to use a third-party module to then load your module.

Three rationales:

  1. Suppose you want to code using ES6 module syntax, but want to use the resulting module in a CommonJS module? Node.js does not support require('path/to/module.mjs'), meaning that a CommonJS module cannot load an ES6 module using require.
  2. Suppose you totally despise the .mjs file extension required to use ES6 modules with Node.js. Babel can be used to rewrite .js files containing an ES6 module into a .js file containing a CommonJS module.
  3. Suppose your management requires using an older Node.js release that lacks ES6 module support? You can write code with all the latest goodness, then use Babel to transpile the code to ES5 syntax until your management gets a clue.

Between those three, we have sufficient rationale to use Babel for publishing a Node.js module to the npm repository.

But... why use Webpack? I'm still a little mystified. The only rationale I can come up with is obfuscation. To see why let's go through the tutorial and the results.

This helped me a lot to have a beginning of an inkling how Webpack is used. You can follow this and see the entrypoint to the module is src/index.js, that Webpack is to package anything referred from that file, the output is put into dist/index.js which will be written in CommonJS format.

const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    path: path.resolve('dist'),
    filename: 'index.js',
    libraryTarget: 'commonjs2',
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        exclude: /(node_modules)/,
        use: 'babel-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.js'],
  },
};

Then, the result of that is:

module.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t);var n=(e,t)=>Boolean(Math.round(Math.random()));var o=(e,t)=>Math.random()*(e-t)+t;var u=(e,t)=>~~(Math.random()*(e-t+1)+t);t.default=((e=1,t=0,r={})=>!0===r.float?o(e,t):r.bool?n(e,t):u(e,t))}]);

I dunno about you, but I have a hard time following this. I even manually cleaned this up hoping that would help, but the cleaned up code was still hard to follow.

If you want to obfuscate the module for whatever reason, this is a great way to go. Me? I don't care much about obfuscating the Node.js modules I publish to npm.

Another possible rationale for using Webpack is its guarantee of minimizing the code. You can see some code minimization here, with all the single-letter variable and function names. But Webpack does even more by leaving out any unreferenced code as it packages your code.

This blob shown here is the result of smushing together four separate modules. During the smushing process, if Webpack were to find a function that's not referenced from anywhere it'll simply leave out that function. Therefore your module has two execution-time advantages: a) faster parsing time because the code is all scrunched up, b) minimized memory footprint because it's all one module and because unneeded code is left out.

« Javascript (specifically Node.JS) for server-side web application programming How to fix Node.js require returning an empty module object »
2016 Election 2018 Elections Acer C720 Ad block Affiliate marketing Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Flexgate Apple Hardware History Apple Hardware Mistakes Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital audio Digital Nomad Digital Photography Direct Attach Storage Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DuckDuckGo DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake Advertising Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey Gig Economy git Github GitKraken Gitlab GMAIL Google Google Adsense Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing Incognito Mode InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent jQuery Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X Mac Pro MacBook Pro Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online Make Money with Gigs March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NSA NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online News Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Private E-mail server Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Renewable Energy Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Search Engines Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Video editing Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Website Business Models Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Adpocalypse YouTube Monetization