Is there a way to import every value from a module in JavaScript?

calin92540842 profile image PDS OWNER CALIN (Calin Baenen) ・1 min read

I want to import everything from a module, and I had the idea of:

import "./module.js";

but I looked on MDN and saw that would run the code, but not import anything. So I thought:

import * from "./module.js";

Is this correct? If not, what is the correct way to import everything from a module?


markdown guide

Use the import * as ns syntax

import * as ModuleName from 'source.js'

Don't use the default export

import ModuleName from 'source.js'

...because it only imports the default export not the rest of the exports.

It'll work for CommonJS + Webpack b/c CJS has no concept of named vs default, but not for standard ESM.


You can import modules in the ff. ways

// 1. import default export from the file as moduleName object,
// moduleName can be anything
import moduleName from "path/to/module"; 

// 2. destructured import, it will destructure import and 
// can access the export module without prefixing anything
import { exportMemberName1, exportMemberName2, ... } from "path/to/module";

// 3.
import * as moduleName from "path/to/module";

If you have tons of modules, the first one is the best way. You can also destructure it along the way.

import moduleName from "path/to/module"; 

const { exportMemberName1, exportMemberName2 } = moduleName;