react组件样板_如何构建自己的React样板

news/2024/7/3 0:46:28

react组件样板

by Nick Karnik

尼克·卡尼克(Nick Karnik)

如何构建自己的React样板 (How to build your own React boilerplate)

什么是样板? (What is a Boilerplate?)

In programming, the term boilerplate code refers to blocks of code used over and over again.

在编程中,样板代码一词是指一遍又一遍地使用的代码块。

Let’s assume your development stack consists of several libraries, such as React, Babel, Express, Jest, Webpack, etc. When you start a new project, you initialize all these libraries and configure them to work with each other.

假设您的开发堆栈由多个库组成,例如React,Babel,Express,Jest,Webpack等。启动新项目时,请初始化所有这些库并将其配置为可以相互协作。

With every new project that you start, you will be repeating yourself. You could also introduce inconsistencies in how these libraries are set up in each project. This can cause confusion when you switch between projects.

随着您开始的每个新项目,您都将重复自己。 您还可以在每个项目中如何设置这些库中引入不一致之处。 在项目之间切换时,这可能会引起混乱。

This is where boilerplates come in. A boilerplate is a template that you can clone and reuse for every project.

这就是样板的来源。样板是一个模板,您可以为每个项目克隆和重复使用该模板。

The modular Javascript ecosystem simplifies application development through various libraries, frameworks and tools. Boilerplates can be daunting if you don’t understand the fundamentals of their underlying components. Let’s learn about these basic building blocks while creating our own.

模块化的Javascript生态系统通过各种库,框架和工具简化了应用程序开发。 如果您不了解底层组件的基础知识,那么它们可能会令人生畏。 在创建自己的模块时,让我们了解这些基本的构建模块。

Click here for source on GitHub

单击此处获取GitHub上的源

I am using Webstorm, Git, NodeJS 8.9, NPM 5.6, and React 16. Fire up your favorite IDE, create a blank project, and let’s get started!
我正在使用Webstorm,Git,NodeJS 8.9,NPM 5.6和React16。启动您喜欢的IDE,创建一个空白项目,然后开始吧!

Git存储库:设置 (Git Repository: Setup)

Create a project folder and initialize a Git repo:

创建一个项目文件夹并初始化一个Git仓库:

mkdir react-boilerplate && cd react-boilerplategit init

You can connect this project to your own repo on GitHub using these instructions.

您可以按照以下说明将此项目连接到GitHub上自己的仓库。

自述文件 (Readme File)

Every project should contain a landing page with useful instructions for other developers. Let’s create a README.md file under the project root with the following content:

每个项目都应包含一个登录页面,其中包含对其他开发人员的有用说明。 让我们在项目根目录下创建一个README.md文件,其内容如下:

# React-BoilerplateThis is my react-boilerplate
## Setupnpm installnpm run buildnpm start

GitHub displays the contents of the readme file on the landing page for the project.

GitHub在项目的目标页面上显示自述文件的内容。

Now, commit the above changes to Git:

现在,将以上更改提交给Git:

git add .git commit -m "created readme"

At the end of each section, you should commit your code to Git.

在每个部分的结尾,您应该将代码提交给Git。

资料夹结构 (Folder Structure)

Create the following folder structure for your project:

为您的项目创建以下文件夹结构:

react-boilerplate    |--src       |--client       |--server

with the command:

使用命令:

mkdir -p src/client src/server

This folder structure is basic and will evolve as you integrate other libraries in the project.

此文件夹结构是基本的,并且在您将其他库集成到项目中时会不断发展。

忽略Git (Git Ignore)

Once we build our project, there will be a few auto-generated files and folders. Let’s tell Git to ignore some of those files that we can think of ahead of time.

一旦我们构建了项目,就会有一些自动生成的文件和文件夹。 让我们告诉Git忽略一些我们可以提前想到的文件。

Create .gitignore under the root folder with the following content:

在根文件夹下创建.gitignore,其内容如下:

# Nodenode_modules/
# Webstorm.idea/
# Projectdist/

Comments in a .gitignore file are prefixed with #.

