...

/

Importing from a Module

Importing from a Module

Let's start exploring the import side of modules.

A module must import the references it wants to use, such as primitives, functions, objects, or classes exported by other modules. The import directive should specify the location of the module or file to load. The path may be a relative path, an absolute path, or the name of the module file. In the last case, the location is decided based on the runtime environment and configuration; for example, Node may pick the module from the node_modules directory. The path in general does not include the file extension. JavaScript offers a variety of import options; choose the one that best meets your needs.

Importing named exports

There are two rules to bring in named exports from another module.

  1. First, the name specified in the import for the reference should match the exported name.
  2. Second, the names have to be specified within a {} block.

Let’s create a module that imports some references from the temperature module.

Press + to interact
index.mjs
temperature.mjs
export const FREEZING_POINT = 0;
export function f2c(fahrenheit) {
return (fahrenheit - 32) / 1.8;
}
export const temperaturePoints = { freezing: 0, boiling: 100 };
export class Thermostat {
constructor() {
//...initialization sequence
}
}
const FREEZINGPOINT_IN_F = 32;
function c2f(celsius) {
return celsius * 1.8 + 32;
}
const FREEZINGPOINT_IN_K = 273.15, BOILINGPOINT_IN_K = 373.15;
export { c2f, FREEZINGPOINT_IN_K };
function c2k(celsius) {
return celsius + 273.15;
}
export { c2k as celsiusToKelvin };
export default function unitsOfMeasures() {
return ['Celsius', 'Delisle scale', 'Fahrenheit', 'Kelvin', /*...*/];
}
  • The temperature-operations module currently imports only two of the
...