Best Website-BuildersBest Website-Builders
    What's Hot

    ‘Vanderpump Rules’ star Raquel Levis intends to drop Shaana Shay’s restraining order

    March 24, 2023

    Apple Watch Series 8 Vs Fitbit Sense 2: Which Smartwatch Is Best?

    March 24, 2023

    Framework’s DIY laptop puts Apple and Microsoft to shame with upgradeable CPUs and makes me excited for the future

    March 24, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Federal agencies still use cell phones as tracking beacons

      March 24, 2023

      41 House Builders Score 5 Stars for Customer Satisfaction – Show House

      March 24, 2023

      CAS earns Chief Secretary or better in new review

      March 24, 2023

      Determining the survival benefit of postoperative radiation therapy in patients with pT1-3N1M0 rectal cancer who underwent total mesorectal resection: a retrospective analysis BMC Gastroenterology

      March 23, 2023

      What you need to know about CSS Profiles

      March 23, 2023
    • Joomla

      Save Thousands On Web Hosting With iBrave, Now Only $86

      March 23, 2023

      In Vitro Transcription Services Market Analysis, Research Study with Shanghai Zhishuo Biotechnology Co., Yunzhou Biotechnology Co.

      March 23, 2023

      Current state of UK content management systems

      March 23, 2023

      Reseller Hosting Business: Important Q&A

      March 21, 2023

      Web Hosting: 8 Elements Every Entrepreneur Should Look For

      March 20, 2023
    • PHP

      ‘Vanderpump Rules’ star Raquel Levis intends to drop Shaana Shay’s restraining order

      March 24, 2023

      Beyoncé announces new fashion collaboration with Balmain

      March 24, 2023

      All shower trends on TikTok: 12 products to try

      March 24, 2023

      Why do I get gas and bloating on air travel?

      March 24, 2023

      Ben Affleck and Matt Damon’s shared bank account

      March 24, 2023
    • UX

      Q&A with Debbie Levitt on UX research and design — Visual Studio Magazine

      March 24, 2023

      New book examines effects of European arrivals in Mexico: UNM Newsroom

      March 24, 2023

      When and how to use HTML sitemaps for SEO and UX

      March 24, 2023

      What is an infographic resume? | | Career

      March 24, 2023

      A Comprehensive Approach to Accuracy and Efficiency

      March 24, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Framework’s DIY laptop puts Apple and Microsoft to shame with upgradeable CPUs and makes me excited for the future

      March 24, 2023

      New Python info-stealing malware uses Unicode to avoid detection

      March 24, 2023

      4 reasons Rescue is the remote support champion

      March 24, 2023

      Intel exits 5G and LTE PC business

      March 24, 2023

      These next-level phishing scams use PayPal or Google Docs to steal your data

      March 24, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » Introduction to JavaScript’s module system
    JavaScript

    Introduction to JavaScript’s module system

    websitebuildersnowBy websitebuildersnowSeptember 25, 2022No Comments6 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    The concept of modules comes from the modular programming paradigm. This paradigm proposes that software should be composed of discrete, interchangeable components called “modules” by dividing program functionality into stand-alone files that either operate independently or can be combined in an application. .

    Modules are stand-alone files that encapsulate code to implement specific functionality and promote reusability and organization.

    Here we discuss the module systems used in JavaScript applications, including the module pattern, the CommonJS module system used in most Node.js applications, and the ES6 module system.


    module pattern

    Before the introduction of native JavaScript modules, the module design pattern was used as a module system for scoping variables and functions to a single file.

    This was implemented using an immediately-invoked function expression, commonly known as an IIFE. IIFEs are non-reusable functions that execute as soon as they are created.

    The basic structure of IIFE is:

     (function () {
      
    })();
      
    (() => {
      
    })();
      
    (async () => {
      
    })();

    The code block above describes an IIFE used in three different contexts.

    IIFE was used because variables declared within a function are scoped to the function, are only accessible within the function, and can return data by the function (making them publicly accessible). ) because

    for example:

     const foo = (function () {
      const sayName = (name) => {
        console.log(`Hey, my name is ${name}`);
      };

      
      return {
        callSayName: (name) => sayName(name),
      };
    })();
    foo.callSayName("Bar");

    The above code block is an example of how modules were written before native JavaScript modules were introduced.

    The code block above contains an IIFE. The IIFE contains functions that make it accessible by returning it. All variables declared with IIFE are protected from global scope. So the method (say the name) can only be accessed via public functions. callSayName.

    Notice that the IIFE is saved in a variable. PhewThis is because if the variable does not point to a location in memory, it will not be accessible after the script runs. This pattern can occur due to JavaScript closures.

    CommonJS module system

    The CommonJS module system is a module format defined by the CommonJS group to solve the JavaScript scoping problem by having each module run in its own namespace.

    The CommonJS module system works by forcing modules to explicitly export the variables they expose to other modules.

    This module system was created for server-side JavaScript (Node.js) and is not supported by default in browsers.

    To implement CommonJS modules in your project, you must first initialize NPM in your application by running the following command:

     npm init -y

    Variables exported according to the CommonJS module system can be imported as follows:

     


    const installedImport = require("package-name");


    const localImport = require("/path-to-module");

    The module is imported into CommonJS. Required This statement reads a JavaScript file, executes the read file, and export object.of export object contains all exports available in the module.

    You can export variables according to the CommonJS module system using named exports or default exports.

    named export

    A named export is an export identified by an assigned name. Named exports allow multiple exports per module, unlike default exports.

    for example:

     

    exports.myExport = function () {
      console.log("This is an example of a named export");
    };

    exports.anotherExport = function () {
      console.log("This is another example of a named export");
    };

    The code block above exports two named functions (my export and another export) by attaching them to export object.

    Similarly, you can export a function like this:

     const myExport = function () {
      console.log("This is an example of a named export");
    };

    const anotherExport = function () {
      console.log("This is another example of a named export");
    };

    module.exports = {
      myExport,
      anotherExport,
    };

    In the code block above, export Opposes the specified function.can only be assigned export through an object to a new object module object.

    The code will throw an error if you try to run it this way.

     
    exports = {
      myExport,
      anotherExport,
    };

    There are two ways to import named exports:

    1. Import all exports as one object and access them individually using dot notation.

    for example:

     

    const foo = require("./main");

    foo.myExport();
    foo.anotherExport();

    2. Explode the export from export object.

    for example:

     

    const { myExport, anotherExport } = require("./main");

    myExport();
    anotherExport();

    What all import methods have in common is that they must be imported using the same names they were exported with.

    Default export

    The default export is the export identified by any name. You can only have one default export per module.

    for example:

     
    class Foo {
      bar() {
        console.log("This is an example of a default export");
      }
    }

    module.exports = Foo;

    In the code block above, we are exporting a class (Fu) by reassigning export object to it.

    Importing default exports is similar to importing named exports, except that you can import using any name.

    for example:

     
    const Bar = require("./main");

    const object = new Bar();

    object.bar();

    In the code block above, the default exports are named. barbut you can use any name.

    ES6 module system

    The ECMAScript Harmony module system, commonly known as ES6 modules, is the official JavaScript module system.

    ES6 modules are supported by browsers and servers, but require a little configuration before they can be used.

    In the browser you have to specify type As module In the script import tag.

    It seems like:

     
    <script src="./app.js" type="module"></script>

    In Node.js you have to set type To module your package.json File.

    It seems like:

     
    "type":"module"

    You can also export variables using the ES6 module system using named exports or default exports.

    named export

    Similar to named imports in CommonJS modules, multiple exports per module are possible, identified by an assigned name.

    for example:

     
    export const myExport = function () {
      console.log("This is an example of a named export");
    };

    export const anotherExport = function () {
      console.log("This is another example of a named export");
    };

    In the ES6 module system, before variables export keyword.

    A named export can be imported into another module in ES6 in the same way as in CommonJS.

    • Destructuring required exports from export object.
    • Import all exports as a single object and access them individually using dot notation.

    Below is an unstructured example.

     
    import { myExport, anotherExport } from "./main.js";

    myExport()
    anotherExport()

    Here’s an example that imports an entire object:

     import * as foo from './main.js'

    foo.myExport()
    foo.anotherExport()

    In the code block above, an asterisk (*) means “all”.of As Keyword is export In this case, it opposes the string that follows it. Phew.

    Default export

    Similar to CommonJS default exports, you can only have one default export per module, identified by any name you choose.

    for example:

     
    class Foo {
      bar() {
        console.log("This is an example of a default export");
      }
    }

    export default Foo;

    The default export is Default Keyword after export The keyword is followed by the name of the export.

    Importing default exports is similar to importing named exports, except that you can import using any name.

    for example:

     
    import Bar from "./main.js";

    mixed export

    The ES6 module standard allows a module to have both default and named exports, unlike CommonJS.

    for example:

     
    export const myExport = function () {
      console.log("This is another example of a named export");
    };

    class Foo {
      bar() {
        console.log("This is an example of a default export");
      }
    }

    export default Foo;

    Importance of modules

    Dividing your code into modules not only makes your code easier to read, it also makes it more reusable and maintainable. Using modules in JavaScript also makes your code less error prone, as all modules run in strict mode by default.



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleMariposa County Daily Sheriff and Reservation Report for Thursday, September 22, 2022
    Next Article Top website builders for WordPress in 2022
    websitebuildersnow
    • Website

    Related Posts

    Four ways to remove specific items from a JavaScript array

    March 24, 2023

    Toolkit enables JavaScript developers to program embedded devices

    March 23, 2023

    What Will Pass This Year’s Minnesota Legislature and What Will Happen

    March 23, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    ‘Vanderpump Rules’ star Raquel Levis intends to drop Shaana Shay’s restraining order

    March 24, 2023

    Apple Watch Series 8 Vs Fitbit Sense 2: Which Smartwatch Is Best?

    March 24, 2023

    Framework’s DIY laptop puts Apple and Microsoft to shame with upgradeable CPUs and makes me excited for the future

    March 24, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.