programing

angular 2 typecript 앱에서 memant.js 라이브러리를 사용하는 방법?

instargram 2023. 4. 2. 09:43
반응형

angular 2 typecript 앱에서 memant.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');

하지만 내가 전화했을 때.format() 에러가 표시됩니다.간단해야 합니다. 누구나 사용할 수 있는 명령줄과 Import 조합을 제공할 수 있습니까?

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타이프 스크립트 §:

let myMoment: moment.Moment = moment("someDate");

moment존재하는 은 순간window브라우저에 표시됩니다. 때문에 그것은 않습니다.import222222222222222222 ''를 시켜 주세요.<script> filedload moment.dload를 합니다.

TypeScript를 활성화하려면

declare var moment: any;

컴파일 오류를 막기 위해 파일을 사용하는 파일 맨 위에 있습니다.

///<reference path="./path/to/moment.d.ts" />

또는 tsd를 사용하여 typeScript가 자체적으로 찾을 수 있는 memant.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

먼저 System.js와 같은 모듈로더를 설정하여 moment commonjs 파일을 로드해야 합니다.

System.config({
    ...
    packages: {
        moment: {
            map: 'node_modules/moment/moment.js',
            type: 'cjs',
            defaultExtension: 'js'
        }
    }
});

그런 다음 모멘트를 필요한 파일로 가져오려면

import * as moment from 'moment';

또는

import moment = require('moment');

편집:

웹 팩이나 시스템 등의 번들러 옵션도 있습니다.JS Builder 또는 Browserify를 사용하면 모멘트가 창 객체에 닿지 않습니다.상세한 것에 대하여는, 각 Web 사이트를 참조해 주세요.

다음은 나에게 효과가 있었다.

먼저 모멘트의 유형 정의를 설치합니다.

typings install moment --save

(의: 음)--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"CHANGE: "CHANGE:

npm install moment --save

후, 에서도 사용할 수 ..ts「 」 「 」 。

import * as moment from "moment";

Angular 7+(8, 9, 10, 11도 지원):

: 명령어 1에 설치 : " " " "npm install moment --save

2: 에는 아무것도 추가하지 마십시오.app.module.ts

를 3 위에 하세요.component같은 .import * as moment from 'moment';

4: ㄹ 수 요.moment코드 어디든지.예를 들어 다음과 같습니다.

myDate = moment(someDate).format('MM/DD/YYYY HH:mm');

---2017년 11월 1일 갱신

입력은 폐지되어 npm @types로 대체되었습니다.앞으로는 npm 이외에는 툴이 필요하지 않습니다.모멘트는 이미 자체 유형 정의를 제공하므로 모멘트를 사용하기 위해 @types를 통해 유형 정의를 설치할 필요가 없습니다.

즉, 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.discloss에서

import * as moment from 'moment';

providers: [{ provide: 'moment', useValue: moment }]

구성 요소에서

constructor(@Inject('moment') private moment)

이렇게 하면 모멘트를 한 번 가져올 수 있습니다.

업데이트 각도 => 5

{
   provide: 'moment', useFactory: (): any => moment
}

나는 aot과 함께 prod에서 일하며 또한 유니버설과 함께 일합니다.

나는 모멘트를 사용하는 것 외에는 아무 것도 좋아하지 않는다.내가 얻은 순간

Error   Typescript  Type 'typeof moment' is not assignable to type 'Moment'. Property 'format' is missing in type 'typeof moment'.

angular2-moment 라이브러리에는 .html 파일에서 사용하는 {{myDate | amTimeAgo}} 등의 파이프가 있습니다.

이러한 파이프는 구성 요소 클래스(.ts) 파일 내의 유형 스크립트 함수로도 액세스할 수 있습니다.먼저 지시에 따라 라이브러리를 설치합니다.

npm install --save angular2-moment

node_modules/angular2-motent에는 calendar.pipe.d.ts, date-format.pipe.d.ts 의 ".pipe.d.ts" 파일이 포함됩니다.

각 파이프에는 동등한 파이프의 Typescript 함수 이름이 포함됩니다.를 들어 DateFormatPipe()amDateFormatPipe 함수입니다.

프로젝트에서 DateFormatPipe를 사용하려면 DateFormatPipe를 app.module.ts의 글로벌 프로바이더에 Import하여 추가합니다.

import { DateFormatPipe } from "angular2-moment";
.....
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, ...., DateFormatPipe]

그런 다음 함수를 사용할 모든 구성 요소에서 함수를 맨 위에 가져오고 생성자에 주입한 후 다음을 사용합니다.

import { DateFormatPipe } from "angular2-moment";
....
constructor(.......,  public dfp: DateFormatPipe) {
    let raw = new Date(2015, 1, 12);
    this.formattedDate = dfp.transform(raw, 'D MMM YYYY');
}

이 기능을 사용하려면 다음 절차를 따릅니다.모든 기능에 접근할 수 있는 방법이 하나 있다면 좋겠지만, 위의 솔루션 중 어느 것도 제게는 효과가 없었습니다.

angular2 RC5는 이게 나한테 효과가 있었어...

npm을 통한 첫 설치 순간

npm install moment --save

그런 다음 사용할 구성 요소에서 모멘트를 가져오십시오.

import * as moment from 'moment';

마지막으로 systemjs.config.config.config "map"과 "map"에서 모멘트를 설정합니다.

// 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'}
  };

