Javascript 使用meteor在if语句中导出
在if语句中导入文件相当容易,如下所示:Javascript 使用meteor在if语句中导出,javascript,meteor,commonjs,Javascript,Meteor,Commonjs,在if语句中导入文件相当容易,如下所示: import { Meteor } from 'meteor/meteor'; if (Meteor.isServer) { const thing = require('./blah').default; } 但是,我想知道的是,您是否可以在if语句中导出模块的默认成员,而不将其绑定到全局范围或窗口 if (Meteor.isServer) { export serverOnlyFunction = require('./blah').de
import { Meteor } from 'meteor/meteor';
if (Meteor.isServer) {
const thing = require('./blah').default;
}
但是,我想知道的是,您是否可以在if语句中导出模块的默认成员,而不将其绑定到全局范围或窗口
if (Meteor.isServer) {
export serverOnlyFunction = require('./blah').default;
}
在meteor中如何实现这一点?正如您所写,这是不可能的,因为导出必须在顶层(从)定义。这与当发生延迟加载或循环依赖并且在加载期间或之前无法执行代码时如何处理模块有关 通过导出分支而不是从分支内部导出,可以完全避免这种混乱:
export function getTheFunction() {
if (Meteor.isServer) {
return serverOnlyFunction;
} else {
return functionForEverybody;
}
}
或者,包装器函数也可以工作:
export function wrapTheFunction(...args) {
if (Meteor.isServer) {
return serverOnlyFunction.apply(this, args);
} else {
return functionForEverybody.apply(this, args);
}
}
如果您直接使用导出
,而不使用ES6关键字,则可以从分支内部分配:
if (Meteor.isServer) {
module.exports = serverOnlyFunction;
} else {
module.exports = functionForEverybody;
}
但是,除非你坚持ES5,否则这是一个糟糕的做法。导出一个能够判定的函数是一个更加健壮的解决方案
第二:
import { Meteor } from 'meteor/meteor'; // <- is an import
if (Meteor.isServer) {
const thing = require('./blah').default; // <- is *not* an import
}
正如您所写的,这是不可能的,因为导出必须在顶层(从)定义。这与当发生延迟加载或循环依赖并且在加载期间或之前无法执行代码时如何处理模块有关 通过导出分支而不是从分支内部导出,可以完全避免这种混乱:
export function getTheFunction() {
if (Meteor.isServer) {
return serverOnlyFunction;
} else {
return functionForEverybody;
}
}
或者,包装器函数也可以工作:
export function wrapTheFunction(...args) {
if (Meteor.isServer) {
return serverOnlyFunction.apply(this, args);
} else {
return functionForEverybody.apply(this, args);
}
}
如果您直接使用导出
,而不使用ES6关键字,则可以从分支内部分配:
if (Meteor.isServer) {
module.exports = serverOnlyFunction;
} else {
module.exports = functionForEverybody;
}
但是,除非你坚持ES5,否则这是一个糟糕的做法。导出一个能够判定的函数是一个更加健壮的解决方案
第二:
import { Meteor } from 'meteor/meteor'; // <- is an import
if (Meteor.isServer) {
const thing = require('./blah').default; // <- is *not* an import
}
奇怪的是,
System
存在于Meteor中,但没有import
功能据我所知,目前还没有运行时提供功能齐全的System
对象。您需要使用实现它的库或绑定程序。奇怪的是,Meteor中存在System
,但没有import
功能据我所知,目前没有运行时提供功能齐全的System
对象。您需要使用实现它的库或绑定器。