You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何yarn.lock有依赖而package.json无?create-react-app eject场景问询

Great questions—let's break these down one by one to make things clear:

1. Why Moment.js is in 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.

2. Ensuring your Lodash imports are properly optimized

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' or import { 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 use babel-plugin-lodash to 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 for config/webpack.config.js or babel.config.js in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:29:07