According to Webpack
doc, Webpack generates a dependency graph starting from entry point which is usually index.js
.
And also if you use something like create-react-app
that uses webpack under the hood, it will generate a package json like this:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"build": "react-scripts build",
},
You can see there is no devDependencies
! that means not all thing that you just put on the dependencies
will be included in your final build.
Finally I've tested inside a new CRA
my app:
- pressed
npm run build
on the bare installed:
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
- Installed axios via
npm i axios
, but never imported it.
output after running npm run build
:
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Nothin has been changed!
- import axios from "axios", inside but never use it in the code:
import axios from "axios";
export default function App() {
return (
<div className="App">
</div>
);
}
This is the output:
[eslint]
src\App.js
Line 3:8: 'axios' is defined but never used no-unused-vars
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Again nothing changed! but you can see eslint
warning too!
- Use one of it's functions e.g. get method only:
import axios from "axios";
export default function App() {
console.log(axios.get);
return (
<div className="App">
</div>
);
}
the output:
File sizes after gzip:
57.92 kB (+11.31 kB) build\static\js\main.4c83ea39.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Conclusion:
If we don't use a package inside our app, it won't get into the final build.
Note:
Although extra packages won't affect production, don't forget to uninstall unused packages from time to time.
Running npm install still install every package defined in the package.json, no matter whether they are used or not. So having loads of unused packages will slow down deployment and affect your teammates (they need to run npm install as well!!.
Reference