Requirejs not loading a jquery plugin - javascript

I'm working on improving the tests for jquery-csv (jquery plugin).
I can currently run a full suite of tests (ie mocha/chai) from the command line with no problems. I'm having issues figuring out how to use require.js to load dependencies so I can extend the test runner to work with mochaphantomjs tests.
The HTML used to load RequireJS:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="../node_modules/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script data-main="scripts/app" src="scripts/require.js"></script>
</body>
</html>
The RequireJS module:
require.config({
baseUrl: '/',
paths: {
'jquery' : '../../node_modules/jquery/dist/jquery',
'jquery-csv' : '../../src/jquery.csv',
'mocha' : '../../node_modules/mocha/mocha',
'chai' : '../../node_modules/chai/chai',
},
shim: {
'mocha': {
exports: 'mocha'
},
'chai': {
exports: 'chai'
},
'jquery-csv' : {
deps: ['jquery'],
exports: 'jQuery.fn.csv',
}
},
});
define(function(require) {
require('jquery');
require('jquery-csv');
// chai setup
var chai = require('chai');
var expect = chai.expect();
var should = chai.should();
// mocha setup
var mocha = require('mocha');
mocha.setup('bdd');
mocha.reporter('html');
mocha.bail(false);
require(['test.js'], function(require) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});
});
Note: The define function is using the CommmonJS style.
The error I'm getting is:
Uncaught Error: Module name "../src/jquery.csv.js" has not been loaded yet for context: _. Use require([])
AFAIK, the shim should have fixed this issue by loading jQuery first and attaching the plugin to it.
I'm pretty new to RequireJS, is there something obvious I'm missing?

Try to add your "jquery-csv" as dependency in:
require(['test.js', 'jquery', 'jquery-csv'], function(require, $) {
if (window.mochaPhantomJS) {
mochaPhantomJS.run();
}
else {
mocha.run();
}
});

Related

React not defined when loading with RequireJS

Given the JavaScript below:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script>
<script type="text/javascript">
require.config({
paths: {
'react': 'https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min',
'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min'
}
});
require(['react', 'react-dom'], function () {
var x = React;//Error - React is not defined
});
</script>
Why am I getting an error in the console React is not defined?
You should declare the modules you're importing:
requirejs(['react', 'react-dom'], function(React, ReactDOM) { })
Here's a working example:https://jsfiddle.net/remarkablemark/mejyoLk6/?utm_source=website&utm_medium=embed&utm_campaign=mejyoLk6

Require JS Refress Issue while file access from browser cache

