我正在尝试为这个灯塔文件创建一个.d.ts
,并且我很难理解如何处理默认的导出
https://github.com/GoogleChrome/lighthouse/blob/master/lighthouse-core/index.js#L28
module.exports = function(url, flags = {}, configJSON) {
const startTime = Date.now();
return Promise.resolve().then(_ => {
// set logging preferences, assume quiet
flags.logLevel = flags.logLevel || 'error';
log.setLevel(flags.logLevel);
// Use ConfigParser to generate a valid config file
const config = new Config(configJSON, flags.configPath);
const connection = new ChromeProtocol(flags.port, flags.hostname);
// kick off a lighthouse run
return Runner.run(connection, {url, flags, config})
.then(lighthouseResults => {
// Annotate with time to run lighthouse.
const endTime = Date.now();
lighthouseResults.timing = lighthouseResults.timing || {};
lighthouseResults.timing.total = endTime - startTime;
return lighthouseResults;
});
});
};
module.exports.getAuditList = Runner.getAuditList;
module.exports.traceCategories = require('./gather/driver').traceCategories;
module.exports.Audit = require('./audits/audit');
module.exports.Gatherer = require('./gather/gatherers/gatherer');
在这个阶段,我的项目中有一个lighthouse.d.ts
文件:
declare module "lighthouse" {
export interface flags {
port: number;
disableCpuThrottling: boolean;
disableDeviceEmulation: boolean;
disableNetworkThrottling: boolean;
}
export default function lighthouse(url: string, flags: flags, perfConfig: any): any
}
它似乎打得很好。如果我使用import * as lighthouse from "lighthouse";
导入,我可以在需要的地方做lighthouse.default
和lighthouse.flags
。
但是如果我运行我的代码,我会得到TypeError: lighthouse.default is not a function
。我被迫使用export =
吗?如果没有选择,如何使用export =
但导出函数、flags
类型和getAuditList
、traceCategories
、Audit
、Gatherer
发布于 2017-11-17 00:17:03
这就是公共as模块导出默认内容的方式.
module.exports.default = ...;
..。在代码样本中没有它的迹象。该模块只导出一个函数并为其分配一些属性。尝试将此作为.d.ts的起点:
declare module "lighthouse" { // the module name must be in quotes
const lighthouse: { // it must be a "const".
//here starts the signature "(...): any " that describes the object as callable
(url: string,
flags: {
port?: number; // all of these flags keys must be "?"
disableCpuThrottling?: boolean; // because the parameter initializer
disableDeviceEmulation?: boolean; // is an empty {}
disableNetworkThrottling?: boolean; //
} = {},
perfConfig: any): any;
// and here are all the properties that the library has attached to the function.
getAuditList: ...; //
traceCategories: ...; // give them the correct type for a better compiler support
Audit: ...; //
Gatherer: ...; //
}
export = lighthouse; // <-finally
}
这是在.ts文件中必须使用的方法。
import * as lighthouse from "lighthouse";
lighthouse(...); //<- invoke it directly
...lighthouse.traceCategories...; //<- get access to one of it's properties
使用"export =“不会将函数包装在对象中,因此转移的.js文件如下所示:
var lighthouse = require("lighthouse");
lighthouse(...); // this is the desired result and not _whateverName.lighthouse(...);
https://stackoverflow.com/questions/47327369
复制相似问题