Cómo usar el momento.biblioteca js en angular 2 typescript aplicación?
Traté de usarlo con enlaces typescript:
npm install moment --save
typings install moment --ambient -- save
Prueba.ts:
import {moment} from 'moment/moment';
Y sin:
npm install moment --save
Prueba.ts:
var moment = require('moment/moment');
Pero cuando llamo momento.format (), obtengo un error. Debería ser simple, ¿puede alguien proporcionar una combinación de línea de comandos / importación que funcione?
22 answers
Estamos usando módulos ahora,
Intenta import {MomentModule} from 'angular2-moment/moment.module';
Después de npm install angular2-moment
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-12-19 11:44:11
Actualización de Abril 2017:
A partir de la versión 2.13.0, Moment incluye un archivo de definición de typescript. https://momentjs.com/docs/#/use-it/typescript /
Simplemente instálelo con npm, en su consola escriba
npm install --save moment
Y luego en tu aplicación Angular, importar es tan fácil como esto:
import * as moment from 'moment';
¡Eso es todo, obtienes soporte completo de Typescript!
Bonus edit: Para escribir una variable o propiedad como Moment
en Typescript puede hacer esto, por ejemplo:
let myMoment: moment.Moment = moment("someDate");
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-06-20 13:53:49
moment
es un recurso global de terceros. El objeto moment vive en window
en el navegador. Por lo tanto, no es correcto import
en su aplicación angular2. En su lugar, incluya la etiqueta <script>
en su html que cargará el momento.archivo js.
Para hacer feliz a TypeScript puede agregar
declare var moment: any;
En la parte superior de sus archivos donde lo usa para detener los errores de compilación, o puede usar
///<reference path="./path/to/moment.d.ts" />
O use tsd para instalar el momento.d. ts archivo que TypeScript podría encontrar en es propio.
Ejemplo
import {Component} from 'angular2/core';
declare var moment: any;
@Component({
selector: 'example',
template: '<h1>Today is {{today}}</h1>'
})
export class ExampleComponent{
today: string = moment().format('D MMM YYYY');
}
Solo asegúrese de agregar la etiqueta de script en su html o el momento no existirá.
<script src="node_modules/moment/moment.js" />
Carga del módulomoment
Primero debe configurar un cargador de módulos como System.js para cargar los archivos commonjs momento
System.config({
...
packages: {
moment: {
map: 'node_modules/moment/moment.js',
type: 'cjs',
defaultExtension: 'js'
}
}
});
Luego para importar el momento en el archivo donde sea necesario use
import * as moment from 'moment';
O
import moment = require('moment');
EDITAR:
También Hay opciones con algunos preparadores como Webpack o SystemJS builder o Browserify que mantendrá el momento fuera del objeto de la ventana. Para obtener más información sobre estos, visite sus respectivos sitios web para obtener instrucciones.
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-28 02:57:26
Lo siguiente funcionó para mí.
Primero, instale las definiciones de tipo por un momento.
typings install moment --save
(Nota: NO --ambient
)
Entonces, para trabajar en torno a la falta de una exportación adecuada:
import * as moment from 'moment';
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-03-29 16:48:02
Yo diría lo siguiente:
npm install moment --save
A su systemjs.config.js
array de archivos map
agregue:
'moment': 'node_modules/moment'
A packages
matriz añadir:
'moment': { defaultExtension: 'js' }
En tu componente.ts uso:
import * as moment from 'moment/moment';
Y eso es todo. Puedes usar desde la clase de tu componente:
today: string = moment().format('D MMM YYYY');
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-16 11:34:52
Para usarlo en un proyecto Typescript
necesitará instalar moment:
npm install moment --save
Después del momento de instalación, puede usarlo en cualquier archivo .ts
después de importarlo:
import * as moment from "moment";
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-02-20 12:21:16
--- Actualización 11/01/2017
Typings ahora está en desuso y fue reemplazado por npm @types. A partir de ahora, obtener declaraciones de tipo no requerirá herramientas aparte de npm. Para usar Moment no necesitará instalar las definiciones de tipo a través de @types porque Moment ya proporciona sus propias definiciones de tipo.
Por lo tanto, se reduce a solo 3 pasos:
1-Momento de instalación que incluye las definiciones de tipo:
npm install moment --save
2-Añadir el script etiqueta en su archivo HTML:
<script src="node_modules/moment/moment.js" />
3 - Ahora solo puedes usarlo. Periodo.
today: string = moment().format('D MMM YYYY');
--- Respuesta original
Esto se puede hacer en solo 3 pasos:
1 - Install moment definition - *.d. ts archivo:
typings install --save --global dt~moment dt~moment-node
2-Añade la etiqueta script en tu archivo HTML:
<script src="node_modules/moment/moment.js" />
3 - Ahora solo puedes usarlo. Periodo.
today: string = moment().format('D MMM YYYY');
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-01-11 14:35:46
Con ng CLI
> npm install moment --save
In app.módulo
import * as moment from 'moment';
providers: [{ provide: 'moment', useValue: moment }]
En el componente
constructor(@Inject('moment') private moment)
De esta manera se importa momento una vez
ACTUALIZACIÓN Angular = > 5
{
provide: 'moment', useFactory: (): any => moment
}
Para mí funciona en prod con aot y también con universal
No me gusta usar ninguna pero usar el momento.Momento Tengo
Error Typescript Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.
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-12-19 11:44:46
La biblioteca angular2-moment tiene tuberías como {{myDate | amTimeAgo}} para usar .archivos html.
Esas mismas tuberías también se pueden acceder como funciones de Typescript dentro de una clase de componente (.ts) file. Primero instale la biblioteca como se indica:
npm install --save angular2-moment
En el node_modules / angular2-el momento ahora será ".tubo.d. ts" archivos como calendar.tubo.d. ts, formato de fecha.tubo.d. ts y muchos más.
Cada uno de ellos contiene el nombre de la función Typescript para el equivalente pipe, por ejemplo, DateFormatPipe () es la función para amDateFormatPipe .
Para usar DateFormatPipe en tu proyecto, impórtalo y agrégalo a tus proveedores globales en app.módulo.ts:
import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]
Luego, en cualquier componente donde desee usar la función, impórtelo en la parte superior, inyecte en el constructor y use:
import { DateFormatPipe } from "angular2-moment";
....
constructor(......., public dfp: DateFormatPipe) {
let raw = new Date(2015, 1, 12);
this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}
Para usar cualquiera de las funciones siga este proceso. Sería bueno si hubiera una forma de obtener acceso a todas las funciones, pero ninguna de las soluciones anteriores funcionó para mí.
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-14 15:27:27
Si está de acuerdo en agregar más paquetes de terceros, usé la biblioteca angular2-moment. La instalación fue bastante sencilla, y debe seguir las últimas instrucciones en el README. También instalé typings como resultado de esto.
Funcionó como un encanto para mí, y apenas agregó ningún código para que funcione.
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-03-19 00:38:35
No estoy seguro si esto sigue siendo un problema para la gente, sin embargo... Usando SystemJS y MomentJS como biblioteca, esto lo resolvió para mí
/*
* Import Custom Components
*/
import * as moment from 'moment/moment'; // please use path to moment.js file, extension is set in system.config
// under systemjs, moment is actually exported as the default export, so we account for that
const momentConstructor: (value?: any) => moment.Moment = (<any>moment).default || moment;
Funciona bien a partir de ahí para mí.
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-06-06 12:09:52
Para angular2 RC5 esto funcionó para mí...
Primer momento de instalación a través de npm
npm install moment --save
Luego importa el momento en el componente que deseas usar
import * as moment from 'moment';
Finalmente configure el momento en systemjs.config.js "map"y" packages "
// map tells the System loader where to look for things
var map = {
....
'moment': 'node_modules/moment'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
...
'moment': { main:'moment', defaultExtension: 'js'}
};
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-31 10:13:35
Momento.js ahora soporta TypeScript en v2.14. 1.
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-08 07:18:58
Además de la respuesta de SnareChop, tuve que cambiar el archivo typings para momentjs.
En moment-node.d.ts
sustituí:
export = moment;
Con
export default moment;
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-02-17 22:59:38
Intenta agregar "allowSyntheticDefaultImports": true
a tu tsconfig.json
.
¿Qué hace la bandera?
Esto básicamente le dice al compilador de TypeScript que está bien usar una instrucción de importación ES6, es decir,
import * as moment from 'moment/moment';
En un módulo CommonJS como Moment.js que no declara una exportación predeterminada. El indicador solo afecta a la comprobación de tipos, no al código generado.
Es necesario si utiliza SystemJS como cargador de módulos. El indicador se activará automáticamente si le indica a su compilador de TS que utiliza SystemJS:
"module": "system"
Esto también eliminará cualquier error lanzado por los IDE si están configurados para hacer uso de tsconfig.json
.
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-06-27 09:53:20
Para angular2 con systemjs y jspm tenía que hacer:
import * as moment_ from 'moment';
export const moment = moment_["default"];
var a = moment.now();
var b = moment().format('dddd');
var c = moment().startOf('day').fromNow();
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-07 19:23:11
Para usuarios de ANGULAR CLI
Usar bibliotecas externas está en la documentación aquí:
Https://github.com/angular/angular-cli/wiki/stories-third-party-lib
Simplemente instale su biblioteca a través de
Npm install lib-name save save
E impórtalo en tu código. Si la biblioteca no incluye tipografías, puedes instalarlos usando:
Npm install lib-name save save
Npm install @types / lib-name save save-dev
Luego abra src/tsconfig.app.json y añadirlo a la matriz de tipos:
"tipos": ["lib-name"]
Si la biblioteca para la que agregó tipografías solo se usa en su e2e pruebas, en su lugar use e2e / tsconfig.e2e. json. Lo mismo ocurre con las pruebas unitarias y src / tsconfig.spec.json.
Si la biblioteca no tiene tipografías disponibles en @types/, puede todavía usarlo mediante la adición manual tipos para ello:
Primero, crea una tipografía.archivo d. ts en su carpeta src/.
Este archivo se incluirá automáticamente como definición de tipo global. Luego, en el directorio src/tipificaciones.d. ts, añádase el siguiente código:
Declare module 'typeless-package';
Finalmente, en el componente o archivo que usa la biblioteca, agregue código siguiente:
Importar * como typelessPackage desde 'typeless-package'; Tipo de paquete.método();
Hecho. Nota: es posible que necesite o encuentre útil definir más tipos para la biblioteca que intentas usar.
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-10 16:22:02
Lo siguiente funcionó para mí:
typings install dt~moment-node --save --global
El moment-node no existe en el repositorio typings. Es necesario redirigir a Definitivamente escrito con el fin de hacer que funcione utilizando el prefijo dt.
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-24 22:09:48
Con systemjs lo que hice es, dentro de mi systemjs.configuración He añadido mapa para moment
map: {
.....,
'moment': 'node_modules/moment/moment.js',
.....
}
Y luego puede importar fácilmente moment
simplemente haciendo
import * as moment from 'moment'
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-11-02 11:31:43
Sé que es un hilo viejo, pero para mí la solución más simple que realmente funcionó fue:
- Instalándolo primero
npm install moment --save
- En mis componentes que lo requieren de node_modules y lo utilizan:
const moment = require('../../../node_modules/moment/moment.js');
@Component({...})
export class MyComponent {
...
ngOnInit() {
this.now = moment().format();
}
...
}
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-14 00:22:13
Mi propia versión de usar Momento en Angular
npm i moment --save
import * as _moment from 'moment';
...
moment: _moment.Moment = _moment();
constructor() { }
ngOnInit() {
const unix = this.moment.format('X');
console.log(unix);
}
Primero importa el momento como _moment
, luego declara moment
variable con el tipo _moment.Moment
con un valor inicial de _moment()
.
La importación simple de moment no le dará ninguna finalización automática, pero si declara moment con type Moment
interfaz desde _moment
espacio de nombres desde 'moment'
el paquete inicializado con moment namespace invocado _moment()
le da la finalización automática de las api de moment.
Creo que esto es lo más forma angular de usar el momento sin usar @types
typings
o proveedores de angular, si está buscando finalización automática para bibliotecas javascript vanilla como moment.
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
2018-05-05 08:02:59
Seguí los consejos para permitir allowSyntheticDefaultImports (ya que no hay exportación desde el momento para usar para mí), usando System. Luego seguí el consejo de alguien para usar:
import moment from 'moment';
Con el momento mapeado en mi sistema.js config. Las otras declaraciones de importación no funcionarían para mí, por alguna razón
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-19 20:06:45