How do you export a function from a RequireJS module in Node? With the code I have, I get an empty object rather than the Backbone model I'm expecting.
first.js
contains:
'use strict';
var define=require('amd-define');
define(function (require) {
var Backbone = require('backbone');
// Our basic **Todo** model has `title`, `order`, and `completed` attributes.
var Todo = Backbone.Model.extend({
// Customizations of my model...
});
return Todo;
})
My test file test.js
contains:
'use strict';
var chai =require("chai");
var assert=chai.assert;
var expect=chai.expect;
var Todo=require("first");
describe('Tests for Todo model', function () {
it('should create global variables for Todo', function () {
expect(Todo).to.be.exist;
console.log(typeof (Todo))
});
it('should be created with default values for its attributes', function() {
var todo = new Todo();
expect(todo.get('title')).to.equal('');
});
it('should fire a custom event when state change', function() {
var todo = new Todo();
todo.set({completed: true, order: 1});
todo.set('title', 'my title');
});
});
It gives the error that Todo
is not a function. The console.log
statement prints object
.
The package amd-define
is either buggy or does not support the CommonJS sugar. (The latter is probably the case. I do not see any code in it that takes care of doing the dependency transformation necessary for supporting the CommonJS sugar.)
I recommend dumping amd-define
and using amd-loader
instead. I've used it for years, it works.
For your code:
Remove var define=require('amd-define');
from first.js
.
Add require('amd-loader')
(after installing it) in your test file before you load any AMD module.
I was able to get an export from first.js
doing this.