Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tree Shaking Not Working - React #7473

Closed
7 tasks done
malavshah9 opened this issue Mar 26, 2022 · 6 comments
Closed
7 tasks done

Tree Shaking Not Working - React #7473

malavshah9 opened this issue Mar 26, 2022 · 6 comments
Labels
cannot reproduce The bug cannot be reproduced pending triage

Comments

@malavshah9
Copy link

malavshah9 commented Mar 26, 2022

Describe the bug

I have monorepo setup with component library.

  1. I am Using Lerna for that
  2. Using vite for multiple project creation inside that packages.
  3. Using component kit as component library to use those components.

I am using vite as bundler for building library as well as other projects inside that packages folder.

Currently component library is pretty big, which is around 8 MB after build.

This 8 MB is being downloaded for each project even though I am not using all components for particular project.

Checked with production build.

  1. Vite Config file of Component Lib.
import { defineConfig } from 'vite';
import path from 'path';
import typescript from '@rollup/plugin-typescript';

export default defineConfig({
    build: {
        lib: {
            entry: path.resolve(__dirname, 'src/index.ts'),
            name: 'index',
            formats: ['es'],
        },
        rollupOptions: {
            external: ['react', 'react-router-dom', 'rc-time-picker', 'moment'],
            output: {
                globals: {
                    react: 'react',
                },
                strict: false,
                dir: 'lib',
                sourcemap: false,
            },
            plugins: [
                typescript({
                    allowJs: true,
                    allowSyntheticDefaultImports: true,
                    exclude: path.resolve(__dirname, './node_modules/**'),
                    declaration: true,
                    declarationDir: 'lib',
                    rootDir: path.resolve(__dirname, './src'),
                    sourceRoot: path.resolve(__dirname, './src/index.ts'),
                    emitDeclarationOnly: true,
                }),
            ],
        },
    },
});`
  1. Used following vite config file for each package
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],

  build: {
    polyfillDynamicImport: true,
  },
  publicDir: "public",
  define: {
    global: "window", // fix for packages that support both node and browser
  },
});

Reproduction

Use reproduction step mentioned in description.

System Info

System:
    OS: macOS 11.5.2
    CPU: (8) arm64 Apple M1
    Memory: 83.00 MB / 8.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.6.0 - ~/.nvm/versions/node/v16.6.0/bin/node
    Yarn: 1.22.17 - /opt/homebrew/bin/yarn
    npm: 7.19.1 - ~/.nvm/versions/node/v16.6.0/bin/npm
  Browsers:
    Chrome: 99.0.4844.83
    Firefox: 98.0.2
    Safari: 14.1.2

Used Package Manager

yarn

Logs

System:
    OS: macOS 11.5.2
    CPU: (8) arm64 Apple M1
    Memory: 100.28 MB / 8.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 16.6.0 - ~/.nvm/versions/node/v16.6.0/bin/node
    Yarn: 1.22.17 - /opt/homebrew/bin/yarn
    npm: 7.19.1 - ~/.nvm/versions/node/v16.6.0/bin/npm
  Browsers:
    Chrome: 99.0.4844.83
    Firefox: 98.0.2
    Safari: 14.1.2

Validations

@malavshah9 malavshah9 changed the title Tree Shaking Not Working Tree Shaking Not Working - React Mar 26, 2022
@github-actions
Copy link

Hello @malavshah9. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.

@bluwy
Copy link
Member

bluwy commented Mar 27, 2022

Please provide a repo/stackblitz to showcase the issue. The steps alone isn't enough to tell what doesn't work. From a glance, this doesn't sound like an issue with Vite if dynamic imports are used for some features of the app.

@malavshah9
Copy link
Author

@bluwy Here is the Repo Link.

Pushed with node modules intentionally as using some private packages.

My problem is:

Even though I have only imported Button Component, Why did bundle get the code for both component Input and Button.

@Codex-
Copy link
Contributor

Codex- commented Jun 1, 2022

Experiencing issues with tree shaking in basically the same style, using specific paths and esm but still getting an entire UI lib bundled:

image

@sapphi-red
Copy link
Member

@malavshah9 I was not able to reproduce it. Icon Component is included in bundle.

This is the output. (formatted with prettier)

import { R as p, j as b, a as O } from './vendor.933a898e.js'
const g = function () {
  const t = document.createElement('link').relList
  if (t && t.supports && t.supports('modulepreload')) return
  for (const e of document.querySelectorAll('link[rel="modulepreload"]')) o(e)
  new MutationObserver((e) => {
    for (const r of e)
      if (r.type === 'childList')
        for (const i of r.addedNodes)
          i.tagName === 'LINK' && i.rel === 'modulepreload' && o(i)
  }).observe(document, { childList: !0, subtree: !0 })
  function n(e) {
    const r = {}
    return (
      e.integrity && (r.integrity = e.integrity),
      e.referrerpolicy && (r.referrerPolicy = e.referrerpolicy),
      e.crossorigin === 'use-credentials'
        ? (r.credentials = 'include')
        : e.crossorigin === 'anonymous'
        ? (r.credentials = 'omit')
        : (r.credentials = 'same-origin'),
      r
    )
  }
  function o(e) {
    if (e.ep) return
    e.ep = !0
    const r = n(e)
    fetch(e.href, r)
  }
}
g()
var d = { exports: {} },
  f = {}
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/ var u = Object.getOwnPropertySymbols,
  v = Object.prototype.hasOwnProperty,
  j = Object.prototype.propertyIsEnumerable
function h(s) {
  if (s == null)
    throw new TypeError('Object.assign cannot be called with null or undefined')
  return Object(s)
}
function _() {
  try {
    if (!Object.assign) return !1
    var s = new String('abc')
    if (((s[5] = 'de'), Object.getOwnPropertyNames(s)[0] === '5')) return !1
    for (var t = {}, n = 0; n < 10; n++) t['_' + String.fromCharCode(n)] = n
    var o = Object.getOwnPropertyNames(t).map(function (r) {
      return t[r]
    })
    if (o.join('') !== '0123456789') return !1
    var e = {}
    return (
      'abcdefghijklmnopqrst'.split('').forEach(function (r) {
        e[r] = r
      }),
      Object.keys(Object.assign({}, e)).join('') === 'abcdefghijklmnopqrst'
    )
  } catch {
    return !1
  }
}
_()
/** @license React v17.0.2
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */ var w = p,
  m = 60103
f.Fragment = 60107
if (typeof Symbol == 'function' && Symbol.for) {
  var a = Symbol.for
  ;(m = a('react.element')), (f.Fragment = a('react.fragment'))
}
var x = w.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,
  E = Object.prototype.hasOwnProperty,
  P = { key: !0, ref: !0, __self: !0, __source: !0 }
function y(s, t, n) {
  var o,
    e = {},
    r = null,
    i = null
  n !== void 0 && (r = '' + n),
    t.key !== void 0 && (r = '' + t.key),
    t.ref !== void 0 && (i = t.ref)
  for (o in t) E.call(t, o) && !P.hasOwnProperty(o) && (e[o] = t[o])
  if (s && s.defaultProps)
    for (o in ((t = s.defaultProps), t)) e[o] === void 0 && (e[o] = t[o])
  return { $$typeof: m, type: s, key: r, ref: i, props: e, _owner: x.current }
}
f.jsx = y
f.jsxs = y
d.exports = f
const S = ({ label: s }) => d.exports.jsx('button', { children: s }),
  l = b.exports.jsx
function R() {
  return l('div', { children: l(S, { label: 'Click here' }) })
}
O.render(
  l(p.StrictMode, { children: l(R, {}) }),
  document.getElementById('root')
)

@sapphi-red sapphi-red added the cannot reproduce The bug cannot be reproduced label Jun 10, 2022
@sapphi-red
Copy link
Member

Closing due to lack of response.

@sapphi-red sapphi-red closed this as not planned Won't fix, can't repro, duplicate, stale Jul 1, 2022
@github-actions github-actions bot locked and limited conversation to collaborators Jul 16, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
cannot reproduce The bug cannot be reproduced pending triage
Projects
None yet
Development

No branches or pull requests

4 participants