【问题标题】:Replace Require statement with Import statement causing error将 Require 语句替换为 Import 语句导致错误
【发布时间】:2017-06-07 07:30:47
【问题描述】:

我正在尝试使用Ajv(并且我正在使用打字稿)。

import { Ajv } from "ajv";

let ajv = new Ajv({allErrors: true});

只是想知道为什么会出现此错误:

[ts] 'Ajv' 仅指一种类型,但在这里用作值。

我使用它的方式与文档相同:

var Ajv = require('ajv');
var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid) console.log(validate.errors);

但是我使用 import 而不是 require 所以我没有设置变量,所以我猜这是导致错误的原因。使用import 而不是require 时如何定义使用变量?

所有代码:

import { Injectable } from "@angular/core";
import { Http, Headers, Response } from "@angular/http";
import { Configuration } from "../shared/configuration.model";
import { Observable } from "rxjs/Rx";
import { Ajv } from "ajv";

@Injectable()
export class ValidateJSONSchemaService {

    constructor(private http: Http) { }

    public valJson(json, schemaFile: string) {
        return new Promise((resolve, reject) => {
            this.http.get(schemaFile)
                .toPromise()
                .then(fileContents => fileContents.json())
                .then((schema) => {
                    let ajv = new Ajv({allErrors: true});
                    ajv.validate(schema, json) ? 
                    resolve() :
                    reject(new Error("JSON does not conform to schema: " + ajv.errorsText()));
                }, err => reject(
                    new Error("Unable to get schema file contents:" + err))
                );
        });
    };
}

【问题讨论】:

  • 你试过import * as Ajv from 'ajv'吗?
  • @elclanrs 成功了,谢谢
  • @elclanrs,您能否将您的评论升级为答案,以便其他人可以找到它?谢谢

标签: typescript import require


【解决方案1】:

正如@elclanrs 所说,使用import * as Ajv from 'ajv'

不是想把功劳放在心上,但已经一年了,我几乎错过了答案,因为没有任何东西被标记为答案。

【讨论】:

    【解决方案2】:

    只是为了在节点 10.x 中添加 TS 3.45 和 Angular 8.x,我必须使用

    // @ts-ignore
    import Ajv = require('ajv');
    

    注意@ts-ignore,因为 TSlint 会抱怨以这种方式导入模块

    然后在我的代码中,我可以正常使用它。

    const ajv = new Ajv();
    

    使用import * as Ajv from 'ajv' angular 无法正确构建,因为我一直看到此错误

     error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
    

    Typescript 编译器建议您使用此导入方法解析

     Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.
    

    希望这会帮助其他使用 angular 8 的人。

    【讨论】:

      【解决方案3】:

      我需要为一个节点项目导入它,我已经将它导入为:

      import Ajv from 'ajv'
      

      然后,您可以将其用作:

      ...
      let ajv = new Ajv({allErrors: true});
      ...
      

      我正在使用节点 v12.8.1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-06
        相关资源
        最近更新 更多