Home  >  Article  >  Web Front-end  >  Tutorial on setting up a React environment

Tutorial on setting up a React environment

php中世界最好的语言
php中世界最好的语言Original
2018-04-16 09:46:261108browse

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:

  1. 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.

  2. output - used to configure the packaged file placement path.

  3. #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.

  4. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn