网站搜索

TypeScript - 在启用 'no-any' TSLint 规则时如何使用 webpack 的 require?


我使用 Ionic 生成了一个 Ionic 4 项目:ionic start app sidemenu --type=angular。我现在想让代码检查规则更严格,并引入了 'no-any'。但不幸的是,代码检查失败。它给出了我以下提示:

ng lint app
Linting "app"...

ERROR: ./src/test.ts[10, 24]: Type declaration of 'any' loses type-safety. Consider replacing it with a more precise type.

Lint errors found in the listed files.

问题在于这一行:

declare const require: any;

关于此文件:

// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

我怀疑 require 是由 webpack 提供的。如果我理解正确,它应该在 @types/webpack/index.d.ts 中声明,并且我必须从 webpack 中引入它,而 webpack 会进一步在 @types 中查找它。然而,我找不到它在那里被声明。

我该如何解决这个问题?

答案#1

require 是 CommonJS (CJS) 模块系统的一部分。require 的类型定义可以在 @types/node 或 @types/webpack-env 包中找到。可以从 npm 安装其中一个:

npm install --save-dev @types/node