我的 Meteor 应用程序中安装了一个 Meteor 软件包
/packages/mypackage/some_code.js
里面是一个函数:
function myFunction(){
...
}
我想从我的 metoer 应用程序内的另一个文件调用此函数。两个代码都在服务器端运行。
/imports/api/myapi.js
如何从 myapi.js 访问 myFunction ?
更新:
经过多次尝试和错误,我的导出看起来像这样:
var exports = module.exports = {};
exports.getResponses = function (){
return responses;
}
并导入:
import { getResponses } from 'meteor/user:mypackage/myfile.js' ;
最佳答案
此主题由 Meteor Guide on Exporting 涵盖。在该指南中:
While some packages exist just to provide side effects to the app, most packages provide a reusable bit of code that can be used by the consumer with import. To export a symbol from your package, simply use the ES2015 export syntax in your mainModule:
// in my-package.js:
export const myName = 'my-package';
Now users of your package can import the symbol with:
import { myName } from 'meteor/username:my-package';
这适用于在 /package
中找到的内部包。目录也是如此。只需确保您有 ecmascript
core 包,并且您正在正确导出/导入对象。您还需要在.meteor/packages
中添加包的名称。通过meteor add <package>
或手动输入。
编辑 - 关于导入/导出语法的一些详细说明 - 希望这将帮助您调试undefined
问题!
来自MDN's guide on import/export :
导出有两种类型,命名和默认。
命名导出:
export { myFunction }; // exports a function declared earlier
export const foo = Math.sqrt(2); // exports a constant
默认导出:(每个脚本只有一个)
export default function() {} // or 'export default class {}'
// there is no semi-colon here
命名导出允许每个脚本导出多个值,而导出默认值则允许每个脚本导出一个值,或者作为后备。
例如,要从多个命名导出导入,您可以编写:
import { myFunction, foo } from 'some-module.js';
导入默认值如下所示:
import defs from 'definitions.js';
关于javascript - 如何访问 meteor 包内的变量(函数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41810727/