.gitignore文件中的注释以#开头。

节点包管理器 (Node Package Manager)

The starting point for a node project is to initialize its package manager which creates a file called package.json. This file must be checked into Git.

节点项目的起点是初始化其包管理器,该包管理器创建一个名为package.json的文件。 该文件必须检入Git。

It generally contains:

它通常包含:

  • A description of your project for NPM

    您的NPM项目说明
  • List of references to all installed packages

    所有已安装软件包的参考列表
  • Custom command line scripts

    自定义命令行脚本
  • Configuration for installed packages

    配置已安装的软件包

Go to your project root and type the following:

转到您的项目根目录,然后键入以下内容:

npm init

Fill out all the details, and after you accept them, npm will create a package.json file that looks something like:

填写所有详细信息,并在接受之后,npm将创建一个package.json文件,看起来像:

{  "name": "react-boilerplate",  "version": "1.0.0",  "description": "Basic React Boilerplate",  "main": "index.js",  "scripts": {    "test": "echo \"Error: no test specified\" && exit 1"  },  "repository": {    "type": "git",    "url": "git+https://github.com/theoutlander/react-boilerplate.git"  },  "keywords": [    "Node",    "React"  ],  "author": "Nick Karnik",  "license": "Apache-2.0",  "bugs": {    "url": "https://github.com/theoutlander/react-boilerplate/issues"  },  "homepage": "https://github.com/theoutlander/react-boilerplate#readme"}

静态内容 (Static Content)

Let’s create a static HTML file src/client/index.html with the following content:

让我们创建一个包含以下内容的静态HTML文件src / client / index.html:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>React Boilerplate</title></head><body>    <div id="root">        Welcome to React Boilerplate!    </div></body></html>

Express Web服务器 (Express Web Server)

To serve the static file above, we need to create a web server in ExpressJS.

为了提供上面的静态文件,我们需要在ExpressJS中创建一个Web服务器。

NPM v5 automatically saves installed packages under the dependencies section in package.json so the --save attribute is not necessary

NPM v5自动将已安装的软件包保存在package.json的“ dependencies”部分下,因此--save 属性不是必需的

npm install express

I would recommend following a file naming convention where file names are lower case and multiple words are separated by a dot. You will avoid running into case sensitivity issues across platforms, and will also simplify naming files with multiple words across larger teams.

我建议遵循文件命名约定,其中文件名是小写字母,并且多个单词由点分隔。 您将避免在跨平台时遇到区分大小写的问题,并且还将简化大型团队中多个单词的命名文件。

Create a file src/server/web.server.js and add the following code to host a web server via an express app and serve the static HTML file:

创建文件src / server / web.server.js并添加以下代码,以通过Express应用程序托管Web服务器并提供静态HTML文件:

const express = require('express')
export default class WebServer {  constructor () {    this.app = express()    this.app.use(express.static('dist/public'))  }
start () {    return new Promise((resolve, reject) => {      try {        this.server = this.app.listen(3000, function () {          resolve()        })      } catch (e) {        console.error(e)        reject(e)      }    })  }
stop () {    return new Promise((resolve, reject) => {      try {        this.server.close(() => {          resolve()        })      } catch (e) {        console.error(e.message)        reject(e)      }    })  }}

We have created a simple web server above with a start and stop command.

我们在上面创建了一个简单的Web服务器,其中包含start和stop命令。

Click here to learn more about Promises.

单击此处以了解有关Promises的更多信息 。

启动文件 (Startup File)

Next, we need to create an index file which will initialize various high-level components. In our example, we’re going to initialize the web server. However, as your project grows, you can also initialize other components such as configuration, database, logger, etc.

接下来,我们需要创建一个索引文件,该文件将初始化各种高级组件。 在我们的示例中,我们将初始化Web服务器。 但是,随着项目的增长,您还可以初始化其他组件,例如配置,数据库,记录器等。

Create a file src/server/index.js with the following code:

使用以下代码创建文件src / server / index.js:

import WebServer from './web.server'
let webServer = new WebServer();webServer.start()  .then(() => {    console.log('Web server started!')  })  .catch(err => {    console.error(err)    console.error('Failed to start web server')  });

