In Rollup config, how does one use moduleSideEffects to import side effect files AND their dependencies?

Viewed 1013

Many things are being included in my bundles that I do not want because they are being considered as side-effectful when they are not. Promise calls and the like. So I am experimenting with setting moduleSideEffects to a function* that marks only those files that really have side effects as side-effectful. However, I'm running into a problem: Rollup will not include a file marked as side-effectful if all it's dependencies are not side-effectful.

// a.js
export function se() {
   console.log('Side effect');
}

// b.js
import { se } from 'b.js';
se();

I mark b.js as side-effectful because I only want a.js to be included where b.js is included. Now consider these two possible main.js files:

// main.js
import 'a.js';

Here a.js is not included in the bundle, correctly, as it is not side-effectful.

// main.js
import 'b.js';

Here neither a.js or b.js are included, even though b.js side-effectful. When I mark a.js as side-effectful they are both included, however that means it is also included in the previous version of main.js.

I'm having trouble working out if this is a bug or intended behaviour, or how to work around it.

Rollup 2.21.0

(* I use a function because I could not get an array of relative, absolute or blob paths to work as moduleSideEffects, which is a separate problem. I'm obviously missing something about how they should be defined.)

2 Answers

As mentioned here: https://rollupjs.org/guide/en/#treeshake

To specify which modules having side effect, you can do as follow:

{
...
  treeshake: {
    moduleSideEffects: ['@saleshood/design-system/dist/style.css'],
  },
}

Notice: the string params refer to modules that have side effect NOT its consumer. For example, for this file to keep loading the css file:

// src/hocs/DSHOC.tsx
import React from 'react';
import { ConfigProvider } from 'antd';

import '@saleshood/design-system/dist/style.css';

export const DSHOC = {...}

Use

moduleSideEffects: ['@saleshood/design-system/dist/style.css'],

Not

moduleSideEffects: ['src/hocs/DSHOC.tsx'],

The answer is that moduleSideEffects: true only switches on the test for side-effects, it doesn't mark every module as side-effectful. So if there are no side-effects the file will, correctly, still not be included.

Related