I started compiling my Ember.js templates server-side using the "ember-template-compiler.js" file mentioned here.
After compiling my templates and transpiling the output with Babel, I get a file which contains all of my templates assigned to an object called "export". Here are the first few lines:
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = Ember.HTMLBars.template((function () {
return {
meta: {
...
Now I've integrated jQuery, "ember.prod.js" and that file within the front-end. I thought it would work, but the only thing I get from the console, is:
ReferenceError: Can't find variable: exports
Why is "exports" not defined?
P.S.: Usually, I would use "ember-cli" for all of this. But in my current project, I need to do everything by myself (please don't ask, why).
But it should work, am I right? I mean, I did it exactly like it was stated here.
Fixed the problem by writing my own template compiler for Gulp istead of trying to use the one in Ember CLI: https://github.com/leo/gulp-ember-compiler
Related
I'm working on an existing (and working) Angular 1.5.5 app. It's very small and has a controller, a directive and a couple of services, all split into individual files.
I'd now like to move to Webpack and make the minimum number of changes to the app to support that. A lot of the Webpack/Angular demos I've found have been about creating a new Angular app with web pack built in from the start, but I don't want to rebuild the existing app, just make whatever changes are necessary to use a webpack-produced bundle. It's also using regular JS, whereas most of the tutorials I've seen are for ES6.
I've got grunt-webpack installed and working, it's creating the bundle.js file and I can see inside the bundle that it's pulling in Angular, Angular-aria and Angular-animate (my module dependencies)
However, when I run the site I see an error:
Uncaught TypeError: angular.module is not a function
My webpack task is as follows:
module.exports = {
dist: {
entry: './Static/js/Ng/app.js',
output: {
path: './Static/dist/js',
filename: 'bundle.js'
}
}
};
As I say, the actual Webpack bundling seems to be working as expected and creates the bundle.js file.
The main entry file (app.js) is as follows:
(function () {
'use strict';
var angular = require('../vendor/angular.js');
var ngAria = require('../vendor/angular-aria.js');
var ngAnimate = require('../vendor/angular-animate.js');
angular.module('app', [ngAria, ngAnimate]);
}());
If I log out the angular variable in this file, it's just an empty object, even though I can see the Angular source in the bundle.
What am I missing?
You probably shadow the global angular property by your local var angular variable. Try this:
(function () {
'use strict';
require('../vendor/angular.js');
require('../vendor/angular-aria.js');
require('../vendor/angular-animate.js');
angular.module('app', [ngAria, ngAnimate]);
}());
I'm using the expect.js library with my mocha unit tests. Currently, I'm requiring the library on the first line of each file, like this:
var expect = require('expect.js');
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
If possible, I'd like to remove the boilerplate require code from the first line of each file, and have my unit tests magically know about expect. I thought I might be able to do this using the mocha.opts file:
--require ./node_modules/expect.js/index.js
But now I get the following error when running my test:
ReferenceError: expect is not defined
This seems to make sense - how can it know that the reference to expect in my tests refers to what is exported by the expect.js library?
The expect library is definitely getting loaded, as if I change the path to something non-existent then mocha says:
"Error: Cannot find module './does-not-exist.js'"
Is there any way to accomplish what I want? I'm running my tests from a gulp task if perhaps that could help.
You are requiring the module properly but as you figured out, the symbols that the module export won't automatically find themselves into the global space. You can remedy this with your own helper module.
Create test/helper.js:
var expect = require("expect.js")
global.expect = expect;
and set your test/mocha.opts to:
--require test/helper
While Louis's answer is spot on, in the end I solved this with a different approach by using karma and the karma-chai plugin:
Install:
npm install karma-chai --save-dev
Configure:
karma.set({
frameworks: ['mocha', 'chai']
// ...
});
Use:
describe('something', function () {
it('should pass', function () {
expect(true).to.be(true); // works
});
});
Thanks to Louis answer and a bit of fiddling around I sorted out my test environment references using mocha.opts. Here is the complete setup.
My project is a legacy JavaScript application with a lot of "plain" js files which I wish to reference both in an html file using script tags and using require for unit testing with mocha.
I am not certain that this is good practice but I am used to Mocha for unit testing in node project and was eager to use the same tool with minimal adaptation.
I found that exporting is easy:
class Foo{...}
class Bar{...}
if (typeof module !== 'undefined') module.exports = { Foo, Bar };
or
class Buzz{...}
if (typeof module !== 'undefined') module.exports = Buzz;
However, trying to use require in all the files was an issue as the browser would complain about variables being already declared even when enclosed in an if block such as:
if (typeof require !== 'undefined') {
var {Foo,Bar} = require('./foobar.js');
}
So I got rid of the require part in the files and set up a mocha.opts file in my test folder with this content. The paths are relative to the root folder:
--require test/mocha.opts.js
mocha.opts.js content. The paths are relative to the location of the file:
global.assert = require('assert');
global.Foo = require("../foobar.js").Foo;
global.Bar = require("../foobar.js").Bar;
global.Buzz = require("../buzz.js");
I am trying to set up unit testing for a SPA using karma/jasmine
First of all, the following test runs just fine in karma:
/// <reference path="../../definitions/jasmine/jasmine.d.ts" />
/// <reference path="../../src/app/domain/core/Collections.ts"/>
define(["app/domain/core/Collections"], (collections) => {
describe('LinkedList', () => {
it('should be able to store strings for lookup', () => {
var list = new collections.Collections.LinkedList<string>();
list.add("item1");
expect(list.first()).toBe("item1");
});
});
});
However, collections is of type anyso that I can not use it for type declarations, thus I'm missing intellisense and whatnot when I am writing my tests. No good!
The problem arises when I try to re-write the test to a more TypeScript friendly format:
/// <reference path="../../definitions/jasmine/jasmine.d.ts" />
/// <reference path="../../src/app/domain/core/Collections.ts"/>
import c = require("./../../src/app/domain/core/Collections");
describe('LinkedList', () => {
it('should be able to store strings for lookup', () => {
var list: c.Collections.LinkedList<string> = new c.Collections.LinkedList<string>();
list.add("item1");
expect(list.first()).toBe("item1");
});
});
This compiles just fine, I get my type information for handy intellisense etc, but now karma throws an error.
It turns out it is trying to load the module without the .js postfix, indicated by the following error messages:
There is no timestamp for /base/src/app/domain/core/Collections!
Failed to load resource: the server responded with a status of 404 (Not Found)
(http://localhost:9876/base/src/app/domain/core/Collections)
Uncaught Error: Script error for: /base/src/app/domain/core/Collections
I'm gonna stop here for now, but if it will help I am glad to supply my karma config file, test-main and so on. But my hope is that someone has encountered this exact problem before and might be able to point me in the right direction.
My typescript is compiled with the AMD flag.
It is not a TypeScript problem. We encountered the same problem. Turns out that karma "window.__karma__.files" array includes all files included in the test, including the .js extenstion.
Now requireJS does not work when supplying the .js extension. To fix it, in our main-test.js file, we created a variable "tests" by filtering all the *Spec.js files and then we removed the .js from the file name as requireJS needs it to be. More information here: http://karma-runner.github.io/0.8/plus/RequireJS.html
Below is how we did it (based on the info supplied in the link above):
main-test.js
console.log('===========================================')
console.log('=================TEST FILES================')
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return /\Spec\.js$/.test(file);
}).map(function (file) {
console.log(file);
return file.replace(/^\/base\/|\.js$/g, '');
});
console.log('===========================================')
console.log('===========================================')
require.config({
baseUrl:'/base',
paths: {
jquery :["http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min", "lib/jquery"],
angular : ["https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min", "lib/angular"],
angularMocks: 'app/vendors/bower_components/angular-mocks/angular-mocks',
},
shim: {
'angularMocks': {
deps: ['angular'],
exports: 'angular.mock'
}
},
deps: tests,
callback: window.__karma__.start
});
Also make sure you have supplied the files to be tested in your karma.config.js file, more details here: http://karma-runner.github.io/0.8/plus/RequireJS.html same as the link above.
Hope it helps
It turns out it is trying to load the module without the .js postfix,
That is the perhaps not the actual source of the error. Actually it is looking at /base/src/app/domain/core/Collections and not app/domain/core/Collections (as in your manual type unsafe way). Notice base/src/ that shouldn't be there.
I recently tried to use the gulp Gist posted here:
Everything builds fine, but in the browser I get an error in the generated templates.js file:
global.Handlebars = require("handlebars");
module.exports = Ember.TEMPLATES["index"] = Ember.Handlebars.template(function anonymous(Handlebars,depth0,helpers,partials,data) {
The error claiming, basically, that 'module' is undefined...
I'm getting a strong feeling that I'm missing something extremely trivial here.
Thanks in advance
Because this causes the file to be wrap in some shim javascript:
'templates': {
path: 'public/js/templates.js',
exports: 'Ember.TEMPLATES'
},
Remove it and you'll be fine.
And requiring Ember in the prebundle is useless if you are also requiring it from your code.
Using RequireJS I'm building an app which make extensive use of widgets. For each widget I have at least 3 separate files:
request.js containing code for setting up request/response handlers to request a widget in another part of my application
controller.js containing handling between model and view
view.js containing handling between user and controller
Module definition in request.js:
define(['common/view/widget/entity/term/list/table/controller'],
function(WidgetController) { ... });
Module definition in controller.js:
define(['common/view/widget/entity/term/list/table/view'],
function(WidgetView) { ... });
Module definition of view.js is:
define(['module','require'],function(module,require) {
'use strict';
var WidgetView = <constructor definition>;
return WidgetView;
});
I have lots of these little situations as above in the case of widgets I have developed. What I dislike is using the full path every time when a module is requiring another module and both are located in the same folder. I'd like to simply specify as follows (assuming we have a RequireJS plugin which solves this for us):
define(['currentfolder!controller'],
function(WidgetController) { ... });
For this, I have written a small plugin, as I couldn't find it on the web:
define({
load: function (name, parentRequire, onload, config) {
var path = parentRequire.toUrl('.').substring(config.baseUrl.length) + '/' + name;
parentRequire([path], function (value) {
onload(value);
});
}
});
As you might notice, in its basic form it looks like the example of the RequireJS plugins documentation.
Now in some cases, the above works fine (e.g. from the request.js to the controller.js), but in other cases a load timeout occurs (from controller.js to view.js). When I look at the paths which are generated, all are proper RequireJS paths. Looking at the load timeouts, the following is logged:
Timestamp: 13-09-13 17:27:10
Error: Error: Load timeout for modules: currentfolder!view_unnormalized2,currentfolder!view
http://requirejs.org/docs/errors.html#timeout
Source File: http://localhost/app/vendor/requirejs/require.js?msv15z
Line: 159
The above log was from a test I did with only loading the view.js from controller.js using currentfolder!view in the list of modules in the define statement. Since I only requested currentfolder!view once, I'm confused as to why I both see currentfolder!view_unnormalized2 and currentfolder!view in the message.
Any idea as to why this might be happening?
My answer may not answer your primary questions, but it will help you achieve what you're trying to do with your plugin.
In fact, Require.js support relative paths for requiring modules when using CommonJS style. Like so:
define(function( require, exports, module ) {
var relativeModule = require("./subfolder/module");
module.exports = function() {
console.log( relativeModule );
};
});