巴别塔 (Babel)

To run the above ES6 code, we need to transform it to ES5 first via Babel. Let’s install Babel and the babel-preset-env dependency which supports ES2015 transpilation:

要运行上述ES6代码,我们需要先通过Babel将其转换为ES5 。 让我们安装Babel和支持ES2015转译的babel-preset-env依赖项:

npm i babel-cli babel-preset-env --save-dev

Create a Babel configuration file called .babelrc under the root and add the following details to it:

在根目录下创建一个名为.babelrc的Babel配置文件,并向其中添加以下详细信息:

{  "presets": ["env"]}

The env preset implicitly includes babel-preset-es2015, babel-preset-es2016, and babel-preset-es2017 together, which means you can run ES6, ES7 and ES8 code.

env预设隐式包含babel-preset-es2015,babel-preset-es2016和babel-preset-es2017,这意味着您可以运行ES6,ES7和ES8代码。

生成命令 (Build Commands)

Let’s create commands to build the server and client components of the project and start the server. Under the scripts section of package.json, remove the line with the test command and add the following:

让我们创建命令来构建项目的服务器和客户端组件并启动服务器。 在package.json的scripts部分下,使用test命令删除该行并添加以下内容:

"scripts": {    "build": "npm run build-server && npm run build-client",    "build-server": "babel src/server --out-dir ./dist",    "build-client": "babel src/client --copy-files --out-dir ./dist/public",    "start": "node ./dist/index.js"}

The build command above will create a dist/public folder under the root. The build-client command is simply copying the index.html file to the dist/public folder.

上面的build命令将在根目录下创建一个dist / public文件夹。 build-client命令只是将index.html文件复制到dist / public文件夹。

启动 (Starting up)

You can run the Babel transpiler on the code above and start the web server by using the following commands:

您可以在上面的代码上运行Babel编译器,并使用以下命令启动Web服务器:

npm run buildnpm start

Open your browser and navigate to http://localhost:3000. You should see the output of your static HTML file.

打开浏览器并导航到http:// localhost:3000 。 您应该看到静态HTML文件的输出。

You can stop the web server by pressing <Ctrl> C

您可以通过按<Ctrl> C来停止Web服务器。

测试线束:笑话 (Test Harness: Jest)

I cannot stress enough the importance of introducing unit tests at the beginning of a project. We’re going to use the Jest Testing Framework which is designed to be fast and developer friendly.

我不能太强调在项目开始时引入单元测试的重要性。 我们将使用Jest测试框架 ,该框架旨在快速且对开发人员友好。

First, we need to install Jest and save it to development dependencies.

首先,我们需要安装Jest并将其保存到开发依赖项中。

npm i jest --save-dev

单元测试 (Unit Tests)

Let’s add two test cases to start and stop the web server.

让我们添加两个测试用例来启动和停止Web服务器。

For test files, you should add a .test.js extension. Jest will scan the src folder for all files containing .test in the filename, you can keep your test cases under the same folder as the files they’re testing.

对于测试文件,您应该添加.test.js扩展名。 Jest会在src文件夹中扫描文件名中包含.test的所有文件,您可以将测试用例与要测试的文件放在同一文件夹下。

Create a file called src/server/web.server.test.js and add the following code:

创建一个名为src / server / web.server.test.js的文件,并添加以下代码:

import WebServer from './web.server'
describe('Started', () => {  let webServer = null
beforeAll(() => {    webServer = new WebServer()  })
test('should start and trigger a callback', async () => {    let promise = webServer.start()    await expect(promise).resolves.toBeUndefined()  })
test('should stop and trigger a callback', async () => {    let promise = webServer.stop()    await expect(promise).resolves.toBeUndefined()  })})

测试指令 (Test Command)

Let’s add an npm command to run the test under the scripts section of package.json. By default, Jest runs all files with the word .test in their file name. We want to limit it to running tests under the src folder.

让我们添加一个npm命令在package.json的脚本部分下运行测试。 默认情况下,Jest运行所有文件名中带有单词.test的文件。 我们希望将其限制为在src文件夹下运行测试。

