Angular2 5 minute install bug-require no está definido


Estoy haciendo el Angular2 inicio rápido de 5 minutos.

Alrededor de la mitad del tutorial ahora, tengo los siguientes archivos configurados correctamente:

  • index.html,
  • app.componente.ts
  • app / boot.ts
  • paquete.json
  • tconfig.json

Corrí npm start y obtengo este error:


Uncaught ReferenceError: require is not defined(anonymous function) @ boot.js:1 angular2-polyfills.js:143 Uncaught TypeError: Cannot read property 'split' of undefinedreadMemberExpression @ system.src.js:1456(anonymous function) @ system.src.js:3224(anonymous function) @ system.src.js:3749complete @ system.src.js:2487run @ angular2-polyfills.js:138zoneBoundFn @ angular2-polyfills.js:111


Encontré este enlace sobre el uso de la cuña es6 e incluí <script src="node_modules/es6-shim/es6-shim.js"></script>.

Sin embargo, todavía estoy recibiendo el Uncaught ReferenceError: require is not defined error.


App.componente.ts

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

(app / boot.ts)

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'

bootstrap(AppComponent);

Index.html

<html>

  <head>
    <title>Angular 2 QuickStart</title>

    <!-- 1. Load libraries -->
    <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>

    <!-- 2. Configure SystemJS -->
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>

  </head>

  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>

</html>

Paquete.json

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
  },
  "license": "ISC",
  "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"
  }
}

Tconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

La aplicación compilada/boot.js

introduzca la descripción de la imagen aquí

Último registro de npm start

introduzca la descripción de la imagen aquí

Author: Sangwin Gawande, 2016-01-11

7 answers

Encontré que la razón por la que la mía trajo un error era debido módulo establecido como "commonjs" en mi tsconfig.json archivo, cambiándolo a sistema arreglado, ahora se ve como abajo

{
  "compilerOptions": {
        "target": "es5",
        "module": "system",
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true
    },
  "exclude": [
    "node_modules"
  ]
}

EDITAR Esta respuesta se basó en Angular 2 beta 17 .Basado en el tiempo de esta respuesta y los rápidos cambios que angular 2 ha sufrido, esto puede no funcionar más.

 27
Author: Michael Gikaru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 15:27:48

Tengo el mismo error en el angular2.versión beta15.

Lo he resuelto eliminando

format: 'register',

Fuera del índice.html

<script>
    System.config({
        packages: {
            app: {
                format: 'register',
                defaultExtension: 'js'
            }
        }
    });
</script>
 18
Author: Reinhard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-15 22:58:15

OK finalmente conseguí que mi aplicación' básica ' funcionara.

Primero mi problema fue que npm start no estaba compilando mis archivos typescript .ts.

De este post , encontré una respuesta aquí No puedo encontrar el módulo externo 'angular2 / angular2' - Angular2 con Typescript

Necesitaba ejecutar npm install -g tsd@latest para actualizar mi definición de TypeScript. Justo después de eso tuve que actualizar la Definición (TSD) de TypeScript para Angular2 tsd install angular2.

Después de esto se hizo yo todavía estaba recibiendo errores de mi bota.archivo js.

En Lugar de esto import {AppComponent} from './app.component'

Necesitaba escribirlo así import {AppComponent} from '../app.component.js'


Ahora funciona! https://github.com/leongaban/angular2quickstart

introduzca la descripción de la imagen aquí


Un problema molesto es que npm start todavía no está compilando automáticamente los archivos typescript, por lo que todavía tengo que compilar manualmente cada uno .archivo ts a mano tsc app.component.ts --module system

 11
Author: Leon Gaban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

Estoy usando angular-cli y ahora usa webpack, pero estaba recibiendo este error al cargar css. Agregué declare let require: any; antes de mi componente y ahora funciona.

 3
Author: Helzgate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-21 05:36:00

Si estás siguiendo el tutorial de Actualización a Angular2, esto puede morderte:

Asegúrese de no seguir cargando manualmente los archivos javascript convertidos cuando convierta los archivos a typescript y utilice los cargadores de módulos para cargarlos.

Había convertido algunos archivos a TS, pero todavía estaba cargando los archivos JS originales (ahora transpiled) en el índice.HTML. Si haces esto, seguirás obteniendo "require is not defined" porque la biblioteca "require" no se ha cargado aun.

En pocas palabras: Por lo tanto, si obtienes "require is not defined", coloca una instrucción debugger antes de la línea ofensiva (para mí, fue import { Injectable } desde '@angular/core'), mira qué archivos de origen se han cargado y asegúrate de no seguir cargando el archivo manualmente.

 2
Author: user910531,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 22:54:55

Tuve un problema similar que fue causado por el hecho de que estaba configurando el formato incorrecto para el paquete. El formato del paquete es muy importante para que SystemJS sepa cómo manejarlo. Documentación Aquí

<script>
 System.config({
    packages: {
        appjs: {
            format: 'register',
            defaultExtension: 'js'
        },
        primeng: {
            format: 'cjs',
            defaultExtension: 'js'
        }
    },
    map: {
        'primeng': 'lib'
    }
});
 System.import('appjs/main').then(null, console.error.bind(console));
</script>

En mi caso estaba configurando el formato de primeng a "register" en lugar de "cjs".

 1
Author: Nicolae Anghel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 16:39:05

Usé importación "inválida":

import {UrlSegment} from '@angular/router/index';

Después de eliminar /index comenzó a compilar de nuevo.

 0
Author: D R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 14:00:14