Ответ 1
Я тоже получил эту ошибку.
В моем случае я назвал неправильный tsconfig.json
. Когда я изменился на tsconfig.json
, снова запустил npm install
, а затем npm start
все это сработало.
Я пытаюсь запустить quickstart из Angular 2, но я не понимаю, что он работает. Я выяснил некоторые подобные вопросы, но я не нашел ответа. Кто-нибудь может мне помочь?
Этот мой код.
app.component.ts
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }
main.ts
import {bootstrap} from 'angular2/platform/browser'
import {AppComponent} from './app.component'
bootstrap(AppComponent);
index.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- 1. Load libraries -->
<!-- IE required polyfills, in this exact order -->
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/systemjs/dist/system-polyfills.js"> </script>
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.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>
<!-- 2. Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
package.json
{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",
"tsc": "tsc",
"tsc:w": "tsc -w",
"lite": "lite-server",
"typings": "typings",
"postinstall": "typings install"
},
"license": "ISC",
"dependencies": {
"angular2": "2.0.0-beta.7",
"systemjs": "0.19.22",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.5.15"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.1.0",
"typescript": "^1.8.2",
"typings":"^0.6.8"
}
}
tscoding.json
{
"compilerOptions": {
"target": "ES6",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
npm запуск
> npm start
> [email protected] start /Users/dpcrespo/Google Drive/projects/tutorials/angular/angular2-quickstart
> concurrently "npm run tsc:w" "npm run lite"
[0]
[0] > [email protected] tsc:w /Users/dpcrespo/Google Drive/projects/tutorials/angular/angular2-quickstart
[0] > tsc -w
[0]
[1]
[1] > [email protected] lite /Users/dpcrespo/Google Drive/projects/tutorials/angular/angular2-quickstart
[1] > lite-server
[1]
[0] Version 1.8.7
[0] Syntax: tsc [options] [file ...]
[0]
[0] Examples: tsc hello.ts
[0] tsc --out file.js file.ts
[0] tsc @args.txt
[0]
[0] Options:
[0] --allowJs Allow javascript files to be compiled.
[0] --allowSyntheticDefaultImports Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
[0] --allowUnreachableCode Do not report errors on unreachable code.
[0] --allowUnusedLabels Do not report errors on unused labels.
[0] -d, --declaration Generates corresponding '.d.ts' file.
[0] --experimentalDecorators Enables experimental support for ES7 decorators.
[0] --forceConsistentCasingInFileNames Disallow inconsistently-cased references to the same file.
[0] -h, --help Print this message.
[0] --init Initializes a TypeScript project and creates a tsconfig.json file.
[0] --jsx KIND Specify JSX code generation: 'preserve' or 'react'
[0] --mapRoot LOCATION Specifies the location where debugger should locate map files instead of generated locations.
[0] -m KIND, --module KIND Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
[0] --moduleResolution Specifies module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).
[0] --newLine NEWLINE Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix).
[0] --noEmit Do not emit outputs.
[0] --noEmitOnError Do not emit outputs if any errors were reported.
[0] --noFallthroughCasesInSwitch Report errors for fallthrough cases in switch statement.
[0] --noImplicitAny Raise error on expressions and declarations with an implied 'any' type.
[0] --noImplicitReturns Report error when not all code paths in function return a value.
[0] --noImplicitUseStrict Do not emit 'use strict' directives in module output.
[0] --outDir DIRECTORY Redirect output structure to the directory.
[0] --outFile FILE Concatenate and emit output to single file.
[0] --preserveConstEnums Do not erase const enum declarations in generated code.
[0] --pretty KIND Stylize errors and messages using color and context. (experimental)
[0] -p DIRECTORY, --project DIRECTORY Compile the project in the given directory.
[0] --reactNamespace Specifies the object invoked for createElement and __spread when targeting 'react' JSX emit
[0] --removeComments Do not emit comments to output.
[0] --rootDir LOCATION Specifies the root directory of input files. Use to control the output directory structure with --outDir.
[0] --sourceMap Generates corresponding '.map' file.
[0] --sourceRoot LOCATION Specifies the location where debugger should locate TypeScript files instead of source locations.
[0] --suppressImplicitAnyIndexErrors Suppress noImplicitAny errors for indexing objects lacking index signatures.
[0] -t VERSION, --target VERSION Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES2015' (experimental)
[0] -v, --version Print the compiler version.
[0] -w, --watch Watch input files.
[0] @<file> Insert command line options and files from a file.
[0] npm run tsc:w exited with code 0
[1] Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
[1] ** browser-sync options **
[1] { injectChanges: false,
[1] files: [ './**/*.{html,htm,css,js}' ],
[1] server: { baseDir: './', middleware: [ [Function], [Function] ] } }
[1] [BS] Access URLs:
[1] ------------------------------------
[1] Local: http://localhost:3000
[1] External: http://192.168.0.9:3000
[1] ------------------------------------
[1] UI: http://localhost:3001
[1] UI External: http://192.168.0.9:3001
[1] ------------------------------------
[1] [BS] Serving files from: ./
[1] [BS] Watching files...
[1] 16.03.16 11:30:42 304 GET /index.html
[1] 16.03.16 11:30:42 304 GET /styles.css
[1] 16.03.16 11:30:42 304 GET /node_modules/es6-shim/es6-shim.min.js
[1] 16.03.16 11:30:42 304 GET /node_modules/systemjs/dist/system- polyfills.js
[1] 16.03.16 11:30:42 304 GET /node_modules/angular2/bundles/angular2-polyfills.js
[1] 16.03.16 11:30:42 304 GET /node_modules/systemjs/dist/system.src.js
[1] 16.03.16 11:30:42 304 GET /node_modules/angular2/es6/dev/src/testing/shims_for_IE.js
[1] 16.03.16 11:30:42 304 GET /node_modules/rxjs/bundles/Rx.js
[1] 16.03.16 11:30:42 304 GET /node_modules/angular2/bundles/angular2.dev.js
[1] 16.03.16 11:30:42 404 GET /app/main.js
В моем браузере
Мне нравится, если он не перенаправляет файл main.ts на main.js
Спасибо заранее.
Я тоже получил эту ошибку.
В моем случае я назвал неправильный tsconfig.json
. Когда я изменился на tsconfig.json
, снова запустил npm install
, а затем npm start
все это сработало.
Попробуйте изменить карту в конфиге. В моем случае у меня есть
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}},
map: { 'app': './app' }
});
где/app - это папка, в которой созданы компоненты (.ts)
В вашем index.html ссылка на app/main. У вас есть файл main.ts в папке с именем app или в корне?
tsconfig.js
должен быть tsconfig.json
Я думаю, что это была проблема с разделом system.config. Значение карты было "./ angular2/src/app", что неверно. для меня установлен следующий код.
<script>
System.config({
transpiler: 'typescript',
typescriptOptions: { emitDecoratorMetadata: true },
packages: {'app': {defaultExtension: 'ts'}},
map: { 'app': './app' }
});
System.import('app/hello_world_main')
.then(null, console.error.bind(console));
</script>
map: {'app': './app'} - убедитесь, что компоненты находятся в папке приложения приложения.
Проверьте, установлены ли во всем мире типизации и lite-server ваш cmd, введите typings
, если вы не установили их с помощью npm install -g typings lite-server
.
И добавьте следующий код в начало файла main.ts в каталоге app:
/// <reference path="../typings/browser.d.ts" />
Теперь запустите npm install && npm run
когда команда
npm start
main.ts передается в .js файл, а перед именем каждого файла добавляется слово "app".
но в systemjs.configs.js
он вызывает main.js
не app.main.js
в моем случае, я изменил
'app': { main: 'main.js', defaultExtension: 'js' },
(который указан на официальной странице angular/angular -2-quickstart) до
'app': { main: 'app.main.js', defaultExtension: 'js' },
и он работает хорошо.
не уверен, что это лучшее решение... (пожалуйста, дайте мне отзыв.)
в вашем systemjs.config.js измените отображение для вашего приложения на правильный путь к вашим файлам, поэтому... строка:
'app': 'app',//'dist',
измените на:
'app': 'ваш путь здесь', оставьте пустым для относительного пути.
Измените tsconfig.json на
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
Я могу предложить несколько возможностей.
1. У вас есть main.ts
в вашем решении? если не создать один:)
2. Если у вас есть. Это вариант, что ваш начальный проект не компилирует файлы typescript. Итак, попробуйте выполнить команду: npm run tsc
Он должен выбросить папку main.js
в typescript по умолчанию, она находится в той же папке, что и файл .ts
.
3. И последнее: ваша команда запуска должна содержать обычную команду tsc. Лучше начать проект (в package.json), так как
npm run tsc && concurrently \"npm run tsc:w\" ...
(таким образом, ваш проект не запускается, если не удалось выполнить компиляцию ts
).
Предполагая, что tscoding.json
является опечаткой, для меня это сработало, когда я обновил свои npm
и node
до последних версий.
Настройка работает нормально, если у меня есть версия npm
версии 3.10.3
и node
версии v6.5.0
.
Думаю, вам нужно обновить версию node и npm..
Если Node.js и npm еще не установлены на вашем компьютере, установите их. Наши примеры требуют node v5.x.x или выше и npm 3.x.x или выше. Чтобы проверить, какую версию вы используете, запустите node -v и npm -v в окне терминала.
Это происходит из раздела предварительных условий руководства по быстрому запуску.
Добавьте это:
// DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
transpiler: 'ts',
typescriptOptions: {
tsconfig: true
},
meta: {
'typescript': {
"exports": "ts"
}
},
в файле systemjs.config.js
для компиляции main.ts
.
в вашем tsconfig.json, если вы добавили
"outDir":"yourOutDir"
вам нужно изменить расположение отображения в файле system.config.js
// our app is within the app folder
app: 'yourOutDir/app',
Это может показаться случайным, но с
<base href='/'>
как первый тег в index.html
перед загрузкой любого другого js решил эту проблему
Ясно, что
обновить systemjs.config.js
файл
Из
'app': 'app',
Для
'app': './app',
после
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
...
У меня была проблема с окнами..
e.x. папка проекта - "tmp"
tsconfig.json изменился следующим образом
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"outDir":"tmp"
}
}
systemjs.config.js, как этот
// our app is within the app folder
app: 'app',
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: 'main.js',
defaultExtension: 'js'
},
он работает.
Проблема устранена путем удаления "outDir": "js" в файле tsconfig.js. Теперь все скомпилированные файлы .js приложений сохраняются в папке приложения вместо папки js.
Попробуйте вручную скомпилировать файлы typescript с помощью tsc -p src
. Затем запустите сервер dev.
index.html и styles.css должны находиться в корневой папке проекта (не app/)
Посмотрите на структуру проекта внизу страница быстрого запуска
Привет, у меня была такая же проблема, но она решает создать папку приложение внутри корневой папки и переместить файл main.ts и app.component.ts к ней структура папок учебника