Home  >  Article  >  Web Front-end  >  JavaScript Essentials: Part 7

JavaScript Essentials: Part 7

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-02 22:31:02468browse

JavaScript Essentials: Part 7

This is the 7th part of this JavaScript Series (as a part of the whole) and in this part, we will look at how to break down our projects into small pieces so they are manageable. We will create some sort of separation of concerns, making our project appealing and easy to navigate. In all things, there are a beautiful part and of course the ugly part. So, don't overdo it. Do it when it needs to be done.

As mentioned earlier, our focus here is to break some part of our project into a separate file, export it, and then import it into our "main app". There are at the moment two ways to do this in JavaScript. Using the commonjs approach and also the ES6's modular approach. They are all great and we will look at both.

CommonJs

The import and export with commonjs is the default when not specified. That is how we could do, const readline = require("readline");. readline is a built-in package. We can use this approach on the third-party packages or modules written in our project.

  • Import with commonjs is done with const someVarNameForTheModule = require("modNameOrPath");.
  • We export by doing, module.exports = thingToExportOrStructuredObjectToExport.

Project

Let's kick off with a project to perform some math. We will create functions to add and subtract. Just these two.

  • Create a project folder, cmodule: cd ~/Projects && mkdir cmodule && cd cmodule
  • Initial the node project by doing, npm init -y
  • You can choose to add, "type": "commonjs" to the package.json file. I am saying you can choose because that is the default.
  {
    "name": "cmodule",
    "version": "1.0.0",
    "main": "index.js",
    "type": "commonjs",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": ""
  }
  • Create two files, lib.js and main.js: touch lib.js main.js
  • Implement the body for the add function in the lib.js
  function add(x, y) {
    // return the sum of x and y
  }
  • Now that we have the function implemented, we have to export it to be used in our main.js. To export, we use module.exports = functionName. In our case, we do module.exports = add.
  module.exports = add;
  • Here the entirety of lib.js is just the add function. We exported lib.js as the add function. So we can import it as, const someName = require("./lib");
  • In the main.js, we will import the lib.js file and make use of the add function.
  const lib = require("./lib");
  // we did, "./lib", "dot slash lib", because main.js and lib.js are in the same folder.

  console.log(lib(1, 2));
  • Let's add the subtraction function
  function sub(x, y) {
    // returns the difference x and y
  }
  • You are supposed to implement these functions yourself ?

  • The question is, how do we export sub? Try it and access it inside main.js

  • Know that, when we do, module.exports = X, X is exported as a whole module so when we import const moduleName = require("moduleName");, we directly get access to X. So we can not export another value with this same approach.

  • In a case such as this, we can export both add and sub by exporting them as a group (object).

  {
    "name": "cmodule",
    "version": "1.0.0",
    "main": "index.js",
    "type": "commonjs",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": ""
  }
  • Now when we import in main.js we can do
  function add(x, y) {
    // return the sum of x and y
  }
  • The lib module is exported as an object so we can do, moduleName.add and moduleName.sub.

  • We can also import by doing by destructuring, const { add, sub } = require("./lib");

  module.exports = add;
  • There is another way to do multiple exports
  const lib = require("./lib");
  // we did, "./lib", "dot slash lib", because main.js and lib.js are in the same folder.

  console.log(lib(1, 2));

Or

  function sub(x, y) {
    // returns the difference x and y
  }
  • exports.alias = someThing and exports.someThing= someThing or also works like modules.exports = { someThing }. I'd usually choose the exports.alias = someThing because, the module.exports = { ... } could extra lines.

ES Module

The import and export with the ES module style is not the default currently and as such must be specified explicitly by setting the type property to "module" in the package.json file. In this case, we would be able to do, import readline from "readline"; instead of const readline = require("readline");. We replaced the const with import, the = and require with from.

  • ES module import is done with import someVarNameForTheModule from "modNameOrPath";.
  • We export by doing, export default thingToExportOrStructuredObjectToExport or export thingToExportOrStructuredObjectToExport.

Project

We will build a similar project using the ES module style of import and export. We will create functions to add and subtract just as we did previously. So you can copy and paste it this time.

  • Create a project folder, emodule: cd ~/Projects && mkdir emodule && cd emodule
  • Initial the node project: npm init -y
  • Add, "type": "module" to the package.json file.
  module.exports = { add, sub };
  • Create two files, lib.js and main.js: touch lib.js main.js

  • Implement the body for the add in the lib.js

  {
    "name": "cmodule",
    "version": "1.0.0",
    "main": "index.js",
    "type": "commonjs",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": ""
  }
  • Now that we have the add function implemented, we have to export it to be used in our main.js. To export, we can use export default functionName. In our case, we do export default add.
  function add(x, y) {
    // return the sum of x and y
  }
  • We could have also done
  module.exports = add;
  • Here the entirety of lib.js is just the add function. We exported lib.js as the add function. So we can import it as, import someName from "./lib";
  • In the main.js, we will import the lib.js file and make use of add function.
  const lib = require("./lib");
  // we did, "./lib", "dot slash lib", because main.js and lib.js are in the same folder.

  console.log(lib(1, 2));
  • Let's add the subtraction function
  function sub(x, y) {
    // returns the difference x and y
  }
  • The question is, how do we export sub?
  • In a case such as this, we can export both add and sub by exporting them as a group (object).
  module.exports = { add, sub };
  • Now when we import in main.js we can do
  const lib = require("./lib");
  // lib is an object so we can do lib dot someThing

  console.log(lib.add(1, 2));
  console.log(lib.sub(1, 2));
  • We can also import by doing, import { add, sub } from "./lib";
  const { add, sub } = require("./lib");

  console.log(add(1, 2));
  console.log(sub(1, 2));
  • There is another way to do multiple exports
  exports.add = function add(x, y) {
    // return the sum of x and y
  };

  exports.sub = function sub(x, y) {
    // return the difference of x and y
  };

Or

  exports.add = function (x, y) {
    // return the sum of x and y
  };

  exports.sub = function (x, y) {
    // return the difference of x and y
  };
  • With this sort of approach, it is either, we bundle the whole exports as one import or access individual imports one by one
  {
    "name": "emodule",
    "version": "1.0.0",
    "main": "index.js",
    "type": "module",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": ""
  }

OR

  function add(x, y) {
    // return the sum of x and y
  }

Summary

To use commonjs or es module import and export style is relative. commonjs comes with no configurations, so one would ask why not use it as is? module.exports = someObject is the same as export default someObject. We can import with const someObject = require("pathToModule"); and import someObject from "pathToModule";. I like said, whichever you choose is okay. You can have a module/default export and also individual exports in the same file.

These are some rules that I try to stick to when I am developing my backend projects:

  • I avoid default export or module exports as much as possible and use the individual object export
  • If I have a controller, I use a default/module export without exporting anything else from that same file. So whenever I use module.exports or export default, I don't do any other export from the same file
  • I either use an object to group my constants and default export it or I would do individual exports of all the constants.
  • We can export objects without naming them and it works fine with the alias (name you give it) but I prefer to name my exports

Can you guess what is next? Well, we'd start doing some backend magics. We will start backend development.

Side project

If it challenges you, rewrite the mastermind program using multiple files. While on the topic I will challenge you. Complete this project. Either rewrite it for it to work or do whatever you have got to do to make it work and apply today's lesson.

  {
    "name": "cmodule",
    "version": "1.0.0",
    "main": "index.js",
    "type": "commonjs",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": ""
  }

The above is the detailed content of JavaScript Essentials: Part 7. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn