【问题标题】:How to use webpack require with 'no-any' tslint rule?如何使用带有“no-any” tslint 规则的 webpack 要求?
【发布时间】:2019-05-12 08:55:15
【问题描述】:

我使用 ionic 生成了一个 ionic 4 项目:ionic start app sidemenu --type=angular。 我现在想让 linting 规则更加严格,并引入了'no-any'。 但不幸的是,linting 失败了。 它给了我:

$ 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 中包含它,然后它会在@types 中查找它。 但是,我找不到它被声明为there

我该如何解决这个问题?

【问题讨论】:

  • 也许this 是你需要的?
  • 嗯...该函数没有提供context 函数,它在const context = require.context('./', true, /\.spec\.ts$/); 这一行中调用,它仍然是正确的吗?
  • 啊,我必须自己定义那个函数吗?
  • 您可能需要设置确切的类型而不是任何类型......类似于链接
  • 我为那个似乎有效的函数创建了一个定义,here 是它的要点。这是要走的路吗?

标签: typescript webpack tslint ionic4


【解决方案1】:

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

npm install --save-dev @types/node

【讨论】:

  • 安装@types/node@types/webpack-env满足tslint,但是在执行测试的时候,我得到ERROR in src/test.ts(17,25): error TS2339: Property 'context' does not exist on type 'NodeRequire'.webpack-env的类型好像有context函数的定义,所以我也尝试了import require from 'webpack-env';,但这给了我一堆错误:Module not found: Error: Can't resolve 'fs' in。我在这里做错了吗?
  • 好的,我搞定了,我必须import RequireFunction from 'webpack-env';declare const require: RequireFunction;,谢谢!
猜你喜欢
  • 2019-02-22
  • 2019-03-06
  • 2018-02-26
  • 2020-07-24
  • 2019-06-01
  • 2017-02-16
  • 2019-05-12
  • 2019-09-18
  • 2020-03-27
相关资源
最近更新 更多