【问题标题】:How to tell Webpack not to read (exclude) unreachable files by tree shaking?如何告诉 Webpack 不要通过摇树来读取(排除)无法访问的文件?
【发布时间】:2020-12-04 19:24:26
【问题描述】:

似乎 Webpack 的 tree shaking 功能有助于从包中删除未使用的代码。但是,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 文件,因为没有从入口点到该文件的路由。

【问题讨论】:

    标签: webpack tree-shaking


    【解决方案1】:

    这按预期工作。

    有一条路线:

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

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

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

    ---> export .. from .. 语法也导入指定的文件:

    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"
    },
    

    但有些事情可能行不通。

    【讨论】:

    • 谢谢拉兹。我不担心错误。这只是为了证明 Webpack 解析了 src/bar/foo.js 文件的事实。由于foo 没有导出到主src/index.js 文件中,我希望这个文件被忽略。
    • Tree Shaking 是一种优化,因此它在模块被解析并构建后工作。听听社区对 webpack 是否应该/不应该解析这些文件的想法很有趣。也许在未来的版本中它不会
    猜你喜欢
    • 1970-01-01
    • 2017-11-08
    • 2017-04-10
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    相关资源
    最近更新 更多