Home > Software design >  ES6 import both all (*) and a specific name in the same statement
ES6 import both all (*) and a specific name in the same statement

Time:07-17

I have an ES6 module, mod.mjs:

export default { f1, f2 };
export function f1() {}
export function f2() {}

Which I can import and use like this:

import { default as mod, f2 } from "./mod.mjs"
mod.f1();
mod.f2();
f2();

Can I do the same without declaring default export inside mod and without de-structuring * alias after importing it?

I've tried the following but it gives a syntax error:

import { * as mod, f2 } from "./mod.mjs"
mod.f1();
mod.f2();
f2();

Basically I want this, but using the import statement syntax only, if possible:

import * as mod from "./mod.mjs"
const { f2 } = mod;

mod.f1();
mod.f2();
f2();

If there is no pure JavaScript solution to that, perhaps, TypeScript has a syntax for something like that?

CodePudding user response:

I am not sure if this is what you are expecting. The Best approach you can follow is this:

import * as mod from "./mod.js";
import { f2 } from "./mod";
mod.f1();
mod.f2();
f2();

CodePudding user response:

You can use code below

import mod, { f1, f2 } from "./fun.mjs";

mod.f1();
mod.f2();
f1();
f2();
  • Related