Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

javascript - 图书馆摇树在Angular 8(Tree shaking for libraries in Angular 8)

I'm planning on making a standalone angular service for Angular 8+, and I've been reading up on how to make it tree tree-shakable.

(我正计划为Angular 8+提供独立的角度服务,并且我一直在阅读如何使其可树状摇动。)

IIUC all we need to do is this :

(IIUC我们需要做的就是 :)

@Injectable({
  providedIn: 'root',
  useFactory: () => new Service('dependency'),
})
export class Service {
  constructor(private dep: string) {
  }
}

As this tells Angular how to construct the service.

(这样就告诉了Angular如何构建服务。)

Is this all we need to do?

(这就是我们需要做的吗?)

I've seen other NPM modules like this one use ModuleWithProviders like this:

(我看过其他类似这样的 NPM模块, 使用了这样的 ModuleWithProviders :)

 export class Module {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: Module,
      providers: [
        StripeScriptTag
      ],
    }
  }

I assume that this is not necessary because the providers array still does not describe how to instantiate the service.

(我认为这不是必需的,因为providers数组仍然没有描述如何实例化服务。)

  ask by Ole translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All you need is the

(您需要的是)

providedIn: 'root'

Services that are provided in root are tree shakeable.

(根目录中提供的服务可摇动树。)

If it is provided in the root then you get the same singleton instance in the entire application.

(如果它在根目录中提供,那么您将在整个应用程序中获得相同的单例实例。)

You only need to add it to a providers array if you want a new instance of the service across your module instead of the global singleton instance.

(如果您希望跨模块的新服务实例而不是全局单例实例,则只需将其添加到providers数组。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...