6

With node.js module syntax you can load a module and use it all in one expression:

const numCPUs = require('os').cpus().length;

Is there any equivalent for ES6 modules?

import os from 'os';
const numCPUs = os.cpus().length;

is the closest I can get; this is two full statements, and leaves me with an unwanted binding for os.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51

1 Answers1

8

No. Bindings to modules happen statically when the file's being parsed, and before it's executed. The only way to achieve what you're trying to do is to use a named export.

export const numCPUs = os.cpus().length;

Which will allow you to specify the named export in your program's entry point:

import { numCPUs } from 'os';
  • We have to keep `export const numCPUs = os.cpus().length;` in another file then import from it, right? – Jagdish Idhate May 07 '16 at 14:50
  • 1
    Yes. If you need to defer the execution until after the program's finished initialising, you can have it return a promise, or export the function that supplies the value instead. –  May 07 '16 at 14:53