Angular 2 Typescript 앱에서 moment.js 라이브러리를 사용하는 방법은 무엇입니까?
typescript 바인딩과 함께 사용하려고했습니다.
npm install moment --save
typings install moment --ambient -- save
test.ts :
import {moment} from 'moment/moment';
그리고없이 :
npm install moment --save
test.ts :
var moment = require('moment/moment');
그러나 moment.format ()을 호출하면 오류가 발생합니다. 간단해야합니까, 누구나 작동하는 명령 줄 / 가져 오기 조합을 제공 할 수 있습니까?
2017 년 4 월 업데이트 :
버전 2.13.0부터 Moment에는 유형 스크립트 정의 파일이 포함되어 있습니다. https://momentjs.com/docs/#/use-it/typescript/
콘솔 유형으로 npm으로 설치하십시오.
npm install --save moment
그런 다음 Angular 앱에서 가져 오기는 다음과 같이 쉽습니다.
import * as moment from 'moment';
그게 다야, Typescript를 완벽하게 지원합니다!
보너스 편집 :Moment
Typescript에서 와 같이 변수 또는 속성을 입력하려면 다음과 같이하십시오 .
let myMoment: moment.Moment = moment("someDate");
moment
타사 글로벌 리소스입니다. 모멘트 객체 window
가 브라우저에 있습니다. 따라서 import
angular2 애플리케이션에서 올바르지 않습니다 . 대신 <script>
moment.js 파일을로드 할 태그를 HTML에 포함 시키 십시오.
TypeScript를 행복하게하려면 추가 할 수 있습니다
declare var moment: any;
파일 상단에서 컴파일 오류를 중지하는 데 사용하거나
///<reference path="./path/to/moment.d.ts" />
또는 tsd를 사용하여 TypeScript가 자체적으로 찾을 수있는 moment.d.ts 파일을 설치하십시오.
예
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');
}
HTML에 스크립트 태그를 추가하십시오. 그렇지 않으면 순간이 존재하지 않습니다.
<script src="node_modules/moment/moment.js" />
모듈 로딩 moment
먼저 moment.js 파일을로드하려면 System.js와 같은 모듈 로더를 설정해야 합니다.
System.config({
...
packages: {
moment: {
map: 'node_modules/moment/moment.js',
type: 'cjs',
defaultExtension: 'js'
}
}
});
그런 다음 필요한 순간에 파일로 순간을 가져옵니다.
import * as moment from 'moment';
또는
import moment = require('moment');
편집하다:
Webpack, SystemJS 빌더 또는 Browserify와 같은 일부 번 들러에는 창 오브젝트에서 벗어나는 옵션도 있습니다. 이에 대한 자세한 내용은 해당 웹 사이트를 방문하여 지시하십시오.
다음은 나를 위해 일했습니다.
먼저 유형 정의를 설치하십시오.
typings install moment --save
(참고 : NOT --ambient
)
그런 다음 적절한 수출 부족 문제를 해결하려면 다음을 수행하십시오.
import * as moment from 'moment';
나는 다음과 같이 갈 것이다.
npm install moment --save
당신으로 systemjs.config.js
파일의 map
배열 추가 :
'moment': 'node_modules/moment'
에 packages
배열 추가 :
'moment': { defaultExtension: 'js' }
component.ts에서 다음을 사용하십시오. import * as moment from 'moment/moment';
그리고 그게 다야. 컴포넌트 클래스에서 사용할 수 있습니다.
today: string = moment().format('D MMM YYYY');
우리는 지금 모듈을 사용하고 있습니다.
시험 import {MomentModule} from 'angular2-moment/moment.module';
후 npm install angular2-moment
http://ngmodules.org/modules/angular2-moment
Typescript
프로젝트 에서 사용 하려면 순간을 설치해야합니다.
npm install moment --save
설치 후, .ts
파일을 가져온 후 모든 파일 에서 사용할 수 있습니다 .
import * as moment from "moment";
--- 업데이트 11/01/2017
타이핑 은 더 이상 사용되지 않으며 npm @types 로 대체되었습니다 . 이제부터는 형식 선언을 얻는 데 npm 외에 다른 도구가 필요하지 않습니다. Moment를 사용하려면 @types를 통해 유형 정의를 설치할 필요가 없습니다. Moment는 이미 자체 유형 정의를 제공하기 때문입니다.
따라서 3 단계로 줄어 듭니다.
1-유형 정의가 포함 된 설치 모멘트 :
npm install moment --save
2-HTML 파일에 스크립트 태그를 추가하십시오.
<script src="node_modules/moment/moment.js" />
3-이제 그냥 사용할 수 있습니다. 기간.
today: string = moment().format('D MMM YYYY');
--- 원래 답변
이 작업은 3 단계 만 거치면됩니다.
1-설치 모멘트 정의- * .d.ts 파일 :
typings install --save --global dt~moment dt~moment-node
2-HTML 파일에 스크립트 태그를 추가하십시오.
<script src="node_modules/moment/moment.js" />
3-이제 그냥 사용할 수 있습니다. 기간.
today: string = moment().format('D MMM YYYY');
ng CLI로
> npm install moment --save
app.module에서
import * as moment from 'moment';
providers: [{ provide: 'moment', useValue: moment }]
구성 요소에서
constructor(@Inject('moment') private moment)
이렇게하면 순간을 한 번 가져올 수 있습니다
각도 업데이트 => 5
{
provide: 'moment', useFactory: (): any => moment
}
나를 위해 aot와 prod로 일하고 또한 보편적으로 일합니다.
I dont like using any but using moment.Moment I got
Error Typescript Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.
The angular2-moment library has pipes like {{myDate | amTimeAgo}} to use in .html files.
Those same pipes can also be accessed as Typescript functions within a component class (.ts) file. First install the library as instructed:
npm install --save angular2-moment
In the node_modules/angular2-moment will now be ".pipe.d.ts" files like calendar.pipe.d.ts, date-format.pipe.d.ts and many more.
Each of those contains the Typescript function name for the equivalent pipe, for example, DateFormatPipe() is the function for amDateFormatPipe.
To use DateFormatPipe in your project, import and add it to your global providers in app.module.ts:
import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]
Then in any component where you want to use the function, import it on top, inject into the constructor and 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');
}
To use any of the functions follow this process. It would be nice if there was one way to gain access to all the functions, but none of the above solutions worked for me.
For Angular 7+ (Supports 8 also):
1: Install moment by command npm install moment --save
2: Do not add anything in the app.module.ts
3: Just add import statement in top of your component
or any other file like this: import * as moment from 'moment';
4: Now you can use moment
anywhere in your code. Just like:
myDate = moment(someDate).format('MM/DD/YYYY HH:mm');
If you're okay adding more third-party packages, I used the angular2-moment library. Installation was pretty straightforward, and you should follow the latest instructions on the README. I also installed typings as a result of this.
Worked like a charm for me, and barely added any code to get it working.
Not sure if this is still an issue for people, however... Using SystemJS and MomentJS as library, this solved it for me
/*
* 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;
Works fine from there for me.
for angular2 RC5 this worked for me...
first install moment via npm
npm install moment --save
Then import moment in the component that you want to use it
import * as moment from 'moment';
lastly configure moment in systemjs.config.js "map" and "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'}
};
In addition to SnareChop's answer, I had to change the typings file for momentjs.
In moment-node.d.ts
I replaced:
export = moment;
with
export default moment;
Moment.js now supports TypeScript in v2.14.1.
See: https://github.com/moment/moment/pull/3280
My own version of using Moment in 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);
}
First import moment as _moment
, then declare moment
variable with type _moment.Moment
with an initial value of _moment()
.
Plain import of moment wont give you any auto completion but if you will declare moment with type Moment
interface from _moment
namespace from 'moment'
package initialized with moment namespace invoked _moment()
gives you auto completion of moment's api's.
I think this is the most angular way of using moment without using @types
typings
or angular providers, if you're looking auto completion for vanilla javascript libraries like moment.
Try adding "allowSyntheticDefaultImports": true
to your tsconfig.json
.
What does the flag do?
This basically tells the TypeScript compiler that it's okay to use an ES6 import statement, i. e.
import * as moment from 'moment/moment';
on a CommonJS module like Moment.js which doesn't declare a default export. The flag only affects type checking, not the generated code.
It is necessary if you use SystemJS as your module loader. The flag will be automatically turned on if you tell your TS compiler that you use SystemJS:
"module": "system"
This will also remove any errors thrown by IDEs if they are configured to make use of the tsconfig.json
.
for angular2 with systemjs and jspm had to do:
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();
For ANGULAR CLI users
Using external libraries is in the documentation here:
https://github.com/angular/angular-cli/wiki/stories-third-party-lib
Simply install your library via
npm install lib-name --save
and import it in your code. If the library does not include typings, you can install them using:
npm install lib-name --save
npm install @types/lib-name --save-dev
Then open src/tsconfig.app.json and add it to the types array:
"types":[ "lib-name" ]
If the library you added typings for is only to be used on your e2e tests, instead use e2e/tsconfig.e2e.json. The same goes for unit tests and src/tsconfig.spec.json.
If the library doesn't have typings available at @types/, you can still use it by manually adding typings for it:
First, create a typings.d.ts file in your src/ folder.
This file will be automatically included as global type definition. Then, in src/typings.d.ts, add the following code:
declare module 'typeless-package';
Finally, in the component or file that uses the library, add the following code:
import * as typelessPackage from 'typeless-package'; typelessPackage.method();
Done. Note: you might need or find useful to define more typings for the library that you're trying to use.
I followed advice to allow allowSyntheticDefaultImports (since there is no export from moment to use for me), using System. Then I followed someone's advice to use:
import moment from 'moment';
With moment being mapped in my system.js config. The other import statements wouldn't work for me, for some reason
The following worked for me:
typings install dt~moment-node --save --global
The moment-node does not exist in typings repository. You need to redirect to Definitely Typed in order to make it work using the prefix dt.
With systemjs what I did is, inside my systemjs.config I added map for moment
map: {
.....,
'moment': 'node_modules/moment/moment.js',
.....
}
And then you can easily import moment
just by doing
import * as moment from 'moment'
I know it's an old thread, but for me the simplest solution that actually worked was:
- Installing it first
npm install moment --save
- In my components requiring it from node_modules and use it:
const moment = require('../../../node_modules/moment/moment.js');
@Component({...})
export class MyComponent {
...
ngOnInit() {
this.now = moment().format();
}
...
}
'Programming' 카테고리의 다른 글
Android Studio에 libs 디렉토리가 없습니다 (0) | 2020.05.06 |
---|---|
데이터베이스에 대한 모든 연결을 종료하는 스크립트 (RESTTEDTED_USER ROLLBACK 이상) (0) | 2020.05.06 |
단위 테스트 안티 패턴 카탈로그 (0) | 2020.05.06 |
EditText가 비어 있는지 확인하십시오. (0) | 2020.05.06 |
numpy : 배열에서 고유 한 값에 대한 가장 효율적인 빈도 수 (0) | 2020.05.06 |