Tutorial on setting up a React environment
This time I will bring you a tutorial on building a React environment. What are the precautions for building a React environment? Here are practical cases, let’s take a look.
The front-end ecology has experienced great development in recent years. In this ecosystem, not accepting new things and learning new skills is tantamount to falling into the devil's path.
This article attempts to introduce React, the front-end development tool, and the technology stack involved in building the project, in order to start thinking about the entire construction process.
It is necessary to point out that in order to understand the principle of something, you must first know what its purpose is.
1、Nodejs & NPM
Why mention nodejs?
Rather than saying that nodejs provides another possibility for server-side development, it is better to say that it has completely changed the entire front-end development ecosystem. The nodejs platform has derived powerful npm, grunt, express, etc., which have almost redefined the front-end workflow and development methods.
It is necessary to talk about the NPM (node package manager) package manager here.
npm is a javascript package manager. We can find, share and use code packages contributed by countless developers on npm without having to reinvent the wheel ourselves.
To use npm, node needs to be installed. The new version of nodejs has been integrated with npm. After installing nodejs, check the installed version through the following command:
$ npm -v
In the project directory, when executing
$ npm install
on the command line It will identify a file called package.json and try to install the dependent packages configured in the file.
2、React
React's organizational thinking makes code highly reusable, easy to test, and easier to separate concerns.
React also claims Learn Once, Write Anywhere. It can run in the client browser and render on the server. At the same time, React Native also makes it possible to develop native apps with React.
Step one: Create a new package.json file and specify the dependency packages required by the project.
{ "name": "react-tutorials", "version": "1.0.0", "description": "", "author": "yunmo", "scripts": { "start": "webpack-dev-server --hot --progress --colors --host 0.0.0.0", "build": "webpack --progress --colors --minimize" }, "dependencies": { "react": "^15.4.0", "react-dom": "^15.4.0" }, "devDependencies": { "webpack": "^2.2.1", "webpack-dev-server": "^2.4.2" }, "license": "" }
This is a necessary file for the npm package manager, which defines the name, version, startup command, production environment dependencies (dependencies) and development environment dependencies (devDependencies) of the project.
Step 2: Create a new index.html file.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>yunmo</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"/> </head> <body> <p id="yunmo"></p> <script src="bundle.js"></script> </body> </html>
Step 3: Write a simple React code.
var React = require('react'); var ReactDOM = require('react-dom'); var element = React.createElement( 'h1', {className: 'yunmo'}, '云陌,欢迎来到react的世界!' ); ReactDOM.render ( element, document.getElementById('yunmo') );
Step 4:Run.
So how to run it in the browser? Here we need to use the powerful webpack-dev-server to start the local server.
We can see that the package.json above contains webpack and webpack-dev-server dependency packages. Webpack will be introduced below.
Of course, we can also build a local server through nodejs, but here webpack-dev-server is actually a small nodejs Express server that uses webpack-dev-middleware middleware to serve webpack packages.
The webpack.config.js file is configured as follows:
var webpack = require('webpack'); module.exports = { entry: ['./app/main.js'], output: { path: dirname + '/build', filename: 'bundle.js' }, module: { loaders: [] } }
In this way, after we install the dependency package through npm install on the command line, type the command
$ npm start
After running the service, enter http://localhost:8080/
in the browser A simple React project is running.
3、Webpack
Webpack is a module loading and packaging tool for modern JavaScript applications. It can not only package JavaScript, but also package styles, images and other resources.
Let’s look at a typical webpack configuration:
var webpack = require('webpack'); var path = require('path') module.exports = { entry: ['./app/main.js'], output: { path: path.resolve(dirname, '/build'), filename: 'bundle.js' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"] }, { test: /\.(otf|eot|svg|ttf|woff|png|jpg)/, loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]' } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin() ] }
From the above webpack configuration, we can see that there are some basic configuration points, which also reflect the four concepts of webpack:
entry - webpack will create a relationship table based on the application's dependencies. The starting point of the table is the so-called entry point. The entry point will tell webpack where to start, and webpack will use the dependencies of the table as the basis for packaging.
- output - used to configure the packaged file placement path.
- #loader - webpack treats each file as a component (such as .css, .html, .scss, .jpg, .png, etc.), but webpack can only recognize JavaScript. At this time, loaders can convert these files into components and then be added to the dependency table.
- plugins——因为loaders作用方式是以单一文件为基础的,所以plugins更广泛的用来对打包组建形成的集合(compilations)进行自定义操作。
这样,一个完整的模块打包体系就建立起来了。
4、ES6
ES6,即ECMAScript 6.0,是 JavaScript的下一代标准。ES6里面新增了很多语法特性,使得编写复杂的应用更加优雅自然。
ES6中引入了诸如let和const、箭头函数、解构赋值、字符串模版、Module、Class、Promise等特性,使得前后端编程语言在语法形式上的差异越来越小。
我们来看一下:
import React from 'react' //模块引入 import '../styles/reactStack.scss' class ReactStack extends React.Component { //class特性 render() { const learner = {name: '云陌', age: 18} //const定义变量 const mainSkills = ['React', 'ES6', 'Webpack', 'Babel', 'NPM',] const extraSkills = ['Git', 'Postman'] const skillSet = [...mainSkills, ...extraSkills] const { name } = learner //解构赋值 let greetings = null //let定义变量 if (name) { greetings = `${name},欢迎来到${mainSkills[0]}的世界!` //字符模版 } //以下用了箭头函数 return ( <p className="skills"> <p>{greetings}</p> <ol> {skillSet.map((stack, i) => <li key={i}>{stack}</li>)} </ol> </p> ) } } export default ReactStack //模块导出
当然,并非所有浏览器都能兼容ES6全部特性,但看到这么优雅的书写方式,只能看怎么行呢?因此,这里又引出了一个神器,Babel!
5、Babel
Babel是一款JavaScript编译器。
Babel可以将ES6语法的代码转码成ES5代码,从而在浏览器环境中实现兼容。
Babel内置了对JSX的支持,所以我们才能向上面那样直接return一个JSX形式的代码片段。
具体用法不在本文过多讲述。
6、Styles引入
在上面的代码中,有以下样式引入方式:
import '../styles/reactStack.scss'
样式文件如下:
body { background: #f1f1f1; } .skills { h3 { color: darkblue; } ol { margin-left: -20px; li { font-size: 20px; color: rgba(0, 0, 0, .7); &:first-child { color: #4b8bf5; } } } }
样式文件要在项目中起作用,还需要在package.json里面添加相应的loader依赖,如css-loader, sass-loader, style-loader等,别忘了package.json里还需要node-sass依赖,然后安装即可。
webpack.config.js中相应配置如下:
module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }, { test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"] } ] }
再将main.js中的内容作如下更改:
import React from 'react' import ReactDOM from 'react-dom' import ReactStack from './pages/ReactStack' ReactDOM.render ( <ReactStack />, document.getElementById('yunmo') );
结语
至此,一个简单的React项目便搭建起来了。
在后续的文章中,我将对本文涉及到的React技术栈做专门的讲解,不仅限于硬性技能。当然更多的是实践做法上的总结,因为如果要掌握它们的理论,细看官方文档和源码是最好不过的做法。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Tutorial on setting up a React environment. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

Testing a monitor when buying it is an essential part to avoid buying a damaged one. Today I will teach you how to use software to test the monitor. Method step 1. First, search and download the DisplayX software on this website, install it and open it, and you will see many detection methods provided to users. 2. The user clicks on the regular complete test. The first step is to test the brightness of the display. The user adjusts the display so that the boxes can be seen clearly. 3. Then click the mouse to enter the next link. If the monitor can distinguish each black and white area, it means the monitor is still good. 4. Click the left mouse button again, and you will see the grayscale test of the monitor. The smoother the color transition, the better the monitor. 5. In addition, in the displayx software we

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

With the continuous development of smart phones, the functions of mobile phones have become more and more powerful, among which the function of taking long pictures has become one of the important functions used by many users in daily life. Long screenshots can help users save a long web page, conversation record or picture at one time for easy viewing and sharing. Among many mobile phone brands, Huawei mobile phones are also one of the brands highly respected by users, and their function of cropping long pictures is also highly praised. This article will introduce you to the correct method of taking long pictures on Huawei mobile phones, as well as some expert tips to help you make better use of Huawei mobile phones.

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.
