2

Seems like the tree shaking feature of Webpack helps to remove unused code from the bundle. However, Webpack does read these unreadable files. How do I tell Webpack not to read them?

Here is an example:

index.js

import { bar } from './bar';

bar();

bar/index.js

export { bar } from './bar';
export { foo } from './foo';

bar/foo.js

import fs from 'fs';

export function foo() {}

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  mode: 'production',
  module: {
    rules: [
      { sideEffects: false }
    ],
  },
  optimization: {
    usedExports: true
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

Running Webpack result in the following error: ERROR in ./src/bar/foo.js Module not found: Error: Can't resolve 'fs' in "/temp/webpack-test/src/bar'

I expect Webpack to not read the foo.js file because there is no route from the entry point to this file.

David
  • 2,528
  • 1
  • 23
  • 29

1 Answers1

0

This works as expected.

There is a route:

  1. ./src/index.js:
import { bar } from './bar';

-> by default routing to {folder}/index.js if bar is a directory

  1. bar/index.js:
export { foo } from './foo';

---> export .. from .. syntax also imports the designated file:

  1. bar/foo.js
import fs from 'fs';

You are getting

Error: Can't resolve 'fs' in "/temp/webpack-test/src/bar'

because fs isn't available in webpack default target: web configuration. You can bypass it by:

node: {
   fs: "empty"
},

but some things may not work.

Raz Ronen
  • 2,418
  • 2
  • 14
  • 26
  • Thanks Raz. I'm not concerned about the error. It was only to demonstrate the fact that Webpack parsed the `src/bar/foo.js` file. Since `foo` was not exported into the main `src/index.js` file, I would expect this file to be ignored. – David Aug 18 '20 at 03:12
  • 1
    Tree shaking is an optimization so it works after modules are parsed an built. Interesting to hear the community thoughts on if webpack should/shouldn’t parse those files at all. Maybe in future versions it wont – Raz Ronen Aug 18 '20 at 04:27