javascript - 摇树不适用于 webpack 4 和 semantic-ui-react

标签 javascript reactjs webpack semantic-ui

我只从 semantic-ui-react 导入一个组件

import { Button as SemanticButton} from 'semantic-ui-react';

但是在运行 webpack -p 之后,我在 bundle 中看到了来自 Semantic UI 的所有组件,它的大小超过 300KB(如果没有 Semantic UI,大约 30KB)。 我安装了所有最新版本:webpack@4.14.0; semantic-ui-react@0.81.3

这是我的 webpack.config.js

module.exports = {
  entry: './src/index.js',
  resolve: {
    modules: [
      path.resolve('./'),
      'node_modules',
    ],
    extensions: ['*', '.js', '.jsx', '.css', '.less'],
  },
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  externals: {
    react: {
      root: 'React',
      commonjs: 'react',
      commonjs2: 'react',
      amd: 'React',
    },
    'react-dom': {
      root: 'ReactDOM',
      commonjs: 'react-dom',
      commonjs2: 'react-dom',
      amd: 'ReactDOM',
    },
    'prop-types': {
      root: 'PropTypes',
      commonjs: 'prop-types',
      commonjs2: 'prop-types',
      amd: 'PropTypes',
    },
  },
};

我做错了什么吗?如何使 tree shaking 与 semantic-ui-react 一起工作?我不想看到 bundle 中未使用的组件。

最佳答案

这个问题的解决方案变得相当简单。你只需要正确配置 Babel 即可。

Simply specifying "modules": false in your babel-preset-env config gets Babel to behave how we want, which allows webpack to analyze your dependency tree and shake off those unused dependencies. Furthermore, this process doesn't cause compatibility issues, as webpack ends up converting your code into a format that's widely compatible, anyway.

所以 .babelrc 可以看起来像这样:

{
  "presets": [
    ["env", {
      "modules": false
    }]
  ]
}

Source

关于javascript - 摇树不适用于 webpack 4 和 semantic-ui-react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51175095/

相关文章:

javascript - 无法使用 Webpack 加载 ES6 模块

javascript - 单选按钮 : "Uncaught syntax error, unrecognized expression" 的 jQuery 值

javascript - 在 React 组件中组合定义的 props 的最佳方法

javascript - jQuery/javascript 动态 hasClass 条件

node.js - 在 Heroku 上部署 React 应用和 API 的最佳实践

webpack - 如何根据环境变量自定义 Service Worker?

javascript - 在javascript中将UTC字符串转换为纪元时间

javascript - 如何在 react-leaflet 中动态更改 Circle 组件的颜色 Prop ?

javascript - 如何配置 WebPack DevServer 来处理 React JS 中的 POST 请求?

css - 如何在 npm 包中导出和导入样式?