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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











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.

The expansion of the virtual market is inseparable from the circulation of virtual currency, and naturally it is also inseparable from the issue of virtual currency transfers. A common transfer error is the address copy error, and another error is the chain selection error. The transfer of virtual currency to the wrong chain is still a thorny problem, but due to the inexperience of transfer operations, novices often transfer the wrong chain. So how to recover the wrong chain of virtual currency? The wrong link can be retrieved through a third-party platform, but it may not be successful. Next, the editor will tell you in detail to help you better take care of your virtual assets. How to retrieve the wrong chain of virtual currency? The process of retrieving virtual currency transferred to the wrong chain may be complicated and challenging, but by confirming the transfer details, contacting the exchange or wallet provider, importing the private key to a compatible wallet, and using the cross-chain bridge tool

In daily shooting, many people encounter this situation: the photos on the camera seem to be exposed normally, but after exporting the photos, they find that their true form is far from the camera's rendering, and there is obviously an exposure problem. Affected by environmental light, screen brightness and other factors, this situation is relatively normal, but it also brings us a revelation: when looking at photos and analyzing photos, you must learn to read histograms. So, what is a histogram? Simply understood, a histogram is a display form of the brightness distribution of photo pixels: horizontally, the histogram can be roughly divided into three parts, the left side is the shadow area, the middle is the midtone area, and the right side is the highlight area; On the left is the dead black area in the shadows, while on the far right is the spilled area in the highlights. The vertical axis represents the specific distribution of pixels

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

Having the right documentation and tutorials at your fingertips is crucial to using Java frameworks effectively. Recommended resources include: SpringFramework: Official Documentation and Tutorials SpringBoot: Official Guide Hibernate: Official Documentation, Tutorials and Practical Cases ServletAPI: Official Documentation, Tutorials and Practical Cases JUnit: Official Documentation and Tutorials Mockito: Official Documentation and Tutorials

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.