"scripts": {...    "test": "jest ./src"...}

Babel-jest is automatically installed when installing Jest and will automatically transform files if a Babel configuration exists in your project.

安装Jest时会自动安装Babel-jest,如果您的项目中存在Babel配置,它将自动转换文件。

Let’s run our tests via the following command:

让我们通过以下命令运行测试:

npm test

Our application is set up to serve a static HTML file via an Express web server. We have integrated Babel to enable ES6 and Jest for unit testing. Let’s shift our focus to the front-end setup.

我们的应用程序设置为通过Express Web服务器提供静态HTML文件。 我们已经集成了Babel,以使ES6和Jest能够进行单元测试。 让我们将重点转移到前端设置上。

React设置 (React Setup)

Install the react and react-dom libraries:

安装react和react-dom库:

npm i react react-dom

Create a file called src/client/app.js with:

使用以下命令创建一个名为src / client / app.js的文件:

import React, {Component} from 'react'
export default class App extends Component {    render() {        return <div>Welcome to React Boilerplate App</div>    }}

Let’s render the App via an index file under src/client/index.js with:

让我们通过src / client / index.js下的索引文件渲染应用程序,其中:

import React from 'react'import ReactDOM from 'react-dom'import App from './app'
ReactDOM.render(<App />, document.getElementById('root'))

巴别塔React (Babel React)

If you execute npm run build-client, you will get an error because we haven’t told Babel how to handle React / JSX.

如果您执行npm run build-client,则会收到错误消息,因为我们没有告诉Babel如何处理React / JSX。

Let’s fix that by installing the babel-preset-react dependency:

让我们通过安装babel-preset-react依赖项来解决此问题:

npm install --save-dev babel-preset-react

We also need to modify the .babelrc config file to enable transpiling react:

我们还需要修改.babelrc配置文件以启用转译React:

{  "presets": ["env", "react"]}

Now, when you run npm run build-client, it will create app.js and index.js under dist/public with ES6 code transpiled to ES5.

现在,当您运行npm run build-client时,它将在dist / public下创建app.js和index.js,并将ES6代码转换为ES5。

以HTML加载脚本 (Load Script in HTML)

To connect our React App to the HTML file, we need to load index.js in our index.html file. Don’t forget to empty the text of the #root node since the React App will be mounted to it:

要将React App连接到HTML文件,我们需要在index.html文件中加载index.js。 不要忘记清空#root节点的文本,因为React App将被安装到该节点:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>React Boilerplate</title></head><body>    <div id="root"></div>    <script src="index.js"></script></body></html>

运行服务器 (Run Server)

If you fire up your web server and go to http://localhost:3000, you will see a blank page with an error in the console.

如果启动Web服务器并转到http:// localhost:3000 ,则控制台中将显示一个空白页面并显示错误。

Uncaught ReferenceError: require is not defined.

未捕获的ReferenceError:未定义require。

This is because Babel is just a transpiler. In order to support dynamically loading modules, we will need to install Webpack.

这是因为Babel只是翻译员。 为了支持动态加载模块,我们将需要安装Webpack。

Start by changing the build commands under scripts in package.json to build-babel:

首先将package.json中脚本下的build命令更改为build-babel:

"scripts": {    "build-babel": "npm run build-babel-server && npm run build-babel-client",    "build-babel-server": "babel src/server --out-dir ./dist",    "build-babel-client": "babel src/client --copy-files --out-dir ./dist/public",    "start": "node ./dist/index.js",    "test": "jest ./src"  }

Webpack (Webpack)

Webpack allows us to easily modularize our code and bundle it into a single Javascript file. It is supported by numerous plugins, and chances are that there’s a plugin for almost any build task you can think of. Start by installing Webpack:

Webpack允许我们轻松地将代码模块化,并将其捆绑到一个Javascript文件中。 许多插件都支持它,而且几乎所有构建任务都可以使用一个插件。 首先安装Webpack:

This tutorial was published right before webpack v4 was released, so we will explicitly install webpack v3.
本教程是在webpack v4发布之前发布的,因此我们将明确安装webpack v3。
npm i webpack@^3

By default, Webpack looks for a configuration file called webpack.config.js, so let’s create it in the root folder and define two entry points, one for the web application and the other for the web server. Let’s create two config objects and export them as a collection:

默认情况下,Webpack会寻找一个名为webpack.config.js的配置文件,因此让我们在根文件夹中创建它,并定义两个入口点,一个用于Web应用程序,另一个用于Web服务器。 让我们创建两个配置对象并将其导出为集合:

const client = {    entry: {        'client': './src/client/index.js'    }};
const server = {    entry: {        'server': './src/server/index.js'    }};
module.exports = [client, server];

Now, let’s specify where Webpack will output the bundle and set the target build so that it ignores native node modules like ‘fs’ and ‘path’ from being bundled. For client, we will set it to web, and for server we will set it to node.

现在,让我们指定Webpack将在何处输出捆绑软件并设置目标构建,以使它忽略诸如“ fs”和“ path”之类的本机节点模块。 对于客户端,我们将其设置为web,对于服务器,我们将其设置为node。

let path = require('path');
const client = {    entry: {        'client': './src/client/index.js'    },    target: 'web',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist/public')    }};
const server = {    entry: {        'server': './src/server/index.js'    },    target: 'node',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist')    }};
module.exports = [client, server];

巴别塔装载机 (Babel Loader)

Before we can run Webpack, we need configure it to handle ES6 and JSX code. This is done via loaders. Let’s start by installing babel-loader:

在运行Webpack之前,我们需要对其进行配置以处理ES6和JSX代码。 这是通过装载机完成的。 让我们从安装babel-loader开始 :

npm install babel-loader --save-dev

We need to modify the Webpack configuration to include babel-loader to run on all .js files. We will create a shared object defining the module section that we can re-use for both targets.

我们需要修改Webpack配置,使其包含babel-loader以便在所有.js文件上运行。 我们将创建一个共享的对象,该对象定义了我们可以同时用于两个目标的模块部分。

const path = require('path');
const moduleObj = {    loaders: [        {            test: /\.js$/,            exclude: /node_modules/,            loaders: ["babel-loader"],        }    ],};
const client = {    entry: {        'client': './src/client/index.js',    },    target: 'web',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist/public')    },    module: moduleObj};
const server = {    entry: {        'server': './src/server/index.js'    },    target: 'node',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist')    },    module: moduleObj}
module.exports = [client, server];

For merging nested shared objects, I would recommend checking out the Webpack Merge module.

对于合并嵌套的共享对象,我建议您检出Webpack合并模块。

排除文件 (Excluding Files)

Webpack will bundle referenced libraries, which means everything that is included from node_modules will be packaged. We don’t need to bundle external code, as those packages are generally minified, and they will also increase the build time and size.

Webpack将捆绑引用的库,这意味着node_modules中包含的所有内容都将被打包。 我们不需要捆绑外部代码,因为这些软件包通常会被精简,并且它们还会增加构建时间和大小。

Let’s configure Webpack to exclude all packages under the node_modules folder. This is easily accomplished via the webpack-node-externals module:

让我们将Webpack配置为排除node_modules文件夹下的所有软件包。 这可以通过webpack-node-externals模块轻松实现:

npm i webpack-node-externals --save-dev

Followed by configuring webpack.config.js to use it:

接下来配置webpack.config.js以使用它:

let path = require('path');let nodeExternals = require('webpack-node-externals');
const moduleObj = {    loaders: [        {            test: /\.js$/,            exclude: /node_modules/,            loaders: ["babel-loader"],        }    ],};
const client = {    entry: {        'client': './src/client/index.js',    },    target: 'web',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist')    },    module: moduleObj};
const server = {    entry: {        'server': './src/server/index.js'    },    target: 'node',    output: {        filename: '[name].js',        path: path.resolve(__dirname, 'dist')    },    module: moduleObj,    externals: [nodeExternals()]}
module.exports = [client, server];

更新构建命令 (Update Build Command)

Finally, we need to make changes to the scripts section under package.json to include a build command that uses Webpack, and to rename index.js to server.js for npm start as that’s what Webpack is configured to output.

最后,我们需要对package.json下的scripts部分进行更改,以包括一个使用Webpack的构建命令,并将index.js重命名为server.js以进行npm start,因为这是Webpack配置为输出的内容。

"scripts": {    "build": "webpack",    "build-babel": "npm run build-babel-server && npm run build-babel-client",    "build-babel-server": "babel src/server --out-dir ./dist",    "build-babel-client": "babel src/client --copy-files --out-dir ./dist/public",    "start": "node ./dist/server.js",    "test": "jest ./src"  }

建立干净 (Build Clean)

Let’s add a command to clean our dist and node_modules folders so we can do a clean build and ensure our project still works as expected. Before we can do that, we need to install a package called rimraf (which is the rm -rfcommand).

让我们添加一个命令来清理dist和node_modules文件夹,以便我们可以进行清理构建并确保我们的项目仍能按预期工作。 在此之前,我们需要安装一个名为rimraf的软件包(这是rm -rfcommand)。

npm install rimraf

The scripts section should now contain:

脚本部分现在应包含:

"scripts": {..."clean": "rimraf dist node_modules",...}

使用Webpack清理构建 (Clean Build with Webpack)

You can now successfully clean and build your project using Webpack:

现在,您可以使用Webpack成功清理和构建项目:

npm run cleannpm installnpm run build

This will create dist/server.js and dist/public/client.js under the root folder.

这将在根文件夹下创建dist / server.js和dist / public / client.js。

HTML Webpack插件 (HTML Webpack Plugin)

However, you may have noticed that index.html is missing. This is because, previously, we asked Babel to copy files that weren’t transpiled. However, Webpack isn’t able to do that, so we need to use the HTML Webpack Plugin.

但是,您可能已经注意到缺少index.html。 这是因为,以前,我们要求Babel复制未转译的文件。 但是,Webpack无法做到这一点,因此我们需要使用HTML Webpack Plugin 。

Let’s install the HTML Webpack Plugin:

让我们安装HTML Webpack插件:

npm i html-webpack-plugin --save-dev

We need to include the plugin at the top of the webpack config file:

我们需要在webpack配置文件的顶部包含插件:

const HtmlWebPackPlugin = require('html-webpack-plugin')

Next, we need to add a plugins key to the client config:

接下来,我们需要向客户端配置添加一个插件密钥:

const client = {  entry: {    'client': './src/client/index.js'  },  target: 'web',  output: {    filename: '[name].js',    path: path.resolve(__dirname, 'dist/public')  },  module: moduleObj,  plugins: [    new HtmlWebPackPlugin({      template: 'src/client/index.html'    })  ]}

Before we build the project, let’s modify our HTML file and remove the reference to the index.js script, because the above plugin will add that for us. This is especially useful when there are one or more files with dynamic filenames (for instance when files are generated with a unique timestamp for cache busting).

在构建项目之前,让我们修改HTML文件并删除对index.js脚本的引用,因为上面的插件将为我们添加该引用。 当存在一个或多个具有动态文件名的文件时(例如,当文件生成时带有唯一的时间戳以用于缓存清除),此功能特别有用。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>React Boilerplate</title></head><body>    <div id="root"></div></body></html>

Lets’s rebuild the project:

让我们重建项目:

npm run cleannpm installnpm run build

And, verify that our existing tests are still running:

并且,验证我们现有的测试仍在运行:

npm test

We have further updated the boilerplate to integrate React and Webpack, created additional NPM commands, dynamically referenced index.js in the HTML file, and exported it.

我们进一步更新了样板,以集成React和Webpack,创建其他NPM命令,在HTML文件中动态引用index.js并将其导出。

酶设定 (Enzyme Setup)

Before we add a React test, we need to integrate Enzyme, which will allow us to assert, manipulate and traverse react components.

在添加React测试之前,我们需要集成Enzyme ,这将使我们能够断言,操纵和遍历React组件。

Let’s start by installing Enzyme and enzyme-adapter-react-16, which is required to connect Enzyme to a project using react v16 and above.

让我们首先安装Enzyme和ases-adapter-react-16,这是使用React v16及更高版本将Enzyme连接到项目所必需的。

enzyme-adapter-react-16 has peer dependencies on react, react-dom, and react-test-renderer

Enzyme-adapter-react-16对react,react-dom和react-test-renderer具有同级依赖

npm i --save-dev enzyme enzyme-adapter-react-16 react-test-renderer

Create a file src/enzyme.setup.js with the following content:

创建具有以下内容的文件src / enzyme.setup.js:

import Enzyme from 'enzyme'import Adapter from 'enzyme-adapter-react-16'
Enzyme.configure({    adapter: new Adapter()})

We need to configure Jest to use src/enzyme.setup.js in package.json by adding the following section under the root object:

我们需要通过在根对象下添加以下部分,将Jest配置为在package.json中使用src / enzyme.setup.js:

{..."jest": {    "setupTestFrameworkScriptFile": "./src/enzyme.setup.js"  }...}

React组件测试 (React Component Test)

Let’s test the App Component and ensure that it renders the expected text. In addition, we will take a snapshot of that component so we can ensure that its structure hasn’t changed with every test run.

让我们测试App组件,并确保它呈现预期的文本。 此外,我们将对该组件进行快照,以便确保每次测试运行时其结构都没有改变。

Click here to learn more about snapshot testing.

单击此处以了解有关快照测试的更多信息 。

Create a test case under src/client/app.test.js with the following content:

在src / client / app.test.js下创建一个具有以下内容的测试用例:

import App from './app'import React from 'react'import {shallow} from 'enzyme'
describe('App', () => {  test('should match snapshot', () => {    const wrapper = shallow(&lt;App/>)
expect(wrapper.find('div').text()).toBe('Welcome to React Boilerplate App')    expect(wrapper).toMatchSnapshot()  })})

If we run this test now, it will pass with a warning:

如果我们现在运行此测试,它将通过警告:

Let’s fix that by installing a polyfill called raf:

让我们通过安装一个名为raf的polyfill来解决此问题:

npm i --saveDev raf

And changing the Jest configuration under package.json to:

并将package.json下的Jest配置更改为:

{..."jest": {    "setupTestFrameworkScriptFile": "./src/enzyme.setup.js",    "setupFiles": ["raf/polyfill"]  }...}

Now, you can verify that all our tests are passing:

现在,您可以验证我们所有的测试都通过了:

npm test

After running the react test, you will notice a new file at src/client/snapshots/app.test.js.snap. It contains the serialized structure of our react component. It must be checked into Git so it can be used to compare against the dynamically generated snapshot during a test run.

运行react测试后,您将在src / client / snapshots / app.test.js.snap中注意到一个新文件。 它包含我们的react组件的序列化结构。 必须将其检入Git,以便可以在测试运行期间将其与动态生成的快照进行比较。

决赛 (Final Run)

Let’s start the web server one more time and navigate to http://localhost:3000 to ensure everything works:

让我们再启动一次Web服务器,并导航到http:// localhost:3000以确保一切正常:

npm start

I hope this article has given you insights into streamlining the process of starting a new project from scratch with Express | React | Jest | Webpack | Babel. It is a good idea to create your own reusable boilerplate so you understand what goes on under the hood, and at the same time get a head-start when creating new projects.

我希望本文能为您提供一些见识,帮助他们简化使用Express |从头开始新项目的过程。 React| 开玩笑 Webpack | 巴别塔 创建自己的可重用样板是一个好主意,这样您就可以了解幕后的情况,同时在创建新项目时获得先机。

We have barely scratched the surface and there is a lot of room for improvement to make this boilerplate production ready.

我们几乎没有刮伤表面,并且有很多改进的余地可以使样板生产做好准备。

Here are some things for you to try:

以下是一些您可以尝试的事情:

  • Enable cache busting in Webpack

    在Webpack中启用缓存清除

  • CSS file bundling using css-loader in webpack

    在webpack中使用css-loader捆绑CSS文件

  • Enable source maps in webpack

    在Webpack中启用源地图

  • Add debug commands to package.json

    将调试命令添加到package.json

  • Hot module replacement

    热模块更换

  • Auto-restart web server when changes are detected via nodemon

    通过nodemon检测到更改后自动重启Web服务器

If you would like to learn more about the react ecosystem, I would highly recommend taking The Complete React Web Developer Course by Andrew Mead.

如果您想了解更多有关react生态系统的信息,我强烈建议您参加Andrew Mead 撰写的The Complete React Web Developer Course 。

如果这篇文章有帮助,??? 然后在Twitter上关注我。 (If this article was helpful, ??? and Follow me on Twitter.)

翻译自: https://www.freecodecamp.org/news/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f/

react组件样板


http://lihuaxi.xjx100.cn/news/239707.html

相关文章

私有vlan

一 拓扑图 二 配置私有vlan&#xff08;pvlan&#xff09; 只有VTP模式为透明模式&#xff0c;才能配置pvlan &#xff08;1&#xff09;配置pc1-4及s2(给测试用) pc1-4按照拓扑图上的说明配置 s2(config)#interface fastEthernet 0/1 s2(config-if)#switchport mode access s…

jfinal整合shiro回顾

2019独角兽企业重金招聘Python工程师标准>>> 目前jfinal使用shiro进行身份验证和授权的后台实现已完成&#xff0c;现在我再来总结下学习过程及代码实现过程。最近半年多项目开发都用.net&#xff0c;但又不甘心用了一年多的java&#xff0c;jfinal就这样被废弃&…

怎么用c语言做自动回复消息,【微信开发学习笔记】01消息自动回复关键词自动回复...

消息自动回复添加第10行代码&#xff0c;作用是调用第22行的responseMsg回复信息方法<?php /*** wechat php test*///define your tokendefine("TOKEN", "test");$wechatObj new wechatCallbackapiTest();//$wechatObj->valid();//调用回复方法$we…

渐进式web应用程序_渐进式Web应用程序简介

渐进式web应用程序Interested in learning JavaScript? Get my ebook at jshandbook.com有兴趣学习JavaScript吗&#xff1f; 在jshandbook.com上获取我的电子书 Progressive Web Apps (PWA) are the latest trend in mobile application development using web technologies.…

c语言逻辑推理题大全,C语言逻辑推理例题(附答案)

C语言逻辑推理例题(多重循环)C语言逻辑推理例题(多重循环)例1明明找不到铅笔盒了&#xff0c;妈妈对他说&#xff1a;“我把铅笔盒放到三个抽屉中的一个抽屉里了&#xff0c;每个抽屉上都写了一句话。不过&#xff0c;其中只有一句话是真的。”明明看到的三句话是&#xff1a; …

40.lombok在IntelliJ IDEA下的使用

转自&#xff1a;https://www.cnblogs.com/yjmyzz/p/lombok-with-intellij-idea.html lombok是一款可以精减java代码、提升开发人员生产效率的辅助工具&#xff0c;利用注解在编译期自动生成setter/getter/toString()/constructor之类的代码。代码越少&#xff0c;意味着出bug的…

《MySQL技术内幕:InnoDB存储引擎》读书笔记

2019独角兽企业重金招聘Python工程师标准>>> 1.InnoDB中每一页的大小默认为16kb&#xff0c;但是其也支持压缩页的功能&#xff0c;即将原本16kb的页压缩为1kb、2kb、4kb和8kb。当需要从缓存池中申请4kb大小的页时&#xff0c;MySQL的申请步骤如下&#xff1a; 检查…

热闹的聚会与尴尬的聚会_如何增加(和保存)您最喜欢的技术聚会

热闹的聚会与尴尬的聚会by Jen Weber詹韦伯(Jen Weber) 如何增加(和保存)您最喜欢的技术聚会 (How to Grow (and Save) Your Favorite Tech Meetup) Hey meetup facilitators, friends, and future leaders! Do you want more people to show up to your tech event? Or at l…