Angular 2 빠른 시작 : 예기치 않은 토큰 <
http://angular.io 에있는 빠른 시작에 따라 angular 2를 설정하려고합니다 . 가이드에 설명 된대로 정확하게 모든 파일을 복사했지만 실행 npm start하고 브라우저 탭이 열리면 콘솔에 다음 오류와 함께 "로드 중 ..."이 표시됩니다.
Uncaught SyntaxError: Unexpected token < (program):1
__exec @ system.src.js:1374
Uncaught SyntaxError: Unexpected token < angular2-polyfills.js:138
Evaluating http://localhost:3000/app/boot
Error loading http://localhost:3000/app/boot
이것은 내 app.component.ts:
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>`
})
export class AppComponent {
}
내 boot.ts:
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
bootstrap(AppComponent);
내 index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Angular 2 Quick Start</title>
<script src="node_modules/es6-shim/es6-shim.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>
<script src="node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
packages: {
format: 'register',
defaultExtension: 'js'
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
내 package.json:
{
"name": "angular2-quickstart",
"version": "0.1.0",
"scripts": {
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
},
"license": "MIT",
"dependencies": {
"angular2": "2.0.0-beta.0",
"systemjs": "0.19.6",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.0",
"zone.js": "0.5.10"
},
"devDependencies": {
"concurrently": "^1.0.0",
"lite-server": "^1.3.1",
"typescript": "^1.7.3"
}
}
그리고 마지막으로 내 tsconfig.json:
{
"compilerOptions": {
"target": "ES5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules"
]
}
도움을 주셔서 미리 감사드립니다.
이것을 교체하십시오
System.config({
packages: {
format: 'register',
defaultExtension: 'js'
}
});
이것으로
System.config({
packages: {
app: { // must match your folder name
format: 'register',
defaultExtension: 'js'
}
}
});
나는 그들의 빠른 시작에 약간 다른 폴더 구조를 적용하려고 시도했지만 동일한 문제가 발생했습니다. "패키지"개체의 속성 이름이 상위 폴더와 일치해야한다는 것을 알았습니다.
"예기치 않은 토큰 <"오류가 발생한 사용자를위한 팁입니다. 나에게 이것은 SystemJS가 종속성 (JavaScript 파일)을 검색하려고 시도하고 대신 웹 서버가 HTML 페이지를 반환했을 때 발생했습니다 (따라서 html에서 예기치 않은 여는 <).
HTML이 대신 반환되는 파일을 찾을 때까지 다운로드 한 JavaScript 파일을 하나씩 살펴봄으로써 네트워크 탭에있는 Chrome의 개발 도구에서이를 정확히 찾아 낼 수있었습니다. 이렇게하면 가져 오기 관련 문제를 쉽게 해결할 수 있습니다.
어떤 시점에서 더 의미있는 오류 메시지를받을 수 있기를 바랍니다.
다른 노드 모듈에서 비슷한 문제가 발생하여 Google에서 왔습니다.
일반적으로 import패키지를 사용하고 사용하려고 하면 오류가 발생 합니다.
예를 들어 https://github.com/ngrx/store 로드 할 때 동일한 문제가 발생했습니다 .
네트워크 탭을 확인한 결과 store.js 용으로로드 된 파일 (해당 모듈의 기본 파일)이 올바르지 않은 것으로 나타났습니다. store.js를 요청했지만으로 시작하는 index.html을 얻었습니다 <!DOCTYPE html>. 즉, 유효한 JavaScript가 아닌 "<"로 시작했습니다.
내 index.html이 실제 JavaScript 파일 대신 제공되는 이유가 명확하지 않습니다. 한 가지 설명은 SystemJS가 아무데도 요청하지 않았고 내 서버가 index.html을 기본값으로 제공하도록 구성되었다는 것입니다. 그래도이를 증명할 데이터가 충분하지 않습니다. 정액 grano salis.
어쨌든 나는 패키지가 자체적으로 찾을 수 없다면 SystemJS에 패키지가 어디에 있는지 명시 적으로 알려 주어 수정했습니다. 예를 들어 실패한을 수정 import { Store } from '@ngrx/store';하려면 다음을 수행 할 수 있습니다.
System.config({
packages: {
src: {
format: 'register',
defaultExtension: 'js'
}
},
map: { '@ngrx/store' : '/node_modules/@ngrx/store/dist/store.js' } // <-- this!
});
System.import('src/boot')
.then(null, console.error.bind(console));
Store모듈이 해당 파일에 있기 때문 입니다. 이런 식으로 SystemJS는 그것을 찾고 모듈을 잘 가져올 수 있습니다.
가져 오기와 비슷한 문제가 있었는데 rx.js결국 경로를 추가하여 해결했습니다.System.config()
System.config({
defaultJSExtensions: true,
paths: {
'rx' : 'lib/rx.js'
}
});
비슷한 문제가 발생 index.html하여 라우터가 제대로 작동하도록 모든 경로를 다시 쓰도록 IIS 서버를 구성했습니다 . (페이지 새로 고침이 404를 반환 했습니다.이 답변의 세부 정보를 읽으십시오 )
사용자 @dchacke가 지적했듯이 파일이 아닌 파일을 System.js기대 하기 때문 입니다. 이것은 실제로로 시작하는 이상한 메시지를 생성합니다 . URL 재 작성을 일시적으로 비활성화하면 실제 문제를 볼 수 있습니다..js.htmlSyntaxError: Unexpected token <
자식 구성 요소를 부모 구성 요소로 가져올 때 System.js경로가 올바르게 선언되지 않으면 혼동 될 수 있습니다.
예를 들어 parent.component.ts다음 가져 오기가 있습니다.
import { ChildComponent } from './childComponentFolder/childComponent';
이 오류가 발생합니다.
GET app/parentComponentFolder/childComponentFolder/childComponent.js 404 (Not Found)
Error: Error: XHR error (404 Not Found) loading app/parentComponentFolder/childComponentFolder/childComponent.js
가져 오기 명령 경로를 상대 경로에서 절대 경로로 변경하면 문제가 해결됩니다.
import { ChildComponent } from 'app/childComponentFolder/childComponent';
system.config.js에서 경로를 매핑하는 것도 트릭을 수행 할 수 있지만 가져 오기 경로가 작동하는지 여부를 쉽게 알 수 없기 때문에 유지 관리가 더 어렵습니다. 이제 다시 쓰기 규칙의 주석 처리를 제거 할 수 Web.config있으며 모두 정상적으로 작동합니다.
편집하다:
typescript transpiler는 경로에 대해 매우 까다로운 것 같습니다. 상대 경로 만 오류없이 전달됩니다.
기본적으로 당신은 하나 개의 폴더 백업을 단계로 필요 parentComponentFolder/에 app/폴더.
import { ChildComponent } from '../childComponentFolder/childComponent';
나는이 같은 문제에 부딪쳤다. 내 index.html에서 다음을 구현하여 수정했습니다 (참고 : 'lib'폴더에 angular2 js 종속성을 넣었습니다).
<html>
<head>
<title>Desktop main</title>
</head>
<body>
<div>
<my-app>Loading...</my-app>
</div>
<script src="~/lib/anguar2/angular2-polyfills.js"></script>
<script src="~/lib/es6-shim/es6-shim.js"></script>
<script src="~/lib/systemjs/system.src.js"></script>
<script>
System.config({
defaultJSExtensions: true
});
</script>
<script src="~/lib/rxjs/rx.js"></script>
<script src="~/lib/anguar2/angular2.dev.js"></script>
<script>
System.import('app/boot');
</script>
</body>
</html>
import {Component} from "angular2/core";
@Component({
selector: "my-app",
template: "<h1>Hello Angular 2</h1>"
})
export class AppDesktopComponent {
}
이것이 작동하는 이유와 angular2 빠른 시작 보일러 플레이트가 작동하지 않는 이유를 알려 드리고 싶습니다.
비슷한 문제가 발생했습니다.
Unexpected token ]
서버를 시작할 때. 내 뒤에 쉼표가 있음이 밝혀졌습니다 tsconfig.json.
...
"files": [
"app.ts",
"typings.d.ts",
"abc-vt/abc-vt", <-Doh!
]
교훈 : 소스 코드의 오류라고 가정하지 말고 구성 파일도 확인하십시오.
제 경우에는 파일 확장자를 가져 오기에 실수로 포함 시켰습니다.
import {SomeComponent} from 'some.component.ts';
그리고 (분명히!) 그것은 ...
import {SomeComponent} from 'some.component';
A trailing comma in your systemjs configuration will cause this.
Check the systemjs.config.ts file and make sure the json is valid.
I had a similar bug. I got:
Uncaught SyntaxError: Unexpected token = (index):16
because I tossed a semicolon at the end of the @Input() in the hero-detail.component file.
Hope this helps somebody.
The primary cause of this issue is that the file you are trying to import is an html file, not a js file. You can see this by using the network tab in Chrome to have a look at the file it actually imported.
My issue wasn't solved by the methods above. For me, this happened because I had routed all default routes through to the index.html page, which is how I get Angular deep linking working in Visual Studio Enterprise. When I requested a file without the extension, and it couldn't find that file, it would serve the default index.html page, which would start with a < character, and fail.
The giveaway for me was that when I put the full path to the exact file, it would work.
Anyhow, to fix this, I had to add an Ignore route for the node_modules folder in my RouteConfig.cs file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("node_modules/{*pathInfo}");
}
I had received the same error message. Similar to what other people mentioned, my case was caused by url rewrites, serving the html instead of the javascript expected by angular.
I am using lite-server/browser-sync to develop and host my app locally. To get the angular routing working properly, I was using
var history = require('connect-history-api-fallback')
to redirect relevant pushState navigation back to index.html. Ultimately, a misconfiguration in my typescript imports led to one request not being recognised as a js file and instead redirected to index.html. The difficulty was how to figure it out.
I found that you can enable verbose logging for the connect-history-api-fallback.
middleware: [history({
index: '/src/index.html',
verbose: true
})]
which then led me to find the culprit by scanning the log for redirected entries:
Not rewriting GET /node_modules/systemjs/dist/system.js because the path includes a dot (.) character.
Not rewriting GET /node_modules/core-js/client/shim.min.js because the path includes a dot (.) character.
Rewriting GET /src/culprit to /src/index.html
For those who read the whole thing and didn't found anything interesting, I may have another option for you.
I ran into the same problem because the website was deployed on more than 1 web server. The problem was related to different builds deployed on some servers.
Basically, you have 1 server with one version and another server with some other version. So, of course when you load balance you're likely to get 404 on some resources on some servers because the versions are different (remember the main.xxxxx.js where xxx is different at every build). And if you configured your webserver to return a 404 webpage - which happens a lot I guess - you get some HTML instead of the JS files then the unexpected token.
So, check your versions on each server !
For me, this error was caused because I served my angular frontend with a simple node express server as such:
app.use('/*', (req, res) => {
res.sendFile(path.join(__dirname,'index.html'));
});
but I had forgotten to specify that all static files should be served from the current directory with the line:
app.use(express.static(__dirname));
So every call for a static asset returned index.html. Woops. Once I added that line, everything was fine. Hope this can help someone down the line :)
참고URL : https://stackoverflow.com/questions/34387174/angular-2-quickstart-unexpected-token
'IT TIP' 카테고리의 다른 글
| Gerrit에서 주어진 패치 세트를 git-pull하는 방법은 무엇입니까? (0) | 2020.12.07 |
|---|---|
| v2.4에서 / [post-id]가 더 이상 사용되지 않으므로 개별 게시물을 검색하려면 어떻게해야합니까? (0) | 2020.12.07 |
| ExecutorService의 활성 스레드 (0) | 2020.12.07 |
| 디렉토리 나 파일에 쓸 수있는 권한을 어떻게 확인합니까? (0) | 2020.12.07 |
| VBA에서 문자열을 어떻게 연결할 수 있습니까? (0) | 2020.12.07 |