How to Code in ReactJS - PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides a tutorial on how to set up and use Create React App, explaining various npm commands including "npm start", "npm run build", and "npm test." It details the directory structure, configuration files, and scripting. The tutorial covers initial project setup, as well as how to build, test, and customize React projects.
Full Transcript
Output... Success! Created digital-ocean-tutorial at your_file_path/digital-ocean-tut orial Inside that directory, you can run several commands: npm start Starts the development server. npm run build Bundles the app into static files for production....
Output... Success! Created digital-ocean-tutorial at your_file_path/digital-ocean-tut orial Inside that directory, you can run several commands: npm start Starts the development server. npm run build Bundles the app into static files for production. npm test Starts the test runner. npm run eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd digital-ocean-tutorial npm start Happy hacking! your_file_path will be your current path. If you are a macOS user, it will be something like /Users/your_username ; if you are on an Ubuntu server, it will say something like /ho me/your_username. You will also see a list of npm commands that will allow you to run, build, start, and test your application. You’ll explore these more in the next section. Note: There is another package manager for JavaScript called yarn. It’s supported by Facebook and does many of the same things as npm. Originally, yarn provided new functionality such as lock files, but now these are implemented in npm as well. yarn also includes a few other features such as offline caching. Further differences can be found on the yarn documentation. If you have previously installed yarn on your system, you will see a list of yarn commands such as yarn start that work the same as npm commands. You can run n pm commands even if you have yarn installed. If you prefer yarn , just replace npm with yarn in any future commands. The results will be the same. Now your project is set up in a new directory. Change into the new directory: cd digital-ocean-tutorial You are now inside the root of your project. At this point, you’ve created a new project and added all of the dependencies. But you haven’t take any actions to run the project. In the next section, you’ll run custom scripts to build and test the project. Step 2 — Using react-scripts In this step, you will learn about the different react-scripts that are installed with the repo. You will first run the test script to execute the test code. Then you will run the bui ld script to create a minified version. Finally, you’ll look at how the eject script can give you complete control over customization. Now that you are inside the project directory, take a look around. You can either open the whole directory in your text editor, or if you are on the terminal you can list the files out with the following command: ls -a The -a flag ensures that the output also includes hidden files. Either way, you will see a structure like this: Output node_modules/ public/ src/.gitignore README.md package-lock.json package.json Let’s explain these one by one: node_modules/ contains all of the external JavaScript libraries used by the application. You will rarely need to open it. The public/ directory contains some base HTML, JSON, and image files. These are the roots of your project. You’ll have an opportunity to explore them more in Step 4. The src/ directory contains the React JavaScript code for your project. Most of the work you do will be in that directory. You’ll explore this directory in detail in Step 5. The.gitignore file contains some default directories and files that git—your source control—will ignore, such as the node_modules directory. The ignored items tend to be larger directories or log files that you would not need in source control. It also will include some directories that you’ll create with some of the React scripts. README.md is a markdown file that contains a lot of useful information about Create React App, such as a summary of commands and links to advanced configuration. For now, it’s best to leave the README.md file as you see it. As your project progresses, you will replace the default information with more detailed information about your project. The last two files are used by your package manager. When you ran the initial npx command, you created the base project, but you also installed the additional dependencies. When you installed the dependencies, you created a package-lock.json file. This file is used by npm to ensure that the packages match exact versions. This way if someone else installs your project, you can ensure they have identical dependencies. Since this file is created automatically, you will rarely edit this file directly. The last file is a package.json. This contains metadata about your project, such as the title, version number, and dependencies. It also contains scripts that you can use to run your project. Open the package.json file in your favorite text editor: nano package.json When you open the file, you will see a JSON object containing all the metadata. If you look at the scripts object, you’ll find four different scripts: start , build , test , and ej ect. These scripts are listed in order of importance. The first script starts the local development environment; you’ll get to that in the next step. The second script will build your project. You’ll explore this in detail in Step 4, but it’s worth running now to see what happens. The build Script To run any npm script, you just need to type npm run script_name in your terminal. There are a few special scripts where you can omit the run part of the command, but it’s always fine to run the full command. To run the build script, type the following in your terminal: npm run build You will immediately see the following message: Output > [email protected] build your_file_path/digital-ocean-tutorial > react-scripts build Creating an optimized production build...... This tells you that Create React App is compiling your code into a usable bundle. When it’s finished, you’ll see the following output: Output... Compiled successfully. File sizes after gzip: 39.85 KB build/static/js/9999.chunk.js 780 B build/static/js/runtime-main.99999.js 616 B build/static/js/main.9999.chunk.js 556 B build/static/css/main.9999.chunk.css The project was built assuming it is hosted at the server root. You can control this with the homepage field in your package.json. For example, add this to build it for GitHub Pages: "homepage" : "http://myname.github.io/myapp", The build folder is ready to be deployed. You may serve it with a static server: serve -s build Find out more about deployment here: bit.ly/CRA-deploy List out the project contents and you will see some new directories: ls -a Output build/ node_modules/ public/ src/.gitignore README.md package-lock.json package.json You now have a build directory. If you opened the.gitignore file, you may have noticed that the build directory is ignored by git. That’s because the build directory is just a minified and optimized version of the other files. There’s no need to use version control since you can always run the build command. You’ll explore the output more later; for now, it’s time to move on to the test script. The test Script The test script is one of those special scripts that doesn’t require the run keyword, but works even if you include it. This script will start up a test runner called Jest. The test runner looks through your project for any files with a.spec.js or.test.js extension, then runs those files. To run the test script, type the following command: npm test After running this script your terminal will have the output of the test suite and the terminal prompt will disappear. It will look something like this: Output PASS src/App.test.js ✓ renders learn react link (67ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 4.204s Ran all test suites. Watch Usage › Press f to run only failed tests. › Press o to only run tests related to changed files. › Press q to quit watch mode. › Press p to filter by a filename regex pattern. › Press t to filter by a test name regex pattern. › Press Enter to trigger a test run. There are a few things to notice here. First, as noted before, it automatically detects any files with test extensions including.test.js and.spec.js. In this case, there is only one test suite—that is, only one file with a.test.js extension—and that test suite contains only one test. Jest can detect tests in your code hierarchy, so you can nest tests in a directory and Jest will find them. Second, Jest doesn’t run your test suite once and then exit. Rather, it continues running in the terminal. If you make any changes in the source code, it will rerun the tests again. You can also limit which tests you run by using one of the keyboard options. If you type o, for example, you will only run the tests on files that have changed. This can save you lots of time as your test suites grow. Finally, you can exit the test runner by typing q. Do this now to regain your command prompt. The eject Script The final script is npm eject. This script copies your dependencies and configuration files into your project, giving you full control over your code but ejecting the project from the Create React App integrated toolchain. You will not run this now because, once you run this script, you can’t undo this action and you will lose any future Create React App updates. The value in Create React App is that you don’t have to worry about a significant amount of configuration. Building modern JavaScript applications requires a lot of tooling from build systems, such as Webpack, to compilation tools, such as Babel. Create React App handles all the configuration for you, so ejecting means dealing with this complexity yourself. The downside of Create React App is that you won’t be able to fully customize the project. For most projects that’s not a problem, but if you ever want to take control of all aspects of the build process, you’ll need to eject the code. However, as mentioned before, once you eject the code you will not be able to update to new versions of Create React App, and you’ll have to manually add any enhancements on your own. At this point, you’ve executed scripts to build and test your code. In the next step, you’ll start the project on a live server. Step 3 — Starting the Server In this step, you will initialize a local server and run the project in your browser. You start your project with another npm script. Like npm test , this script does not need the run command. When you run the script you will start a local server, execute the project code, start a watcher that listens for code changes, and open the project in a web browser. Start the project by typing the following command in the root of your project. For this tutorial, the root of your project is the digital-ocean-tutorial directory. Be sure to open this in a separate terminal or tab, because this script will continue running as long as you allow it: npm start You’ll see some placeholder text for a brief moment before the server starts up, giving this output: Output Compiled successfully! You can now view digital-ocean-tutorial in the browser. http://localhost:3000 Note that the development build is not optimized. To create a production build, use npm run build. If you are running the script locally, it will open the project in your browser window and shift the focus from the terminal to the browser. If that doesn’t happen, you can visit http://localhost:3000/ to see the site in action. If you already happen to have another server running on port 3000 , that’s fine. Create React App will detect the next available port and run the server with that. In other words, if you already have one project running on port 3000 , this new project will start on port 3001. If you are running this from a remote server you can still see your site without any additional configuration. The address will be http://your_server_ip:3000. If you have a firewall configured, you’ll need to open up the port on your remote server. In the browser, you will see the following React template project: React template project As long as the script is running, you will have an active local server. To stop the script, either close the terminal window or tab or type CTRL+C or ⌘-+c in the terminal window or tab that is running your script. At this point, you have started the server and are running your first React code. But before you make any changes to the React JavaScript code, you will see how React renders to the page in the first place. Step 4 — Modifying the Homepage In this step, you will modify code in the public/ directory. The public directory contains your base HTML page. This is the page that will serve as the root to your project. You will rarely edit this directory in the future, but it is the base from which the project starts and a crucial part of a React project. If you cancelled your server, go ahead and restart it with npm start , then open public/ in your favorite text editor in a new terminal window: nano public/ Alternatively, you can list the files with the ls command: ls public/ You will see a list of files such as this: Output favicon.ico logo192.png manifest.json index.html logo512.png robots.txt favicon.ico , logo192.png , and logo512.png are icons that a user would see either in the tab of their browser or on their phone. The browser will select the proper-sized icons. Eventually, you’ll want to replace these with icons that are more suited to your project. For now, you can leave them alone. The manifest.json is a structured set of metadata that describes your project. Among other things, it lists which icon will be used for different size options. The robots.txt file is information for web crawlers. It tells crawlers which pages they are or are not allowed to index. You will not need to change either file unless there is a compelling reason to do so. For instance, if you wanted to give some users a URL to special content that you do not want easily accessible, you can add it to robots.txt and it will still be publicly available, but not indexed by search engines. The index.html file is the root of your application. This is the file the server reads, and it is the file that your browser will display. Open it up in your text editor and take a look. If you are working from the command line, you can open it with the following command: nano public/index.html Here’s what you will see: digital-ocean-tutorial/public/index.html React App