如何通过摇树树告诉Webpack不要读取排除无法访问的文件?

问题描述

似乎Webpack的摇树功能有助于从捆绑中删除未使用的代码。但是,Webpack会读取这些不可读的文件。如何告诉Webpack不要阅读它们?

这里是一个例子:

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'
  }
};

运行Webpack会导致以下错误ERROR in ./src/bar/foo.js Module not found: Error: Can't resolve 'fs' in "/temp/webpack-test/src/bar'

我希望Webpack不会读取foo.js文件,因为从入口点到此文件之间没有路由。

解决方法

这按预期工作。

有一条路线:

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

->如果bar是目录,则默认路由到{folder} /index.js

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

--->从..语法导出..也会导入指定的文件:

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

你正在得到

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

因为fs在Webpack的默认target: web配置中不可用。 您可以通过以下方法绕过它:

node: {
   fs: "empty"
},

但是某些事情可能无法正常工作。