最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Importing multiple functions from module without explicitly exporting object or named export - Stack Overflow

programmeradmin0浏览0评论

utils/mathlib.js

export function add(x, y) {
    return x + y;
}
export function subtract(x, y) {
    return x - y;
}

main.js

import add from "./../utils/mathlib"; //not working. but if I do default export like `export default function add(x, y)` it will work
import { add } from "./../utils/mathlib"; //working
import * as MathLib from "./../utils/mathlib"; //working

But I want to import all the functions available in the module with the same identifier without importing separately or through importing object. Something like the below,

import * from "./../utils/mathlib"

I should be able to use add, subtract function.

The reasoning behind this use case is, Whenever I add new functions in MathLib.js it should be available without modifying.(I took MathLib as sample use case only, in my real use case all the functions is necessary whenever I import the module).

utils/mathlib.js

export function add(x, y) {
    return x + y;
}
export function subtract(x, y) {
    return x - y;
}

main.js

import add from "./../utils/mathlib"; //not working. but if I do default export like `export default function add(x, y)` it will work
import { add } from "./../utils/mathlib"; //working
import * as MathLib from "./../utils/mathlib"; //working

But I want to import all the functions available in the module with the same identifier without importing separately or through importing object. Something like the below,

import * from "./../utils/mathlib"

I should be able to use add, subtract function.

The reasoning behind this use case is, Whenever I add new functions in MathLib.js it should be available without modifying.(I took MathLib as sample use case only, in my real use case all the functions is necessary whenever I import the module).

Share Improve this question asked Apr 9, 2018 at 7:22 Ember FreakEmber Freak 12.9k5 gold badges26 silver badges55 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

You need to export your functions in an default object

export default {
    add(x, y) {
        return x + y;
    }
    subtract(x, y) {
        return x - y;
    }
}

You can't currently import into the global namespace without explicit named import/exports. It helps to prevent global namespace pollution and accidental overriding of variables in the global scope.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论