为何yarn.lock有依赖而package.json无?create-react-app eject场景问询
Great questions—let's break these down one by one to make things clear:
yarn.lock but not your package.json, and why your app still runs First, a quick refresher on what yarn.lock does: it’s a file that records every single dependency (and its exact version) that gets installed in your node_modules folder—including indirect dependencies. These are dependencies that aren’t listed in your own package.json, but are required by one of the packages you did explicitly install (like a UI library, form handling tool, or date utility).
For example, if you’re using a component library that relies on Moment.js for date formatting, when you install that library via Yarn, it will automatically pull in Moment.js as a transitive dependency. Yarn adds this to yarn.lock to ensure everyone working on the project gets the exact same version, but it won’t add Moment.js to your package.json because you never explicitly asked for it.
As for why your app runs: Webpack doesn’t care if a package is a direct or indirect dependency—it looks for modules in the node_modules folder regardless. If any code in your project (yours or from a dependency) imports Moment.js, Webpack will resolve it from node_modules and bundle it into your app, so everything works as expected.
It’s smart to focus on importing only specific Lodash utilities—let’s make sure you’re doing it in a way that actually keeps your bundle size small:
- Direct file imports (most straightforward): Use syntax like
import debounce from 'lodash/debounce'orimport { debounce } from 'lodash-es/debounce'. This pulls only the code for that exact utility, no extra parts of Lodash get bundled. - Babel plugin for cleaner syntax: If you prefer writing
import { debounce } from 'lodash'(instead of the longer path imports), you can usebabel-plugin-lodashto automatically tree-shake unused Lodash code. Since you’ve ejected from create-react-app, you’ll need to add this plugin to your Babel configuration (look forconfig/webpack.config.jsorbabel.config.jsin your project root).
If you’re still seeing the full Lodash library in your source-map-explorer output, double-check your import statements: accidentally writing import _ from 'lodash' will pull in the entire library, even if you only use one function. Also, stick to ES module syntax (import instead of require())—Webpack’s tree-shaking works best with ES modules to eliminate unused code.
内容的提问来源于stack exchange,提问作者praks5432

