Gobliins
Gobliins

Reputation: 4026

how to acces a variable (function) inside a meteor package?

I have a meteor package installed in my Meteor app

/packages/mypackage/some_code.js

inside is a function:

function myFunction(){
    ...
}

i would like to call this function from another file inside my metoer app. Both codes are running on serverside.

/imports/api/myapi.js

How can i access myFunction from myapi.js ?

UPDATE:

After lots of try and error my export looks like this:

var exports = module.exports = {};

exports.getResponses = function (){
    return responses;
}

and import:

import { getResponses } from 'meteor/user:mypackage/myfile.js' ;

Upvotes: 2

Views: 220

Answers (1)

chazsolo
chazsolo

Reputation: 8429

This topic is covered by the Meteor Guide on Exporting. In that guide:

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';

This works for internal packages found at the /package directory as well. Just make sure you have the ecmascript core package, and that you are exporting/importing your objects correctly. You will also need to add the name of the package in .meteor/packages through meteor add <package> or by entering it in manually.

Edit - some elaboration on import/export syntax - hopefully this will help you debug the undefined issues!

From MDN's guide on import/export:

There are two types of exports, named and default.

Named exports:

export { myFunction }; // exports a function declared earlier
export const foo = Math.sqrt(2); // exports a constant

Default exports: (only one per script)

export default function() {} // or 'export default class {}'
// there is no semi-colon here

Named exports allow exporting multiple values per script, while exporting a default allows one per script, or a fallback.

For example, to import from multiple named exports, you would write:

import { myFunction, foo } from 'some-module.js';

Whereas importing a default value looks like:

import defs from 'definitions.js';

Upvotes: 2

Related Questions