简体   繁体   中英

Ignore or replace dependencies' imports when bundling with Rollup

I'm bundling a JS library using Rollup. This lib has a dependency on @tensorflow/tfjs-core .

On tfjs's code, there's a function that fetches a URL. If it's in the browser environment, it uses the global fetch function; if it's not, it tries to import node-fetch .

Something among these lines:

fetch(path: string, requestInits?: RequestInit): Promise<Response> {
  if (env().global.fetch != null) {
    return env().global.fetch(path, requestInits);
  }

  if (systemFetch == null) {
    systemFetch = require('node-fetch');
  }

  return systemFetch(path, requestInits);
}

My library is made to run in the browser, so it always uses the global fetch function. However, Rollup still bundles node-fetch 's require in my lib's assets.

It should not be an issue, but some consumers are reporting errors when using the library in a React project that uses webpack:

Failed to compile.

./node_modules/[my lib]/index.js Cannot find module: 'node-fetch'. Make sure this package is installed.

You can install this package by running: npm install node-fetch.

Question is: is there some way I can tell Rollup not no bundle this?

I thought about replacing the require('node-fetch') by undefined after the bundle is generated, but it feels like a dirty hack. Any other sugestions?

PS: I believe marking node-fetch as external on consumer projects would fix the issue, but since I do not use node-fetch in my lib, it would be nice to remove it from final output.

Other package managers can include or exclude files based on the environment, test , development , production , etc.

There is any number of ways of implementing this, even going so far as

# Makefile

ENVIRONMENT ?= test

ROLLUP = $(which rollup)

ENVSUBST = $(which envsubst)

rollup.config.js: src/$(ENVIRONMENT)
    ${ENVSUBST} < $@ > $^
    ${ROLLUP} $^ -o $(ENVIRONMENT).js

If you created files named after your environments, you could compile them using

make -e environment=browser

I don't expect my code to work, only to express ideas.

There is this loc which is used to exclude node-fetch from the bundle. You could consider a similar approach in your rollup configuration. (I think) If you add that, node-fetch will/should not be a part of your minified library.

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