简体   繁体   中英

Is there a way to remove unnecessary 'require(...)'/'import "..."' statements when using Rollup

I am creating a library, we'll call it share that will be used in other services and am bundling the library using Rollup.js

share is a shared library that is used by several services, so I need to be able to treeshake the library. What is going on is... let's say I have service A and service B that depend on share .

  • service A uses googleapis which is one of the dependencies used by shared , however, googleapis is a peer dependency and is a true dependency of service A .

  • service B does not use googleapis at all and is not a dependency. No functions are even included in service B from shared where googleapis is used.


When bundling, both service A and service B only include the functions/attributes that are required. The problem I am running into is on service B , when I look at the generated bundle, there is the following line...

service A 's generated bundle

// ...
var path = require('path');
var googleapis = require('googleapis'); // works as expected
// ...

service B 's generated bundle

// ...
var path = require('path');
require('googleapis'); // this line is causing my issue
// ...

Simply removing the require('googleapis') on service B does fix the problem as this library isn't used at all, even globally, however, this is just the beginning of this shared library, and I'd much rather not have to manually remove unnecessary requires, or write a utility to strip them out if there is a simple fix to this issue.

I figured there would be some setting that I could pass along to treeshake , but I have yet to find what I'm looking for.

I figured out which property is responsible for this.

treeshake.moduleSideEffects


My solution was...

...
treeshake: {
   moduleSideEffects: (id) => !id.includes('googleapis')
}
...

which I will need to include to prevent bundling an empty require statement

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