gpt4 book ai didi

javascript - 导入导出javascript函数库的正确方法(模块重定向)

转载 作者:行者123 更新时间:2023-11-29 23:00:54 26 4
gpt4 key购买 nike

考虑以下具有多个导出的文件(函数库):

lib.js:

export const Funct1 = () => {
...
}

export const Funct2 = () => {
...
}

export const Funct3 = () => {
...
}

为了在环境之间使用共享代码,我需要构建一个中间文件来导入所有 lib.js 函数,然后作为导出(模块重定向)提供给新项目。这是我的代码:

MyLib.js

export { default as functionlib } from "./src/helpers/lib";

现在我需要将 MyLib.js 导入到我的最终代码中:

App.js

import { lib } from "../shared/MyLib.js"

...

// Later use the function
let a = lib.Funct1();

根据该语法,lib 在我的结束代码 App.js 处结束为 null

这些是我在 MyLib.js 中使用的变体以及 App.js 上的结果错误:

import { default as lib } from "../shared/MyLib.js" <--- ERROR: lib ends being null

import { * as lib } from "../shared/MyLib.js" <--- ERROR: unexpected token at * 

我如何正确地重定向 MyLib.js 中的所有函数以使所有 lib 函数可用(无需显式显示 lib`` 中的所有函数MyLib`) ?

最佳答案

Is there a way to do it "in a bulk mode" without expliciting all thelibrary functions?

不,动态计算的值不能静态导出:ECMAScript 6 modules: the final syntax :

You may be wondering – why do we need named exports if we could simply default-export objects (like CommonJS)? The answer is that you can’t enforce a static structure via objects and lose all of the associated advantages (described in the next section).


您可以默认导出:

//lib.js
const Funct1 = () => {
...
}

export default Funct1;

默认导入:

import Funct1 from './lib.js'
import MyFunc from './lib.js'
import Whatever from './lib.js'

您可以在导入时分配任何名称,因为它解析为 lib.js 的默认导出是什么。


或者命名导出:

//lib.js
export const Funct1 = () => {
...
}

命名导入

import { Func1 } from './lib.js'
import { MyFunc } from './lib.js' //Doesn't work
import { Whatever } from './lib.js' //Doesn't work

在这种情况下,导入名称必须与导出名称相对应,因为您是按名称导入特定事物。

More on the subject


lib.js

export const Funct1 = () => {
...
}

export const Funct2 = () => {
...
}

export const Funct3 = () => {
...
}

MyLib.js

export {
Funct1,
Funct2,
Funct3,
} from "./src/helpers/lib";

//You can easily add more
export {
Foo,
Bar
} from "./src/helpers/fooBar";

应用程序.js

import * as MyLib from "../shared/MyLib.js"

// Usage
MyLib.Funct1()
MyLib.Foo()

关于javascript - 导入导出javascript函数库的正确方法(模块重定向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com