Am using requiredjs. After deployment to the any environment (now screenshot from local) am getting refresh issue. page is not loading properly. I have checked in network tab in firebug. its showing(below image). when the file get 200 OK (BF Cache) status, page not loading properly.
Error:
After giving ctrl+f5
all the pages are coming correctly.
some time i need to give lot of ctrl+f5 then only its working asexpected
my requirejs config file:
require.config({
baseUrl: "../../../../../../../Scripts",
//waitSecond: 0,
//urlArgs : "q="+new Date().getTime(),
enforcedefine: true,
paths: {
//RequireJS Plugins.
'text': 'lib/requirejs/text',
'domReady': 'lib/requirejs/domReady',
'app': 'app',
'noext': 'lib/requirejs/noext',
// Shared Libraries.
'jquery': 'lib/Kendo/jquery.min',
'jqueryMigrate': 'lib/jquery-migrate-1.2.1.min',
'jszip': 'lib/jszip',
'kendo': 'lib/Kendo/kendo.all.min',
'materialize': 'lib/materialize/materialize',
'jqueryValidate': 'jquery.validate.min',
'jsignature': 'lib/jSignature/jSignature.min',
'jqueryMaskedinput': 'lib/jquery/jquery.maskedinput.min',
'jqueryMd5': 'lib/jquery/jquery.md5',
'truckNotifier': 'Controls/serviceTruck.Notifier'
},
shim: {
'app': {
deps: ['kendo']
},
'kendo': {
deps: ['jquery', 'jszip'],
},
'jqueryExtensions': {
deps: ['jquery'],
},
'materialize': {
deps: ['jquery', 'kendo'],
},
'krossRespJs': {
deps: ['jquery'],
},
'jqueryMaskedinput': {
deps: ['jquery'],
},
'truckUploadSelector': {
deps: ['jquery'],
},
'underscore': {
exports: '_'
}
}
});
app.js file:
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define([
'domReady!',
'text',
'noext',
'jquery',
'kendo',
'jszip',
'truckNotifier'
], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function (domReady,text,noext,$,kendo,jszip,truckNotifier) {
'use strict';
var app = kendo.observable({
// ---- PUBLIC FIELDS ----
DATE_FORMAT: 'MM/dd/yyyy',
DATE_MASK: '99/99/9999',
DATE_TIME_FORMAT: 'MM/dd/yyyy HH:mm',
DATE_TIME_MASK: '99/99/9999 99:99',
PHONE_MASK: '(999) 999-9999',
TIME_FORMAT: 'HH:mm',
TIME_MASK: '99:99',
$notifier: $('#notify_container'),
router: new kendo.Router(),
isInitialized: false,
/** This call sets up background components of the current page. */
initialize: function () {
var self = this;
// Initialize this first so it can show loading while the rest
// of this module loads.
if (!self.isInitialized) {
$('.link-external').attr('target', '_blank');
$('#notify_container').serviceTruckNotifier();
self.isInitialized = true;
}
window.JSZip = jszip;
},
showPleaseWait: function (show) {
},
/* Pops up a notification at the top of the page. */
notify: function (type, message) {
var types = {
'push': 'notifyPush',
'info': 'notifyInfo',
'success': 'notifySuccess',
'error': 'notifyError',
'warn': 'notifyWarn',
'expired': 'notifyExpired'
};
this.$notifier.serviceTruckNotifier(types[type], message);
}
});
app.initialize();
return app;
}));
script used in View Page:
<script>
require([
'domReady!',
'text',
'noext',
'app',
'jquery',
'jqueryValidate',
'kendo',
'truckNotifier'
],
function (
domReady,
text,
noext,
app,
$,
jqueryValidate,
kendo,
truckNotifier
) {
var notifier = $('#notify_container'),
message = '#(ViewBag.Message)';
$("#primaryTextButton").kendoButton();
$('.all-content').removeClass('dn');
$('.mcenter').addClass('dn');
if (message != "") {
notifier.serviceTruckNotifier("notifyExpired", "#C.LINK_HAS_BEEN_EXPIRED");
}
});
</script>
HTML FILE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/Styles/all/css")
<script src="~/Scripts/lib/requirejs/require.js"></script>
<script src="~/Scripts/config.js"></script>
</head>
<body id="#RenderSection("BodyId", false)">
#{
System.Reflection.Assembly web = typeof(ServiceTruck.Web.Models.ExternalLogin).Assembly;
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(web.Location);
string version = fvi.FileVersion;
System.Reflection.AssemblyName webName = web.GetName();
string myVersion = version.ToString();
ViewBag.Version = myVersion;
}
#RenderSection("featured", required: false)
<section class="container-fluid">
#RenderBody()
</section>
<!-- Service Truck Layout Footer Start -->
<footer class="copy-right">
<div class="col-md-6 text-left">
<p>All rights reserved.</p>
<p>Copyright © 2016 Name.</p>
</div>
<div class="col-md-6 text-right">
<p>Build #myVersion</p>
<p>Recommended Browsers: Internet Explorer 11, Firefox 48, Chrome 52</p>
</div>
</footer>
<!-- Service Truck Layout Footer End -->
#RenderSection("scripts", required: false)
</body>
</html>
One thing that is definitely wrong with your configuration is the shim for app:
'app': {
deps: ['kendo']
},
Your app module is an AMD module: it calls define. So you cannot use a shim for it. Setting a shim for a module that cannot benefit from one can lead to undefined behavior.
I've run experiments with this at times and got inconsistent results from one version of RequireJS to the next. The point is that setting a shim for an AMD module has no defined semantics.

