React not defined when loading with RequireJS - javascript

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

Related

How to export a function with Webpack and use it in an HTML page?

I have a file called index.js:
"use strict";
var $ = require("jquery");
window.jQuery = $;
export function foo() {
console.log('hello world');
}
And in the same directory, webpack-config.js:
module.exports = {
entry: './index.js',
output: {
filename: './dist.js'
},
mode: "development"
};
And finally I have an index.html file which loads my bundled JavaScript, and tries to use the exported function definition...
<script src="/media/js/dist/dist.js"></script>
<script type='text/javascript'>
foo();
</script>
When I run webpack, I see no output errors.
But when I load my HTML page, I see:
(index):211 Uncaught ReferenceError: foo is not defined
at (index):211
What am I doing wrong? The dist.js file is loading perfectly OK.
Add a library property to your output configuration:
module.exports = {
entry: './index.js',
output: {
filename: './dist.js',
library: 'myLibrary'
},
mode: "development"
};
Then in index.js, you should be able to call foo() like so:
myLibrary.foo();
For this to work it's important that the foo() function is being exported with export function and not export default function

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.

angular2: SyntaxError: Unexpected token <(…)

I know, this question was asked already, but I can't find the solution for my particular case I can't not understand real reason of the error.
I have an angularjs2 app which is running fine. Now I would like to import marked library.
What I did:
npm install marked
tsd install marked --save
and the tsd.json
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "master",
"path": "typings",
"bundle": "typings/tsd.d.ts",
"installed": {
"marked/marked.d.ts": {
"commit": "cc3d223a946f661eff871787edeb0fcb8f0db156"
}
}
}
now trying to import "marked" into my component
import {Component} from 'angular2/core';
import * as marked from 'marked';
#Component({
selector: 'blog-component',
templateUrl: 'app/components/blog/blog.html'
})
export class BlogComponent {
private md: MarkedStatic;
constructor() {
this.md = marked.setOptions({});
}
getMarked() {
return this.md.parse("# HELLO");
}
}
This line: this.md = marked.setOptions({}); produces the error with SyntaxError: Unexpected token.. removing this line does not end with an error.. I also thing that MarkedStatic was imported correclty then. but then ist not possible to parse markdown, because it should be first initialized whith setOptions.
So I assume that importing of marked fails, or the setOptions method fails.. but I can't figure why...
and here the script part of my index.html:
<!-- 1. Load libraries -->
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/typescript/lib/typescript.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script src="node_modules/angular2/bundles/router.dev.js"></script>
<script src="node_modules/angular2/bundles/http.dev.js"></script>
<script src="node_modules/marked/marked.min.js"></script>
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}}
});
System
.import('app/boot')
.then(null, console.error.bind(console));
</script>
You need to add this in your SystemJS configuration instead of including it into a script element:
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
map: {
marked: 'node_modules/marked/marked.min.js'
},
packages: {'app': {defaultExtension: 'ts'}}
});
</script>
See this plunkr: https://plnkr.co/edit/0oSeaIyMWoq5fAKKlJLA?p=preview.
This question could be useful for you:
How to detect async change to ng-content

Requirejs not loading a jquery plugin

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();
}
});

Categories

Resources