How to tell Webpack not to read (exclude) unreachable files by tree shaking?

Viewed 224

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.

1 Answers

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.

Related