React ES6 SystemJS - Uncaught (in promise) Error: Unexpected token <(…)

I have react and react-dom installed and imported in via the System.config below, but I still get this error below:
Uncaught (in promise) Error: Unexpected token <(…)
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES2015 Module Example</title>
</head>
<body>
<script src="lib/system.js"></script>
<script>
System.config({
"baseURL": "src",
// Set defaultJSExtensions to true so you don't have to use .js extension when importing the es6 module.
"defaultJSExtensions": true,
// 'plugin-babel' or 'traceur' or 'typescript'
transpiler: 'traceur',
map: {
'react': './node_modules/react/dist/react.min.js',
'react-dom': './node_modules/react-dom/dist/react-dom.min.js',
'traceur': './lib/traceur.min.js',
'plugin-babel': './lib/plugin-babel/plugin-babel.js',
'systemjs-babel-build': './lib/plugin-babel/systemjs-babel-browser.js'
},
});
System.import("app.js");
</script>
</body>
<div id="example"></div>
</html>
app.js:
import React from 'react';
import ReactDOM from 'react-dom';
var Hello = React.createClass({
render: function() {
return <h1>Hello {this.props.name}</h1>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('example')
);
Any ideas what else do I have to configure?
browserify is the best solution (for production & development) - to me:
npm install --save-dev babel-preset-react
gulp:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var livereload = require('gulp-livereload');
gulp.task('build', function() {
// app.js is your main JS file with all your module inclusions
return browserify({entries: 'src/app.js', debug: true})
.transform("babelify", { presets: ["es2015", "react"] })
.bundle()
.pipe(source('compile.min.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('js'))
.pipe(livereload());
});
gulp.task('default', ['build']);
As for non-production with SystemJS (painfully slow):
<!DOCTYPE html>
<script src="https://jspm.io/system#0.19.js"></script>
<script>
System.config({
transpiler: 'babel',
babelOptions: {}
});
System.import('./main.js');
</script>
You still can use gulp for development. Just add this to the gulpfile:
gulp.task('watch', ['build'], function () {
livereload.listen();
gulp.watch('js/*.js', ['build']);
});
gulp.task('default', ['watch']);
This saves you from other tedious dev workflows as listed here.
Unexpected token < usually occurs in html5 applications, when the server is configured to return the contents of index.html instead of 404 pages (so pressing f5 on dynamic routing still works). Check then network panel in your browsers developer console, and see which js file was served with html contents.

How to make systemjs module loading work with .net mvc?

I grabbed the ng-book 2 as it seemed like a quality way to figure out Angular2. As a heads up, I've never used any of these module loaders or anything before and I've had very limited use of npm and node so all the terminology and assumed knowledge can be quite confusing.
ng-book 2 uses node but I figured I might as well start off using my usual .NET MVC server as that is what I'll be pairing Angular 2 with at work.
My current issue is apparently in the module loading, as I just keep getting 404 errors when systemjs is trying to load angular packages.
app.ts
/**
* A basic hello-world Angular 2 app
*/
import {
NgModule,
Component
} from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
#Component({
selector: 'hello-world',
template: `
<div>
Hello World
</div>
`
})
class HelloWorld {
}
#NgModule({
declarations: [HelloWorld],
imports: [BrowserModule],
bootstrap: [HelloWorld]
})
class HelloWorldAppModule { }
platformBrowserDynamic().bootstrapModule(HelloWorldAppModule);
systemjs.config.js
// See also: https://angular.io/docs/ts/latest/quickstart.html
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app/app',
'rxjs': 'app/node_modules/rxjs',
'#angular': 'app/node_modules/#angular'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'rxjs': { defaultExtension: 'js' }
};
var angularPackages = [
'core',
'common',
'compiler',
'platform-browser',
'platform-browser-dynamic',
'http',
'router',
'forms',
'upgrade'
];
// add package entries for angular packages in the form '#angular/common': { main: 'index.js', defaultExtension: 'js' }
angularPackages.forEach(function(pkgName) {
packages['#angular/' + pkgName] = {
main: 'bundles/' + pkgName + '.umd.js',
defaultExtension: 'js'
};
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
index.cshtml
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 - Simple Reddit</title>
<script src="~/app/node_modules/core-js/client/shim.min.js"></script>
<script src="~/app/node_modules/zone.js/dist/zone.js"></script>
<script src="~/app/node_modules/reflect-metadata/Reflect.js"></script>
<script src="~/app/node_modules/systemjs/dist/system.src.js"></script>
<link rel="stylesheet" type="text/css" href="~/app/resources/vendor/semantic.min.css" />
<link rel="stylesheet" type="text/css" href="~/app/styles.css" />
</head>
<body>
<script resource="~/app/resources/systemjs.config.js"></script>
<script>
System.import('/app/app.js')
.then(null, console.error.bind(console));
</script>
<hello-world></hello-world>
</body>
</html>
The layout of the project is like this
And what I end up getting with this are requests like
zone.js:101 GET http://localhost:18481/#angular/core 404 (Not Found)
The first thing I see is that probably your systemjs config is not applied, because you have
<script resource="~/app/resources/systemjs.config.js"></script>
Why do you have resource here? systemjs.config.js contains plain javascript code that should be executed like any other script.

qunit/browser works, but qunit/grunt fails with require.js

I've got a small github project with two branches: master (stable) and qunit-require (unstable). I've got some tests written in qunit that I want to have runnable both in the browser and from grunt level. On master branch everything works fine, travis-CI passes. And on qunit-require branch I'm trying to add require.js for the tests, but I didn't succeed yet.
I can run tests from the browser by displaying test/index.html. But when I run grunt in the console, I get no assertions error and I've got no idea why:
tducin#tducin-workshop:~/Development/tree (qunit-require)$ grunt
Running "qunit:all" (qunit) task
Testing test/index.html Warning: 0/0 assertions ran (15ms) Use --force to continue.
Aborted due to warnings.
I've got src/ and test/ directories as long as bower_components/ where bower deps are stored. This is my test/index.html:
<!DOCTYPE html>
<html>
<head>
<title>jsTreeStructure Test Runner</title>
<meta charset="utf-8">
<link rel="stylesheet" href="../bower_components/qunit/qunit/qunit.css" />
<script src="../bower_components/qunit/qunit/qunit.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="../bower_components/requirejs/require.js" data-main="init.js"></script>
</body>
</html>
This is my test/init.js:
require.config({
baseUrl: '../',
shim: {
'underscore': {
exports: '_'
},
'tree' : {
exports: 'Tree'
},
'qunit' : {
exports: 'QUnit'
}
},
paths: {
'underscore': 'bower_components/underscore/underscore',
'qunit': 'bower_components/qunit/qunit/qunit',
'tree': 'src/tree'
}
});
require([
'test/suites/basic', 'test/qunit-extend'
], function(BasicTests) {
QUnit.config.autoload = false;
QUnit.config.autostart = false;
BasicTests.run();
QUnit.load();
QUnit.start();
});
and this is part of my Gruntfile.js:
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
qunit: {
all: ['test/index.html'],
options: {
timeout: 3000,
coverage: {
src: ['src/tree.js']
}
}
},
// [...]
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-qunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
// Default task.
grunt.registerTask('test', ['qunit', 'jshint']);
grunt.registerTask('build', ['uglify']);
grunt.registerTask('default', ['test', 'build']);
};
Anyway, you can find entire content at github: https://github.com/tkoomzaaskz/tree/tree/qunit-require
My question is: what can I do to make grunt execute the assertions (i.e. what mistake did I make here)?

Categories

Resources