我们有一个基于pino
并使用typescript的私有npm日志记录模块。我们正在编译并发布到npm。将模块导入应用程序时,我们会收到错误:
node_modules/@scope/logging/lib/index.d.ts(1,23): error TS2688: Cannot find type definition file for 'pino'
node_modules/@scope/logging/lib/index.d.ts(2,23): error TS7016: Could not find a declaration file for module 'pino'. 'C:/app/node_modules/pino/pino.js' implicitly has an 'any' type. Try `npm install @types/pino` if it exists or add a new declaration (.d.ts) file containing `declare module 'pino';`
的package.json
{
"name": "@scope/logging",
"version": "1.0.0",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"dependencies": {
"pino": "4.16.1"
},
"devDependencies": {
"@types/pino": "4.7.1",
"typescript": "2.8.3"
}
}
tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"moduleResolution": "node",
"inlineSources": true,
"inlineSourceMap": true,
"declaration": true,
"outDir": "lib",
"baseUrl": ".",
"typeRoots": ["node_modules/@types"],
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
},
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"noImplicitReturns": true,
"noUnusedLocals": true
},
"typeAcquisition": {
"enable": true
},
"include": ["src/**/*"],
"exclude": [
"**/*.spec.ts",
"node_modules",
"src/**/node_modules"
]
}
LIB / index.ts
import * as pino from 'pino';
const isProduction = process.env.NODE_ENV === 'production';
const logLevel = process.env.LOG_LEVEL ? process.env.LOG_LEVEL.toLowerCase() : (isProduction ? 'warn' : 'debug');
const logOpts: pino.LoggerOptions = {
safe: true,
level: logLevel,
prettyPrint: !!isProduction,
};
export const logger = (category: string): pino.Logger => {
return pino({
name: category,
...logOpts,
});
};
使用tsc
进行编译后,输出文件如下:
LIB / index.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const pino = require("pino");
const isProduction = process.env.NODE_ENV === 'production';
const logLevel = process.env.LOG_LEVEL ? process.env.LOG_LEVEL.toLowerCase() : (isProduction ? 'warn' : 'debug');
const logOpts = {
safe: true,
level: logLevel,
prettyPrint: !!isProduction,
};
exports.logger = (category) => {
return pino(Object.assign({ name: category }, logOpts));
};
LIB / index.d.ts
/// <reference types="pino" />
import * as pino from 'pino';
export declare const logger: (category: string) => pino.Logger;
现在发布后,我将此模块作为依赖项并导入它:
应用程序/ index.ts
import { logger } from '@scope/logging';
const log = logger('Application');
log.info('Working');
该错误让我相信在编译时我需要在模块中包含@types/pino/index.d.ts
,但我不知道如何做到这一点。
答案 0 :(得分:0)
我认为答案是将@types/pino
作为dependency
包含在模块的package.json中,因此在应用程序中使用时,它会与日志记录模块一起安装。包含类型作为依赖项的感觉很奇怪,但它必须自动安装,而peerDependency不会这样做。