JS Modules

Go back to Tutorial

An JS module is a file containing JS code. There’s no special module keyword; a module mostly reads just like a script. There are two differences.

  • JS modules are automatically strict-mode code, even if you don’t write “use strict”; in them.
  • You can use import and export in modules.

Let’s talk about export first. Everything declared inside a module is local to the module, by default. If you want something declared in a module to be public, so that other modules can use it, you must export that feature. There are a few ways to do this. The simplest way is to add the export keyword.

// kittydar.js – Find the locations of all the cats in an image.

// (Heather Arthur wrote this library for real)

// (but she didn’t use modules, because it was 2013)

export function detectCats(canvas, options) {

var kittydar = new Kittydar(options);

return kittydar.detectCats(canvas);

}

export class Kittydar {

… several methods doing image processing …

}

// This helper function isn’t exported.

function resizeCanvas() {

}

You can export any top-level function, class, var, let, or const.

In JavaScript, modules are individual files with JavaScript code in them. To make what’s in them available, you write an export statement, usually after the relevant code, like this:

export class AppComponent { … }

Then, when you need that file’s code in another file, you import it like this:

import { AppComponent } from ‘./app.component’;

JavaScript modules help you namespace, preventing accidental global variables.

 

Go back to Tutorial

Share this post
[social_warfare]
Module Basics
NgModule Basics

Get industry recognized certification – Contact us

keyboard_arrow_up