How to Disable Tree Shaking in Rollupjs

How to disable Tree shaking in rollupjs

Your entry file — main.js — needs to export any classes or other values that need to be accessible to the outside world:

// main.js
import Base from './Base.js';
import SubB from './SubB.js';
import SubA from './SubA.js';

export { Base, SubA, SubB };

optimize rollup config to enable tree shaking

As for now, the only valid solution I could find is to build separately all the files in the same tree structure inside a dist/ folder. I decided to build the files to provide Vue fileformat style blocks without further need for build or configuration from end consumer.

It looks like this after build :

/src
/index.js
/components
/index.js
/component1
/index.js
/Comp.vue
...
/componentN
/index.js
/Comp.vue
/directives
/index.js
/directive1
/index.js
...
/directiveN
/index.js

/dist
/index.js
/components
/index.js
/component1
/index.js
...
/componentN
/index.js
/directives
/index.js
/directive1
/index.js
...
/directiveN
/index.js

I created a small recursive function to find all 'index.js' and used this list with rollup multi entrypoint feature. hopefully, rollup creates all subfolders so there's no need for checks or mkdir -p.

// shorthand utility for 'find all files recursive matching regexp (polyfill for webpack's require.context)'
const walk = (directory, regexp) => {
let files = readdirSync(directory)

if (directory.includes('/examples'))
return []

return files.reduce((arr, file) => {
let path = `${directory}/${file}`
let info = statSync(path)

if (info.isDirectory())
return arr.concat(walk(path, regexp))
else if (regexp.test(file))
return arr.concat([path])
else
return arr
}, [])
}

// ...

const esm = walk(`${__dirname}/src`, /^index\.js$/)
.map(file => ({
input: file,

output: {
format: 'esm',
file: file.replace(`${__dirname}/src`, CONFIG.module)
},
...
}))

The last part of the process is to copy/paste package.json into dist/, cd into it and npm publish from it... This was integrated into our CI tasks, as it's not directly related to rollup or build, but rather publishing.

It's not perfect, but it's the only way I found due to lack of inputs.
I hope it'll help someone.



Related Topics



Leave a reply



Submit