Is client need to download react library, or how do they access module like react or react-dom?

670 views Asked by At

A quick question: When I am developing, I always have my library in my project folder called 'node_modules', and I use import React from 'react' from time to time, but my client don't have this library in their machine.

So, how did the client reach these code in library, I don't think they will download the entire library for visiting a website.

1

There are 1 answers

3
CertainPerformance On BEST ANSWER

For anything other than toy snippets, the usual approach is for the developer to to run something like npm run build, which will run the build process - either Create React App's, or from a module bundler like Webpack, or some other setup. This will then create a JavaScript "bundle", a single file which will contain all the necessary code - it'll have the code from React, React DOM, and all your used files, put together in a single file.

When you run your React app on your machine, or when you host the app somewhere else, you or the other client will download just that bundled file, and the app will be able to run with just that (and an HTML file, of course). Nothing else has to be downloaded.

It's possible to instead force the client to download React and React DOM, and to have the client compile and run the code - that's how Stack Snippets work here on Stack Overflow:

const App = () => {
    return <div>foo</div>;
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

It's nice for quick demos and toy snippets. But that's not a good approach for a real app, because it makes the client do a good deal of work (both in terms of bandwidth and CPU) unnecessarily - so usually you'd want to create a bundle via an NPM script instead.

This is how many frameworks work nowadays, not just React's - you have a build process that takes the framework code and the developer's code, and turns it all into a bundle, and then that bundle contains all the code needed to run the app.