Convert old NodeJs applications to ES6 modules · Matteo Mattei (2024)

Convert old NodeJs applications to ES6 modules · Matteo Mattei (1)23 Dec 2021 Convert old NodeJs applications to ES6 modules · Matteo Mattei (2)Matteo Mattei Convert old NodeJs applications to ES6 modules · Matteo Mattei (3) nodejs Convert old NodeJs applications to ES6 modules · Matteo Mattei (4)

Nowadays every Nodejs application should be converted to ES6 module because it brings several benefits:

  • Modules may be executed any number of times, but are loaded only once, thus improving performance.
  • Module scripts may be shared by multiple applications.
  • Modules help identify and remove naming conflicts.

The biggest difference between standard javascript library and an ES6 module is how we include a library (which can be either within your project or external). The standard classic way is to use const library = require(‘library-name’) but with ES6 modules we have to use import library from ‘library-name’.

In order to support the import keyword you have to add the following line to the package.json of your application:

"type": "module"

In this way you are telling npm that your application is a pure ES6 module.

Then you have to change all require(xxx) statements with import xxx from ‘yyy’. In case you want to use an external library which is not a pure ES6 module you can always include it with this syntax:

import theNameYouWant from 'official-library-name'

In case you want to use a library which is placed inside your application you can use this syntax:

import theNameYouWant from './path/to/mylibrary.js'

And mylibrary.js can export a default object with all functions like this:

import axios from 'axios';export default {run: function(){console.log('run');},sum: function(x, y){console.log(`Sum is ${x+y}`);},get: async function(){return await axios.get('https://github.com/matteomattei/matteomattei.github.io/raw/master/public/logo_professtional.jpg');}}

And can be used in this way:

import mylib from './path/to/mylibrary.js'mylib.run(); // prints 'run'mylib.sum(2,3); // prints 'Sum is 5';let getResult = await mylib.get();console.log(Buffer.from(getResult.data).length); // prints the size of the image

You can also export single functions from your library like this:

import axios from 'axios';export function run() { console.log("run");}export function sum(x, y) { console.log(`Sum is ${x + y}`);}export async function get() { return await axios.get( "https://github.com/matteomattei/matteomattei.github.io/raw/master/public/logo_professtional.jpg" );}

In this case you have to use it in this way:

import * as mylib from './path/to/mylibrary.js'mylib.run(); // prints 'run'mylib.sum(2,3); // prints 'Sum is 5';let getResult = await mylib.get();console.log(Buffer.from(getResult.data).length); // prints the size of the image

Otherwise you can selectively import only the function you need:

import {run, sum, get} from './path/to/mylibrary.js'run(); // prints 'run'sum(2,3); // prints 'Sum is 5';let getResult = await get();console.log(Buffer.from(getResult.data).length); // prints the size of the image

Remember:

  • You have to add type: “module” to your package.json file.
  • You can use await directly in your main module without a wrap of an async function.
  • Your code must be implicitly strict.
Convert old NodeJs applications to ES6 modules · Matteo Mattei (2024)
Top Articles
What is Strategic Asset Allocation?
AXA Health Insurance UK | Usay Compare
Ffxiv Act Plugin
Truist Park Section 135
Top 10: Die besten italienischen Restaurants in Wien - Falstaff
Best Transmission Service Margate
Naturalization Ceremonies Can I Pick Up Citizenship Certificate Before Ceremony
How to Type German letters ä, ö, ü and the ß on your Keyboard
Pj Ferry Schedule
Infinite Campus Parent Portal Hall County
Dityship
Weekly Math Review Q4 3
Used Wood Cook Stoves For Sale Craigslist
Gfs Rivergate
Craigslist Pets Longview Tx
2021 Lexus IS for sale - Richardson, TX - craigslist
Craigslist Blackshear Ga
Finger Lakes Ny Craigslist
Star Wars: Héros de la Galaxie - le guide des meilleurs personnages en 2024 - Le Blog Allo Paradise
White Pages Corpus Christi
Costco Great Oaks Gas Price
Keci News
Military life insurance and survivor benefits | USAGov
Teen Vogue Video Series
Lost Pizza Nutrition
Globle Answer March 1 2023
Synergy Grand Rapids Public Schools
Jesus Revolution Showtimes Near Regal Stonecrest
Wrights Camper & Auto Sales Llc
Ocala Craigslist Com
manhattan cars & trucks - by owner - craigslist
Imagetrend Elite Delaware
Mastering Serpentine Belt Replacement: A Step-by-Step Guide | The Motor Guy
Gina's Pizza Port Charlotte Fl
Housing Assistance Rental Assistance Program RAP
Autopsy, Grave Rating, and Corpse Guide in Graveyard Keeper
Drabcoplex Fishing Lure
Gateway Bible Passage Lookup
Japanese Big Natural Boobs
Todd Gutner Salary
Funkin' on the Heights
Lawrence E. Moon Funeral Home | Flint, Michigan
Costco The Dalles Or
Backpage New York | massage in New York, New York
Movie Hax
Ewwwww Gif
Understanding & Applying Carroll's Pyramid of Corporate Social Responsibility
Home | General Store and Gas Station | Cressman's General Store | California
Houston Primary Care Byron Ga
Bumgarner Funeral Home Troy Nc Obituaries
Naughty Natt Farting
Latest Posts
Article information

Author: Trent Wehner

Last Updated:

Views: 5818

Rating: 4.6 / 5 (76 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Trent Wehner

Birthday: 1993-03-14

Address: 872 Kevin Squares, New Codyville, AK 01785-0416

Phone: +18698800304764

Job: Senior Farming Developer

Hobby: Paintball, Calligraphy, Hunting, Flying disc, Lapidary, Rafting, Inline skating

Introduction: My name is Trent Wehner, I am a talented, brainy, zealous, light, funny, gleaming, attractive person who loves writing and wants to share my knowledge and understanding with you.