SpearChop의 답변 외에 monentj의 타이핑 파일도 변경해야 했습니다.

인 in inmoment-node.d.ts대체: 체 대?

export = moment;

와 함께

export default moment;

서드파티 패키지를 추가해도 괜찮으시다면, 저는 angular2-moment 라이브러리를 사용했습니다.인스톨은 매우 간단해, README 의 최신의 순서에 따라서 행해 주세요.그 결과, 타이핑도 인스톨 했습니다.

마법처럼 작동했고, 작동시키기 위한 코드도 거의 추가하지 않았어요.

이것이 여전히 사람들에게 문제가 되는지는 잘 모르겠지만...시스템 사용JS 및 모멘트JS는 도서관으로써 해결되었다.

/*
 * 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;

난 거기서부터 잘 돼.

Moment.js는 v2.14.1에서 TypeScript를 지원하게 되었습니다.

참조: https://github.com/moment/moment/pull/3280

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);    

}

import 가져오기 간 가져오기 순 가져오기_moment, , then declare , 그 후 선언합니다.moment variable with type 유형 변수_moment.Moment기의 초기 가치로_moment().

일반적인 중요성은 다음과 같은 자동 완성되지 않지만, 반 져 일 동 으 로 료 import plain 모 만 공 우 comple 경 선 wont moment않 of auto momentMoment interface from 에서 인터페이스하다._moment'moment' initialized initialized invalled with the moment namespace orbled "가 호출되었습니다._moment()API를 사용하다

하지 않고 각도가 높은 이라고 생각합니다.@types typingsmoment와 의 자동 , provider.javascript 라 or 、 ascriptascript 、 providers or 、 providersangular 、 providersangularangularangularangular ( provider provider provider or or or or ) 。

번 더 써보세요."allowSyntheticDefaultImports": trueyour tsconfig.json.

깃발은 무엇을 하나요?

이는 기본적으로 TypeScript 컴파일러에 ES6 Import 스테이트먼트를 사용해도 좋다는 것을 나타냅니다.

import * as moment from 'moment/moment';

공통으로기본 내보내기를 선언하지 않는 Moment.js와 같은 JS 모듈.이 플래그는 생성된 코드가 아닌 유형 확인에만 영향을 줍니다.

시스템을 사용하는 경우 필요합니다.모듈 로더로서의 JS.TS 컴파일러에 시스템을 사용한다고 말하면 플래그가 자동으로 켜집니다.JS:

"module": "system"

, IDE 「IDE」 「IDE」 「IDE」 「IDE」 「IDE」 「IDE」 「IDE」 「」를 되어 있는 , 됩니다.tsconfig.json.

ANGILE CLI 사용자용

외부 라이브러리의 사용 방법에 대해서는, 다음의 메뉴얼을 참조해 주세요.

https://github.com/angular/angular-cli/wiki/stories-third-party-lib

를 사용하여 라이브러리를 설치하기만 하면 됩니다.

npm install lib-name --save

코드로 Import합니다.라이브러리에 입력이 없는 경우 다음을 사용하여 설치할 수 있습니다.

npm install lib-name --save

npm install @types/lib-name --save-dev

그런 다음 src/tsconfig.app.json을 열고 유형 배열에 추가합니다.

"types" : ["lib-name"]

입력한 내용을 추가한 라이브러리가 e2e 테스트에서만 사용되는 경우 대신 e2e/tsconfig.e2e.json을 사용하십시오.유닛 테스트 및 src/tsconfig.spec.json에서도 마찬가지입니다.

라이브러리에 @types/에서 사용할 수 있는 타이핑이 없는 경우에도 수동으로 타이핑을 추가하여 사용할 수 있습니다.

먼저 src/ 폴더에 typings.d.ts 파일을 만듭니다.

이 파일은 글로벌 유형 정의로 자동으로 포함됩니다.그런 다음 src/typings.d.ts에 다음 코드를 추가합니다.

모듈을 'typeless-displayed'로 선언한다.

마지막으로 라이브러리를 사용하는 구성 요소 또는 파일에 다음 코드를 추가하십시오.

*를 'typeless-package'에서 typelessPackage로 Import합니다.typelessPackage는 typelessPackage입니다.메서드();

완료. 참고: 사용하려는 라이브러리의 더 많은 타이핑을 정의해야 할 수도 있습니다.

다음과 같은 것이 도움이 되었습니다.

typings install dt~moment-node --save --global

모멘트 노드가 타이핑 저장소에 없습니다.프리픽스 dt를 사용하여 동작시키려면 "확실히 입력"으로 리다이렉트해야 합니다.

systemjs 및 jspm을 사용하는 angular2의 경우 다음 작업을 수행해야 합니다.

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();

System을 사용하여 Synthetic Default Imports를 허용하도록 조언에 따랐습니다.그 후, 나는 다른 사람의 조언을 따라 다음과 같이 했다.

import moment from 'moment';

모멘트가 system.js 설정에 매핑되어 있습니다.다른 수입 명세서는 왠지 통하지 않습니다.

systemjs에서는 systemjs.config에 맵을 추가했습니다.moment

map: {
   .....,
   'moment': 'node_modules/moment/moment.js',
   .....
}

그러면 쉽게 Import할 수 있습니다.moment하는 것만으로

import * as moment from 'moment'

언급URL : https://stackoverflow.com/questions/35166168/how-to-use-moment-js-library-in-angular-2-typescript-app

반응형