【问题标题】:correct ES6 import for adding moment precise range plugin正确的 ES6 导入以添加时刻精确范围插件
【发布时间】:2018-01-04 20:52:19
【问题描述】:

我在 Angular 4 项目中使用 typescript,并希望使用 moment-precise-range-plugin。

我在https://momentjs.com/docs/#/use-it/typescript/ 之后安装了moment,但我想添加精确范围插件http://momentjs.com/docs/#/plugins/preciserange/

为精确范围插件安装 Node.js 位于 https://codebox.org.uk/pages/moment-date-range-plugin 并指定 require('moment-precise-range-plugin');,但没有安装 Typescript。

我试过import { Moment } from 'moment-precise-range-plugin';,但得到以下打字稿错误

Could not find a declaration file for module 'moment-precise-range-plugin'. 'c:/Users/[UserName]/app/node_modules/moment-precise-range-plugin/moment-precise-range.js' implicitly has an 'any' type. Try npm install @types/moment-precise-range-plugin if it exists or add a new declaration (.d.ts) file containing declare module 'moment-precise-range-plugin';'

非常欢迎任何想法!

【问题讨论】:

    标签: javascript angular typescript ecmascript-6 momentjs


    【解决方案1】:

    我在 Angular 4 项目中使用 moment-precise-range-plugin 并且能够通过以下方式导入它:

    import 'moment-precise-range-plugin';
    

    我是在导入时刻后导入的:import * as moment from 'moment';

    需要注意的一点:我的 TS linter 仍然警告我 preciseDiff() 会导致问题,但一切运行良好。试试看它是否有效。

    【讨论】:

    • 对于 Angular 7,将 @types/moment-precise-range-plugin 添加到您的项目中以保持编译。
    【解决方案2】:

    我通过在 src/typings.d.ts 中添加定义文件来修复它

    import * as moment from 'moment';
    
    export = moment;
    
    declare module 'moment' {
      interface Moment {
        preciseDiff(start: string | Date | moment.Moment): string;
      }
    }
    

    【讨论】:

      【解决方案3】:

      注意:我使用的是 Angular 10。

      将其导入为 -> import 'moment-precise-range-plugin';

      并添加以下 3 行:

      declare module 'moment' {
        function preciseDiff(start: string | Date | moment.Moment, end: string | Date | moment.Moment, convertToObject?: boolean): any;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        相关资源
        最近更新 更多