'require is not defined' in Meteor.js when

2019-05-04 16:51发布

问题:

I'm trying to use a npm package from Meteor.js (Release 0.6.6.3) using Meteor.require. However it throws an error saying that require is not defined. Why is this and how can we solve it?

mrt add npm
npm install github

packages.json

{
    "github": "0.1.8"
}

github.js

var GITHUB = Meteor.require('github');

Error

ReferenceError: require is not defined

The npm package has lines such as

var https = require('https')
var url = require('url')
var crypto = require('crypto')

Must the package's code be manually edited to use Npm.require? Editing them manually got rid of the errors.

However theres a line:

module.exports = SOMETHING

How should we call module from within meteor?

回答1:

Meteor.require is a function added by the meteor npm smart package, which actually doesn't do much for using npm other than wrapping some asynchronous callbacks. It's a few months old, so you might want to try using Meteor's Npm.require directly in case something broke.

The monkey-patching of the Meteor global by this package is misleading.



回答2:

Making comments above an answer.

Is Meteor.require() a typo? That is what is in your code though your question text refers to the correct Npm.require().

I think module.exports is there for non-meteor use of the same file. Within meteor variables for export should be

  1. declared as globals inside the package
  2. exported with api.export() within the package.js file.

The documentation on this is a bit rough but look at namespacing and writing packages. Also looking into the various meteor packages on github is very useful.



回答3:

Make sure you're using the meteor-npm package.

https://www.npmjs.com/package/meteor-npm



回答4:

Use Npm.require() in meteor.

Like this:

var fs = Npm.require("fs");

For that you need to have a Meteor package: meteorhacks:npm , npm-container