angular2: SyntaxError: Unexpected token <(…) - javascript

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

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

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.

Import Underscore to Angular 2 CLI project

I've started a new project with the Angular CLI tool. After that I follow this official guide to import Underscore and I do exactly as it says.
But still my project crashes in the browser when I try to use Underscore in my app.component with the error message:
ORIGINAL EXCEPTION: ReferenceError: _ is not defined
Underscore is added to the dist/vendor folder so my guess would be that the problem is in the Systemjs configuration.
Here is my angular-cli-build:
var Angular2App = require('angular-cli/lib/broccoli/angular2-app');
module.exports = function(defaults) {
return new Angular2App(defaults, {
sassCompiler: {
includePaths: [
'src/styles'
]
},
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(ts|js|js.map)',
'rxjs/**/*.+(js|js.map)',
'underscore/underscore.js',
'#angular/**/*.+(js|js.map)'
]
});
};
Here is my system-config:
"use strict";
// SystemJS configuration file, see links for more information
// https://github.com/systemjs/systemjs
// https://github.com/systemjs/systemjs/blob/master/docs/config-api.md
/***********************************************************************************************
* User Configuration.
**********************************************************************************************/
/** Map relative paths to URLs. */
const map: any = {
'underscore': 'vendor/underscore/',
};
/** User packages configuration. */
const packages: any = {
'underscore': { main: 'underscore.js', format: 'cjs' },
};
////////////////////////////////////////////////////////////////////////////////////////////////
/***********************************************************************************************
* Everything underneath this line is managed by the CLI.
**********************************************************************************************/
const barrels: string[] = [
// Angular specific barrels.
'#angular/core',
'#angular/common',
'#angular/compiler',
'#angular/forms',
'#angular/http',
'#angular/router',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
// Thirdparty barrels.
'rxjs',
// App specific barrels.
'app',
'app/shared',
/** #cli-barrel */
];
const cliSystemConfigPackages: any = {};
barrels.forEach((barrelName: string) => {
cliSystemConfigPackages[barrelName] = { main: 'index' };
});
/** Type declaration for ambient System. */
declare var System: any;
// Apply the CLI SystemJS configuration.
System.config({
map: {
'#angular': 'vendor/#angular',
'rxjs': 'vendor/rxjs',
'main': 'main.js'
},
packages: cliSystemConfigPackages
});
// Apply the user's configuration.
System.config({ map, packages });
My app.component:
/// <reference path="../../typings/globals/underscore/index.d.ts" />
import { Component } from '#angular/core';
declare var _;
#Component({
moduleId: module.id,
selector: 'app-root',
template: `<h1>{{title}}</h1>`
})
export class AppComponent {
title = _.version;
}
Where do I go wrong?
And WHY is this so complicated? Will the community accept it being this cumbersome to just add a simple third party library?
Your configuration basically sets up underscore so SystemJS can find it when needed.
When you changed system-config.ts, you told SystemJS: if anyone asks for underscore, it is a file underscore.js that can be found at the vendor/underscore/ folder -- and its module format is CommonJS (cjs).
The changes at angular-cli-build.js are for telling angular-cli what files it should pick and throw into the vendor folder. (So, if you told SystemJS it'd find underscore there, this is what makes it be there.)
But that alone does not import/add underscore into the global scope of your app.
You have to import it at each .ts file so SystemJS adds it to the transpiled .js of that module.
Instead of these two lines:
/// <reference path="../../typings/globals/underscore/index.d.ts" />
declare var _;
Add this to your file:
import * as _ from 'underscore';
If you have problems, try to inspect the generated .js source being executed at the browser. In your case, you'll probably find that there is no require() method importing the underscore.
The doco adding 3rd party lib is misleading.
I have been banging my head for over an hour!
declare var _; // this won't work.
What you need is
/// <reference path="../../../typings/globals/underscore/index.d.ts" />
import * as _ from 'underscore';

Angular 2 not rendering dependancy links with file extensions

I am getting the following errors while running my app:
It seems to be looking for ./app.component, rather than ./app.component.js
Here is my main.ts file:
import { bootstrap } from 'angular2/platform/browser';
import { AppComponent } from './app.component';
bootstrap(AppComponent);
What have I done wrong to configure the dependencies here? NB: If I change the references to import { AppComponent } from './app.component.js';, then the error goes away and I am faced with more of the same errors for other references.
EDIT:
One of the comments has suggested that there might be an issue with my system.config(), which I think sounds very plausible, however, this is and excerpt from my index.html file, which I can't see any issues with?
...
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('client/dev/main.js')
.then(null, console.error.bind(console));
</script>
...
Your mistake is probably that you have :
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('client/dev/main.js')
.then(null, console.error.bind(console));
</script>
instead of
<script>
System.config({
packages: {
"client/dev": { // this line changed, here the directory where your generated `js` files are, has to be specified
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('client/dev/main')
.then(null, console.error.bind(console));
</script>
I had exactly the same problem as you when I started ;)
Also the zone error should disappear if you use the newest angular beta build (12).

How load Emberjs 2.0 with jspm and systemjs

I am try use Ember 2.0 and have next files
config.js
System.config({
"baseURL": "/static/js",
"transpiler": "traceur",
"paths": {
"*": "*.js",
"github:*": "jspm_packages/github/*.js"
}
});
System.config({
"map": {
"ember": "github:components/ember#2.0.0",
"traceur": "github:jmcriffey/bower-traceur#0.0.88",
"traceur-runtime": "github:jmcriffey/bower-traceur-runtime#0.0.88",
"github:components/ember#2.0.0": {
"jquery": "github:components/jquery#2.1.4",
"handlebars": "github:components/handlebars#1.3.0"
}
}
});
app.js
import Ember from "ember";
let App = Ember.Application.create({
LOG_TRANSITIONS: true,
LOG_TRANSITIONS_INTERNAL: true,
});
and index.html
<script src="{% static "js/jspm_packages/system.js" %}"></script>
<script src="{% static "js/config.js" %}"></script>
<script>
System.import('app');
</script>
aftre load i have next error
Uncaught (in promise) Error: Cannot read property 'Ember' of undefined
Error loading http://localhost:9090/static/js/app.js
at http://localhost:9090/static/js/jspm_packages/github/components/ember#2.0.0/ember.js!transpiled:16:38
at http://localhost:9090/static/js/jspm_packages/github/components/ember#2.0.0/ember.js!transpiled:97:11
at execute (http://localhost:9090/static/js/jspm_packages/github/components/ember#2.0.0/ember.js!transpiled:25603:9)
at m (http://localhost:9090/static/js/jspm_packages/system.js:4:20821)
at m (http://localhost:9090/static/js/jspm_packages/system.js:4:20756)
at m (http://localhost:9090/static/js/jspm_packages/system.js:4:20756)
at Object.Promise.all.then.execute (http://localhost:9090/static/js/jspm_packages/system.js:4:23421)
at b (http://localhost:9090/static/js/jspm_packages/system.js:4:7874)
at S (http://localhost:9090/static/js/jspm_packages/system.js:4:8253)
at p (http://localhost:9090/static/js/jspm_packages/system.js:4:6131)
if load scripts without systemjs and jspm always work. but want use jspm and systemjs :)
Before i use ember 1.13 and with config worked. I think problem with config jquery
It looks like the package for Ember is not always jspm-compatible. I always use the following override in my package.json:
"jspm": {
"overrides": {
"github:components/ember#2.0.0": {
"main": "ember.debug",
"files": [
"ember.prod.js",
"ember.debug.js"
],
"dependencies": {
"jquery": "github:components/jquery#^2.1.3"
},
"shim": {
"ember.prod": {
"deps": [
"jquery"
],
"exports": "Ember"
},
"ember.debug": {
"deps": [
"jquery"
],
"exports": "Ember"
}
}
}
}
}
It dictates jspm to install only prod and debug versions of Ember and describes all dependencies and exports properly. If you use it, you need to run jspm install again after you added it to your package.json.
You may encounter another problem with htmlbars templates. I have got a plugin to solve that: https://github.com/n-fuse/plugin-ember-hbs:
jspm install hbs=github:n-fuse/plugin-ember-hbs#2.0.0
should allow importing hbs templates w/o the need to add a compiler in dependencies.
See also a starter project I created: https://github.com/OrKoN/jspm-ember-playground

Categories

Resources