question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Production build tree shaking not working

See original GitHub issue

Tree shaking does not work. I created a React app with both Nx and create-react-app, and imported a single lodash function.

Current Behavior

Nx bundle: Screen Shot 2022-04-06 at 2 00 07 PM

Expected Behavior

Create react app bundle: Screen Shot 2022-04-06 at 2 00 52 PM

Steps to Reproduce

// eslint-disable-next-line @typescript-eslint/no-unused-vars
import styles from './app.module.scss';
import NxWelcome from './nx-welcome';
import { get } from 'lodash-es';

export function App() {
  console.log(get({ foo: true }, 'foo'));
  return (
    <>
      <NxWelcome title="lodash" />
      <div />
    </>
  );
}

export default App;

Environment

 >  NX   Report complete - copy this into the issue template

   Node : 16.13.2
   OS   : darwin x64
   npm  : 8.1.2
   
   nx : 13.9.7
   @nrwl/angular : Not Found
   @nrwl/cypress : 13.9.7
   @nrwl/detox : Not Found
   @nrwl/devkit : 13.9.7
   @nrwl/eslint-plugin-nx : 13.9.7
   @nrwl/express : 13.9.7
   @nrwl/jest : 13.9.7
   @nrwl/js : 13.9.7
   @nrwl/linter : 13.9.7
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : 13.9.7
   @nrwl/nx-cloud : Not Found
   @nrwl/nx-plugin : Not Found
   @nrwl/react : 13.9.7
   @nrwl/react-native : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : 13.9.7
   @nrwl/web : 13.9.7
   @nrwl/workspace : 13.9.7
   typescript : 4.4.4
   rxjs : 7.5.4
   ---------------------------------------
   Community plugins:
         @nx-tools/nx-docker: 2.3.0

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:11

github_iconTop GitHub Comments

8reactions
vlad-khitev-axoncommented, Apr 15, 2022

A full solution that worked for me. Nx version: 13.10.2

apps/<app>/project.json

{
  "targets": {
    "build": {
      "options": {
        "webpackConfig": "apps/<app>/custom-webpack.config.js"
      }
    }
  }
}

apps/<app>/custom-webpack.config.js

const { merge } = require('webpack-merge')
const getWebpackConfig = require('@nrwl/react/plugins/webpack')

module.exports = (config, _context) => {
  return merge(getWebpackConfig(config), {
    optimization: {
      sideEffects: true,
    },
  })
}

package.json

{
  "sideEffects": false
}

If your app has side effects, for example, global styles, you need to specify an array of effectful files in the package.json:

{
  "sideEffects": ["apps/<app>/src/styles/index.css"]
}

I didn’t have problems with Jest or "target": "es2015" in the tsconfig.base.json file as described in the comment above.

2reactions
joshribakoff-smcommented, Apr 7, 2022

https://webpack.js.org/configuration/optimization/#optimizationsideeffects

By logging out the webpack configs that nx is using, I see it has optimization: { sideEffects: false }. Is there a reason this is turned off?

Additionally, Nx has my tsconfig.json set to "target": "es2015",.

I fully expect both of these issues to prevent tree shaking.

After I fixed both of these issues, I can confirm Nx properly tree shakes 👍 . All I did was:

    optimization: {
      sideEffects: true,
    },

(see https://nx.dev/guides/customize-webpack)

and in tsconfig.base.json I set "target": "esnext", 😃


In turn these changes break Jest, to fix this I added

jest.preset.js:

transformIgnorePatterns: ['<rootDir>/node_modules/(?!lodash-es)'],

babel.config.json:

{
  "presets": [
    [
      "@nrwl/react/babel",
      {
        "runtime": "automatic"
      }
    ]
  ],
  "plugins": []
}

And now jest works again


After making these changes and switching branches nx build also broke with this:

 npx nx build app                    
/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/utilities/project-graph-utils.js:9
    return project.data && project.data.targets && project.data.targets[target];
                   ^

TypeError: Cannot read properties of undefined (reading 'data')
    at projectHasTarget (/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/utilities/project-graph-utils.js:9:20)
    at addTasksForProjectDependencyConfig (/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/tasks-runner/run-command.js:220:64)
    at addTasksForProjectTarget (/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/tasks-runner/run-command.js:157:13)
    at createTasksForProjectToRun (/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/tasks-runner/run-command.js:133:9)
    at /Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/tasks-runner/run-command.js:58:23
    at Generator.next (<anonymous>)
    at /Users/jribakoff/groundwater/node_modules/tslib/tslib.js:117:75
    at new Promise (<anonymous>)
    at __awaiter (/Users/jribakoff/groundwater/node_modules/tslib/tslib.js:113:16)
    at runCommand (/Users/jribakoff/groundwater/node_modules/@nrwl/workspace/src/tasks-runner/run-command.js:53:34)

After rm -fr node_modules/.cache this error was also resolved, and is tracked in a separate bug I reported here https://github.com/nrwl/nx/issues/9662

Read more comments on GitHub >

github_iconTop Results From Across the Web

Webpack Tree Shaking not working when importing from a file ...
If I remove the moment import from module.js tree shaking works fine and i only see square in my bundle. Is this how...
Read more >
Tree Shaking - webpack
Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of ES2015 module...
Read more >
Tree shaking and code splitting in webpack - LogRocket Blog
What is tree shaking? Tree shaking, also known as dead code elimination, is the practice of removing unused code in your production build....
Read more >
How I fixed webpack tree shaking in 3 easy steps
Make sure webpack is set to mode: production . This turns on a bunch of internal flags to make it all work. Step...
Read more >
Tree-Shaking Problems with Component Libraries - Medium
Tree -shaking isn't magic, and much like the garbage collector, ... and you're producing an ES Module build (which you should!), don't bundle ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found