简体   繁体   中英

How to add third party dependencies to typescript reference projects

I have three typescript projects which all reference a single 'core' module.

project-a
project-b
project-c
core

I would like to add some utilities that rely on a third party dependency. This can be an express middleware, winston logger, etc. For example, a default winston logger. So inside core , i may have

core/src/logger/index.ts

import winston from 'winston'
export default winston.createLogger()

This file is referenced by project-a and project-b but not project-c . How do I set up my core project in a way that accommodates this? I was thinking the following steps:

  • Move this file into a brand new typescript project
  • Reference in project-a and project-b
  • Add winston to dependencies and install as usual npm i -S winston
  • Run tsc -b on project-a

Would this be the ideal way of doing it? I would be adding third party references to the shared code, but no way of enforcing a dependency to be installed similar to peerDependencies in node.

There are many ways you could accomplish this, but one of the easiest might be dependency injection .

When you initialize your core code, you could optionally pass in a type the implements some " Logger " interface (which you could define), then in project-a and -b you could pass in a class, etc, that implements the winston logger. In project-c, you simply don't pass in any logger, and so core won't use it.

In this case, your core project would have no direct reference to winston. Only projects -a and -b would have it, and project-c would be free from unnecessary dependencies.

However, depending on your setup, tree shaking may eliminate the extra dependencies in project-c, so you might be fine as-is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM