Reputation: 65510
I have created a class file in Node called chart.js
that relies moment.js
and a bunch of other external dependencies:
var moment = require('moment');
...
var Chart = {
doSomething: function() {
} ...
};
module.exports = Chart;
Now I want to use this chart.js
module in my index.js
file, so I am importing it as follows:
var chart = require('chart');
chart.doSomething();
But this gives me import errors:
ReferenceError: moment is not defined
Do I need to re-include all the require('moment')
statements at the top of index.js
too?
Surely I should be able to change the requirements for the chart file without having to amend the index file too?
Upvotes: 2
Views: 378
Reputation: 7019
No, you don't need to specify require('moment')
in every file. Make sure moment JS library is installed correctly and that it is in your node_modules
directory.
For Node modules installed with npm, you can require them with require('moduleName')
, so require('moment')
is fine. But for your own modules, you have to specify the relative path and the file name. So, assuming index.js
and chart.js
are in the same level, in your index.js
you would do require('./chart.js')
.
Other notes: don't capitalize variable names unless you are using a class constructor function. In your code you are using simple object literal, not a constructor, so there's no need to capitalize the variable name, Chart
.
Upvotes: 5