我正在创建一个单位转换器,我想将所有转换函数放入自己的文件中。使用ES6
export
,有没有办法只用一行就可以导出文件中的所有函数及其默认名称?例如:
export default all;
这些函数都在文件中,而不是在对象中。
不,没有通配符导出(除非您从另一个模块重新导出所有内容,但这不是您要问的)。
只需将
export
放在要导出的每个函数声明前面,例如
export function foo() {
// ...
}
export function bar() {
// ...
}
...或者当然,如果您使用函数表达式:
export var foo = function() {
// ...
};
export let bar = () => {
// ...
};
export const baz = value => {
// ...
};
我认为对此有很多解决方案。正如已经回答的那样,没有通配符导出。但是,您可以使用“通配符”导入。因此,我更喜欢将
export
放在要从文件中公开的每个函数之前:
//myfile.js
export function fn1() {...}
export function fn2() {...}
然后
import
就像这样:
import * as MyFn from './myfile.js'
之后你可以像这样使用它:
MyFn.fn1();
MyFn.fn2();
您还可以使用
module.exports
,如下所示:
function myFunction(arg) {
console.debug(arg);
}
function otherFunction(arg) {
console.error(arg);
}
module.exports = {
myFunction: myFunction,
otherFunction: otherFunction,
};
然后就可以导入了:
import {myFunction, otherFunction} from "./Functions.js";
在我的用例中,我在一个文件中确实有三个可重用函数。
utils/reusables.js
export const a = () => {}
export const b = () => {}
export const c = () => {}
为了指向根文件夹而不是单个文件名,我创建了一个名为
index.js
的文件,它将包含单个文件中列出的所有函数。
utils/index.js
export * from './reusables'
现在,当我想使用我的
a
函数时,我只需像这样导入它
import { a } from '../utils'
而不是从其单独的文件中调用它
import { a } from '../utils/reusables'
您也可以在脚本底部导出它们。
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
您还可以将子模块聚合到父模块中,以便可以从该模块导入它们。
// In parentModule.js
export { myFunction, myVariable } from 'childModule1.js';
export { myClass } from 'childModule2.js';
// In top-level module
import { myFunction, myVariable, myClass } from 'parentModule.js'
我认为缺少一个通用解决方案,即在
index.js
文件中导出:
myModule/myFunctions.js
export const foo = () => { ... }
export const bar = () => { ... }
然后在
myModule/index.js
export * from "./myFunctions.js";
这样您就可以简单地导入并使用它:
import { foo, bar } from "myModule";
foo();
bar();
对于
Node.js
环境,我导出函数的做法是这样的。
UserController.js
module.exports = {
signUp: () => {
return "user"
},
login: () => {
return "login"
}
}
UserRouter.js
const UserController = require('./UserController')
那么
login
和 signUp
函数可以在 UserRouter
中使用,如 UserController.signUp()
和 UserController.login()
如果有人仍然需要现代 JavaScript 的答案:
const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
functions.js
function alpha(msj) {
console.log('In alpha: ' + msj);
}
function beta(msj) {
console.log('In beta: ' + msj);
}
module.exports = {
alpha,
beta
};
main.js
const functions = require('./functions');
functions.alpha('Hi');
functions.beta('Hello');
奔跑
node main.js
输出
In alpha: Hi
In beta: Hello
我喜欢做的是导出对象内的所有函数:
//File.js
export default {
testFunction1: function testFunction1(){
console.log("Hello World")
},
//a little bit cleaner
testFunction2: () => {
console.log("Nothing here")
}
}
现在您可以通过调用对象的键值来访问函数了:
//differentFile.js
import file from 'File.js'
file.testFunction1()
//Hello World
file.testFunction2()
//Nothing here
除了手动导出它们之外,没什么可做的,如果你想自动化这个过程,你可以从使用 babel 开始,这里我向你展示一个如何做到这一点的例子。
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
// Initialize Ace Editor for read-only
var editor2 = ace.edit("editor2");
editor2.setTheme("ace/theme/monokai");
editor2.getSession().setMode("ace/mode/javascript");
editor2.setReadOnly(true);
// Function to trigger transformation
function transformCode() {
try {
// Get the code from the first editor
var code = editor.getValue();
// Transform the code
const transformedCode = astTransform(code);
// Update the content of the second editor with the transformed code
editor2.setValue(transformedCode);
} catch (error) {
console.error("Error during transformation:", error);
}
}
function astTransform(code) {
const result = Babel.transform(code, {
plugins: [{
visitor: {
Program(path) {
//console.log(path.scope);
const {
types: t
} = Babel.packages;
path.pushContainer('body', [t.exportNamedDeclaration(null, Object.keys(path.scope.bindings).map(_ => t.exportSpecifier(t.identifier(_), t.identifier(_))))]);
/*t.addComment(path.container, "trailing", `This is what I found:
Identifiers defined in this scope: ${JSON.stringify(Object.keys(path.scope.bindings))};
Identifiers used that are global or in prelude scope: ${JSON.stringify(Object.keys(path.scope.globals))}
All variables used at all: ${JSON.stringify(Object.keys(path.scope.references))}
`);*/
}
}
}]
});
return result.code;
}
.editor {
width: 500px;
height: 60px;
border: 1px solid lightgray;
}
<!-- Include Ace Editor from CDN -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min-noconflict/ace.js"></script>
<!-- Create a div element for Ace Editor -->
<div id="editor" class="editor">function greet() {
console.log('Hello, world!');
}
var a = 1;
const b = a + a;
((_ => {
var ignored = 1;
console.log(ignored)
}))();
</div>
<button onclick="transformCode()">Add Exports</button>
<div class="editor" id="editor2" readonly></div>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>