On my book of Eric Elliot I find these three code but I can not understand like to use them:
(1)
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
(2)
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, true,
'First dependency loaded correctly.');
equal(results.test2, true,
'Second dependency loaded correctly.');
});
});
(3)
if (typeof define === 'function') {
define([], function () {
return api;
});
}
I tried to use require.js and I write these codes but it doesn't work:
javascript\librerie\jquery.js
javascript\librerie\qunit.js
javascript\librerie\require.js
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script data-main="javascript/moduli" src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
</body>
</html>
javascript\moduli\script_libro.js
define(['ch04/amd1', 'ch04/amd2'],
function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
// Define a public API for your module:
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['ch04-amd'], function (amd) {
var results = amd.testResults();
test('AMD with Require.js', function () {
equal(results.test1, console.log(true),
'First dependency loaded correctly.');
equal(results.test2, console.log(true),
'Second dependency loaded correctly.');
});
});
javascript\configurazione.js
/* global requirejs */
requirejs.config({
"baseUrl": "javascript/librerie",
"paths": {
"moduli": "../moduli"
},
"shim": {
"script_libro": {
deps: ["jquery", "qunit"]
}
}
});
requirejs(["moduli/main"]);
I would like to write output strings on console so I edit Eric Elliot's script too. On my console I can only read:
Error: Script error for: moduli
http://requirejs.org/docs/errors.html#scripterror
Could you help me, please?
NEW UPDATE
I believe that the problem is in script_libro.js in fact the console find an error only in this file. I send you my new code:
script_libro_eric_elliott.php
<!DOCTYPE html>
<html>
<head>
<title>Utilizzo della libreria Require.js</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<script data-main="javascript/configurazione.js"
src="javascript/librerie/require.js">
</script>
</head>
<body>
<div>Utilizzo della libreria Require.js</div>
<div id="contenitore"></div>
</body>
</html>
javascript\moduli\script_libro.js
define(['jquery', 'qunit'], function myModule(amd1, amd2) {
var testResults = {
test1: amd1.test(),
test2: amd2.test()
},
api = {
testResults: function () {
return testResults;
}
};
return api;
});
javascript\moduli\main.js
require(['javascript/moduli/script_libro.js'], function (amd) {
var results = amd.testResults;
test('AMD with Require.js', function () {
equal(results.test1, true,
console.log('First dependency loaded correctly.'));
equal(results.test2, true,
console.log('Second dependency loaded correctly.'));
});
});
javascript\configurazione.js
require.config({
baseUrl: 'javascript/librerie',
urlArgs: "bust=" + (new Date()).getTime(),
paths: {
CartellaModuli: '../moduli',
},
shim: {
script_libro: {
deps: ['qunit', 'jquery']
}
}
});
require(['CartellaModuli/main']);
Your data-main should point to a module instead of a directory. Try changing it to data-main="javascript/moduli/main".
That probably won't solve everything since you don't include your configuration in configurazione.js anywhere.
Related
I was trying using SystemJS to load React but it didn't loaded instead throwing an error message in Console > 'React is not defined'
I've read their documentation also searching through similar questions but doesn't satisfy my need, did i miss something?
Here's is what I was tried
<!DOCTYPE html> <html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>React 18 with SystemJS</title>
<script src="dependencies/systemjs-6.12.1.min.js"></script>
<script type="systemjs-importmap"> {
"imports": {
"react" : "/react.production-18.min.js"
, "reactDOM" : "/react-dom.production-18.min.js"
} }
</script>
</head><body>
<div id="root">
<script type="systemjs-module">
System.import('react');
System.import('reactDOM');
class Hello extends React.Component {
render() {
return React.createElement('div', null, `Hello ${this.props.toWhat}`);
} }
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Hello, {toWhat: 'World'}, null));
</script>
</div></body></html>
Edit1: I'm using SystemJS version 6.12.1
You need a bit more configuration to get it going. It is also recommended to keep react code in separate files.
Full working example here.
SystemJS configuration for react:
System.config({
baseURL: '//npm.jspm.io/',
// CDN resolves
paths: {
'npm:*': '//npm.jspm.io/*',
'unpkg:*': '//unpkg.com/*',
'jsdelivr:*': '//cdn.jsdelivr.net/g/*',
'jsdelivr-npm:*': '//cdn.jsdelivr.net/npm/*'
},
meta: {
'*.scss': { loader: "sass" }
},
map: {
// The Application path
'index': INDEX + '?' + Date.now(),
// SystemJS plugins
'plugin-babel': 'unpkg:systemjs-plugin-babel#0/plugin-babel.js',
'systemjs-babel-build': 'unpkg:systemjs-plugin-babel#0/systemjs-babel-browser.js',
// 'scss': 'npm:scss',
// Application modules
'react': 'jsdelivr:react#15/react.js',
'react-dom': 'jsdelivr:react#15/react-dom.js'
},
packages: {
'https://npm.jspm.io/' : { defaultExtension: 'js' },
'https://cdn.rawgit.com/*' : { defaultExtension: false },
'https://unpkg.com/' : { defaultExtension: false },
'./index.scss' : { defaultExtension: false },
},
transpiler: 'plugin-babel',
babelOptions: {
sourceMaps: false,
stage0: true,
react: true
}
});
Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
in the code sample above first and chai work fine, while mocha is undefined.
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim for it. Here is an index.html file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
You need to have run npm install requirejs mocha in the same directory where index.html is located.
In cases where I want to be able to use the Mocha constructor I use this shim instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},
Can I load mocha module asynchronously in browser? I can do it for sure with chai. Is there any workaround to make mocha work in amd-like style ?
require.config({
baseUrl: "/scripts",
paths: {
"mocha": "framework/mocha",
"chai": "framework/chai",
"first": "custom/first"
}
});
require(['first', 'mocha', 'chai'], function (first, mocha, chai) {
first.echo();
console.log('something');
console.log('something');
mocha.ui('tdd');
var assert = chai.assert;
suite('"Home" Page Tests', function () {
test('page should contain link to contact page', function () {
assert($('a[href="/contact"]').length);
});
});
mocha.run();
console.log('whatever');
});
in the code sample above first and chai work fine, while mocha is undefined.
Mocha is not AMD-aware so if you are going to load Mocha using RequireJS, you need a shim for it. Here is an index.html file that contains a minimal example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
<link href="node_modules/mocha/mocha.css" type="text/css" media="screen" rel="stylesheet" />
<script type="text/javascript" src="node_modules/requirejs/require.js"></script>
</head>
<body>
<div id="mocha"></div>
<script>
require.config({
paths: {
mocha: 'node_modules/mocha/mocha',
},
shim: {
mocha: {
exports: "mocha",
}
},
});
require(["mocha"], function (mocha) {
mocha.setup("bdd");
it("foo", function () {});
mocha.run();
});
</script>
</body>
</html>
You need to have run npm install requirejs mocha in the same directory where index.html is located.
In cases where I want to be able to use the Mocha constructor I use this shim instead:
shim: {
mocha: {
exports: "mocha",
init: function () { return {mocha: mocha, Mocha: Mocha }; }
}
},
I'm getting the exact error as found here: (window.beforeEach || window.setup) is not a function. However the fix did not work, the author of the tutorial series here even mentioned the same fix.
Here is the Tuts+ author's fix:
Which is simply to place the angular-mock script tag after the Mochai and Chai scripts. Which I did so below:
test/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="bower_components/mocha/mocha.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/mocha/mocha.js"></script>
<script src="../bower_components/chai/chai.js"></script>
<!-- see Angular-mocks is here :( -->
<script src="../bower_components/angular-mocks/angular-mocks.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="main.spec.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
My main.spec.js file
/**
* #name Mocha Test Runner
* #desc Describes and runs our dashboard tests
*/
var assert = chai.assert;
var expect = chai.expect;
// This Test is designed to fail on purpose
describe('User Login', function() {
console.log('User Login');
describe('Login Failed', function() {
console.log('Login Failed');
if ('Incorrect login should fail', function() {
module('loginController')
inject(function($injector) {
apiFactory = $injector.get('ApiFactory');
});
expect(apiFactory).to.be.an('number');
});
});
});
My Gulp tasks
gulp.task('serve', function() {
return browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
In your index.html file, you include the angular-mocks.js script before the call to mocha.setup('bdd'). angular-mocks.js is implemented as an immediately-invoked function expression which attempts to use window.beforeEach. (https://github.com/angular/bower-angular-mocks/blob/master/angular-mocks.js#L2586)
However, mocha.js is not immediately invoked and has to be initialized with the mocha.setup function in order to add its magic to the runtime environment.
Try reversing the order of these script tags, so that mocha.js is included and initialized before angular-mocks.js.
<script src='bower_components/mocha/mocha.js'></script>
<script src='bower_components/chai/chai.js'></script>
<script>
mocha.setup('bdd');
</script>
<script src="bower_components/angular-mocks/angular-mocks.js"></script>
can't get the following test to work with Firefox 22.0 when AdBlock Plus is enabled. Works just fine on Chrome + when I've disabled adblock. It also works when I'm loading the scripts with script tags instead of requirejs.
./index.html:
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<!--<link rel="icon" type="image/png" href="img/icon.png"/>-->
<!--<script src="js/lib/jquery.js"></script>-->
<script data-main="js/main" src ="require.js"></script>
<!--
<script src="js/lib/soundmanager2.js"></script>
<script src="js/test.js"></script>
-->
<title></title>
</head>
<body>
<div id="stop" style="cursor:pointer;"> stop</div>
</body>
</html>
./js/main.js:
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
define(['jquery','underscore',"soundmanager2"],
function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
return soundManager;
});
No errors or anything in the console, no alerts after that initial 'hep!' one.
Classic pattern, fight with some issue for hours, give up and ask for help, find solution immediately after posting.
added
soundManager.beginDelayedInit();
after soundManager.setup() and it works now.
Use require () method of RequireJS to load a module. In the callback write your code what need. Note that parameter of function is a array contains paths that loads dependencies
require.config({
paths:{
jquery:"lib/jquery",
underscore:"lib/underscore",
soundmanager2:"lib/soundmanager2"
/*backbone:"lib/backbone",
detectmobilebrowser:"lib/detectmobilebrowser"*/
},
shim: {
'underscore': {
exports: '_'
},
'soundmanager2':{
exports:"soundManager"
}
}
});
require(['jquery','underscore',"soundmanager2"],function($,_,soundManager){
alert("hep");
window.soundManager=soundManager;
soundManager.setup({
url: 'swf',
useHTML5Audio:true,
preferFlash: false, // prefer 100% HTML5 mode, where both supported
onready: function() {
alert('SM2 ready!');
/*
soundManager.createSound({
id: 'mySound',
url: './test/test.mp3',
autoLoad: true,
autoPlay: false,
onload: function() {
soundManager.play('mySound');
},
volume: 50
});
*/
},
ontimeout: function() {
alert('SM2 init failed!');
},
defaultOptions: {
// set global default volume for all sound objects
volume: 100
}
});
$("#stop").on("click",function(){
alert("stop");
soundManager.stop("mySound");
});
});