日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

如何使用Webpack 4简化React.js开发过程

發(fā)布時(shí)間:2023/11/29 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用Webpack 4简化React.js开发过程 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

by Margarita Obraztsova

瑪格麗塔(Margarita Obraztsova)

如何使用Webpack 4簡(jiǎn)化React.js開(kāi)發(fā)過(guò)程 (How to streamline your React.js development process using Webpack 4)

In the real world of development, we have to add new features very quickly. In this tutorial, I will show you everything you can do to streamline this process and reach 120% of your dev speed.

在現(xiàn)實(shí)世界中,我們必須非常快速地添加新功能。 在本教程中,我將向您展示簡(jiǎn)化該過(guò)程并達(dá)到開(kāi)發(fā)速度120%的所有方法。

Why, you might ask?

為什么 ,您可能會(huì)問(wèn)?

Because doing manual work is extremely counter-productive when it comes to programming. We want to automate as much as possible. So I will show you what parts of the development process with React we can adjust using Webpack v4.6.0.

因?yàn)樵诰幊虝r(shí)進(jìn)行手工工作會(huì)適得其反。 我們希望盡可能地自動(dòng)化。 因此,我將向您展示我們可以使用Webpack v4.6.0調(diào)整React開(kāi)發(fā)過(guò)程的哪些部分。

I will not cover the first steps of setting up the webpack configuration, since I have already done it in my previous post. There, I described how to configure Webpack in greater detail. I will assume you are already familiar with the Webpack configuration basics, so we can start with a ready setup.

我不會(huì)介紹設(shè)置Webpack配置的第一步, 因?yàn)槲以?strong>以前的帖子中已經(jīng)做過(guò) 在那里,我詳細(xì)介紹了如何配置Webpack。 我假設(shè)您已經(jīng)熟悉Webpack配置基礎(chǔ)知識(shí),因此我們可以從準(zhǔn)備就緒的安裝開(kāi)始。

設(shè)置Webpack (Setting up Webpack)

In your webpack.config.js, enter the following code:

在您的webpack.config.js中 ,輸入以下代碼:

// webpack v4const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const WebpackMd5Hash = require('webpack-md5-hash');const CleanWebpackPlugin = require('clean-webpack-plugin');module.exports = { entry: { main: './src/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] }, plugins: [ new CleanWebpackPlugin('dist', {} ), new HtmlWebpackPlugin({ inject: false, hash: true, template: './src/index.html', filename: 'index.html' }), new WebpackMd5Hash() ]};

and in your package.json:

并在您的package.json中 :

{ "name": "post", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack --mode production", "dev": "webpack --mode development" }, "author": "", "license": "ISC", "devDependencies": { "babel-cli": "^6.26.0", "babel-core": "^6.26.0", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "babel-runtime": "^6.26.0", "clean-webpack-plugin": "^0.1.19", "html-webpack-plugin": "^3.2.0", "react": "^16.3.2", "react-dom": "^16.3.2", "webpack": "^4.6.0", "webpack-cli": "^2.0.13", "webpack-md5-hash": "0.0.6" }}

Now you can download your node modules:

現(xiàn)在,您可以下載節(jié)點(diǎn)模塊:

npm i

and add src/ folder to your project with index.html and index.js

并使用index.html和index.js將src /文件夾添加到您的項(xiàng)目中

First in src/index.html:

首先在src / index.html中 :

<html> <head> </head> <body> <div id="app"></div> <script src="<%= htmlWebpackPlugin.files.chunks.main.entry %>"></script> </body></html>

and then in src/index.js:

然后在src / index.js中 :

console.log("hello, world");

Let’s run the dev script:

讓我們運(yùn)行dev腳本:

npm run dev

There you have it: it compiled! Now let’s configure React for it, too.

在那里,它已編譯! 現(xiàn)在,我們也為其配置React。

設(shè)置您的React項(xiàng)目 (Setting up your React project)

Since React uses special syntax called JSX, we need to transpile our code. If we go to babel’s website, it has the preset for React.

由于React使用稱(chēng)為JSX的特殊語(yǔ)法,因此我們需要翻譯我們的代碼。 如果我們?cè)L問(wèn)babel的網(wǎng)站,它具有React的預(yù)設(shè) 。

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

Our .babelrc file should look like this:

我們的.babelrc文件應(yīng)如下所示:

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

Add some app initialisation to your index.js:

在您的index.js中添加一些應(yīng)用程序初始化:

import React from 'react';import { render } from 'react-dom';class App extends React.Component {render() { return ( <div> 'Hello world!' </div> ); }}render(<App />, document.getElementById('app'));

and run the dev script:

并運(yùn)行開(kāi)發(fā)腳本:

npm run dev

If you managed to generate a ./dist folder with index.html and a main file with a hash, you have done great! We have our app compiling!

如果您設(shè)法用index.html生成一個(gè)./dist文件夾,并用一個(gè)哈希表生成一個(gè)主文件, 那么您做得很好! 我們有我們的應(yīng)用程序編譯!

設(shè)置web-dev-server (Setting up web-dev-server)

Technically, we do not have to do this, since there are many node-based servers for front-end apps out there. But I recommend webpack-dev-server because it is designed to work with Webpack, and it supports a bunch of nice features such as hot module replacement, source maps, and so on.

從技術(shù)上講,我們不必這樣做,因?yàn)槟抢镉性S多用于前端應(yīng)用程序的基于節(jié)點(diǎn)的服務(wù)器。 但是我建議使用webpack-dev-server,因?yàn)樗荚谂cWebpack一起使用,并且支持許多不錯(cuò)的功能,例如熱模塊替換源映射等 。

As they mention in the official documentation page:

正如他們?cè)诠俜轿臋n頁(yè)面中提到的:

Use webpack with a development server that provides live reloading. This should be used for development only.

將webpack與提供實(shí)時(shí)重載的開(kāi)發(fā)服務(wù)器一起使用。 這僅應(yīng)用于開(kāi)發(fā)。

Here is where it might get a bit confusing: how do you make webpack-dev-server only work for dev mode?

這可能會(huì)使您感到困惑:如何使webpack-dev-server只在dev模式下工作?

npm i webpack-dev-server --save-dev

in your package.json, adjust

在package.json中 ,調(diào)整

"scripts": { "dev": "webpack-dev-server --mode development --open", "build": "webpack --mode production"}

Now it should launch a server and automatically open your browser tab with your app.

現(xiàn)在,它應(yīng)該啟動(dòng)服務(wù)器,并使用您的應(yīng)用程序自動(dòng)打開(kāi)瀏覽器選項(xiàng)卡。

Your package.json looks like this at this point:

此時(shí)您的package.json看起來(lái)像這樣:

{ “name”: “post”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: { "dev": "webpack-dev-server --mode development --open", "build": "webpack --mode production" }, “author”: “”, “l(fā)icense”: “ISC”, “devDependencies”: { “babel-cli”: “6.26.0”, “babel-core”: “6.26.0”, “babel-loader”: “7.1.4”, “babel-preset-env”: “1.6.1”, “babel-preset-react”: “6.24.1”, “babel-runtime”: “6.26.0”, “clean-webpack-plugin”: “0.1.19”, “html-webpack-plugin”: “3.2.0”, “react”: “16.3.2”, “react-dom”: “16.3.2”, “webpack”: “4.6.0”, “webpack-cli”: “2.0.13”, “webpack-dev-server”: “3.1.3”, “webpack-md5-hash”: “0.0.6” }}

Now if you try to modify something in your app, the browser should automatically refresh the page.

現(xiàn)在,如果您嘗試修改應(yīng)用程序中的某些內(nèi)容,瀏覽器應(yīng)該會(huì)自動(dòng)刷新頁(yè)面。

Next, you need to download React devtools as a Chrome extension.

接下來(lái),您需要下載React devtools作為Chrome擴(kuò)展。

This way you can debug your app from the Chrome console much more easily.

這樣,您可以更輕松地從Chrome控制臺(tái)調(diào)試應(yīng)用。

ESLint配置 (ESLint configuration)

Why do we need it? Well, generally we do not have to use it. But ESLint is a handy tool. In our case, it will render our code (in the editor and terminal, and on the browser) and highlight our mistakes, typos, and errors if we have any. This is called linting.

我們?yōu)槭裁葱枰?#xff1f; 好吧,通常我們不必使用它。 但是ESLint是一個(gè)方便的工具。 就我們而言,它將呈現(xiàn)我們的代碼(在編輯器和終端以及在瀏覽器中),并突出顯示我們的錯(cuò)誤,錯(cuò)別字和錯(cuò)誤(如果有)。 這稱(chēng)為棉絨 。

ESLint is an open-source JavaScript linting utility originally created by Nicholas C. Zakas in June 2013. There are alternatives to it, but so far it works great with ES6 and React, finds common problems, and integrates with other parts of the ecosystem.

ESLint是最初由Nicholas C. Zakas在2013年6月創(chuàng)建的開(kāi)源JavaScript linting實(shí)用程序。它可以替代,但到目前為止,它與ES6和React兼容,可以發(fā)現(xiàn)常見(jiàn)問(wèn)題,并且可以與生態(tài)系統(tǒng)的其他部分集成。

For now, let’s install it locally for our own new project. Of course, ESLint at this point has a large number of settings. You can read more about them on the official website.

現(xiàn)在,讓我們?cè)诒镜貫槲覀冏约旱男马?xiàng)目安裝它。 當(dāng)然,此時(shí)ESLint具有大量設(shè)置。 您可以在官方網(wǎng)站上閱讀有關(guān)它們的更多信息。

npm install eslint --save-dev./node_modules/.bin/eslint --init

The last command will create a config file. You will be prompted to choose among three options:

最后一條命令將創(chuàng)建一個(gè)配置文件。 系統(tǒng)將提示您選擇三個(gè)選項(xiàng):

In this tutorial, I chose the first one: answering questions. Here are my answers:

在本教程中,我選擇了第一個(gè):回答問(wèn)題。 這是我的答案:

This will add .eslintrc.js file to your project directory. My generated file looks like this:

這會(huì)將.eslintrc.js文件添加到您的項(xiàng)目目錄中。 我生成的文件如下所示:

module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "indent": [ "error", 4 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] }};

Nothing happens so far. Although this is a perfectly valid config, it is not enough — we have to integrate it with Webpack and our text editor for it to work. As I mentioned, we can have it in the code editor, terminal (as a linter), or as a precommit hook. We will configure it for our editor for now.

到目前為止沒(méi)有任何React。 盡管這是一個(gè)完全有效的配置,但這還不夠—我們必須將其與Webpack和文本編輯器集成在一起才能正常工作。 正如我提到的,我們可以在代碼編輯器,終端(作為linter)或預(yù)提交鉤子中使用它。 現(xiàn)在,我們將為我們的編輯器配置它。

Visual Studio Code的安裝 (Setup for Visual Studio Code)

In case you are wondering, ESLint has a plugin for almost every major code editor, including Visual Studio Code, Visual Studio, SublimeText, Atom, WebStorm, and even vim. So go ahead and download the version for your own text editor. I will be using VS Code in this demo.

如果您想知道,ESLint的幾乎所有主要代碼編輯器都有一個(gè)插件,包括Visual Studio Code,Visual Studio,SublimeTextAtom,WebStorm甚至是vim。 因此,繼續(xù)為您自己的文本編輯器下載該版本。 我將在此演示中使用VS Code。

Now we can see some code errors appear. This is because the project has a configuration file that lints the code and complains when some rules are not obeyed.

現(xiàn)在我們可以看到一些代碼錯(cuò)誤出現(xiàn)。 這是因?yàn)轫?xiàng)目具有一個(gè)配置文件,該文件可以減少代碼并在未遵守某些規(guī)則時(shí)進(jìn)行投訴。

You can debug it manually by checking the error message, or you can take advantage of it and just press save and it will automatically fix things.

您可以通過(guò)檢查錯(cuò)誤消息來(lái)手動(dòng)調(diào)試它,也可以利用它,然后按保存,它將自動(dòng)修復(fù)問(wèn)題。

You can now go and adjust the ESLint settings:

現(xiàn)在,您可以調(diào)整ESLint設(shè)置:

module.exports = { "env": { "browser": true, "commonjs": true, "es6": true }, "extends": ["eslint:recommended", "plugin:react/recommended"], "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "warn", "single" ], "semi": [ "error", "always" ] }};

This will not break the build if you included double quotes by mistake instead of single quotes. It will also add some checks for JSX.

如果您錯(cuò)誤地使用雙引號(hào)而不是單引號(hào),則不會(huì)破壞構(gòu)建。 它還將為JSX添加一些檢查。

添加更漂亮 (Add Prettier)

Prettier is one of the most popular formatters nowadays, and it is well-accepted by the coding community. It can be added to ESLint, your editor, and also installed as a pre-commit hook.

Prettier是當(dāng)今最受歡迎的格式化程序之一,并且已被編碼社區(qū)廣泛接受。 可以將其添加到您的編輯器 ESLint中,也可以將其安裝為預(yù)提交掛鉤。

Once you install it, you can try to check your code again. If we write some weird indentation and press save, it should automatically format the code now.

安裝后,您可以嘗試再次檢查代碼。 如果我們寫(xiě)一些奇怪的縮進(jìn)并按保存,它應(yīng)該立即自動(dòng)格式化代碼。

That is not enough yet. In order for ESLint to work synched and not emit the same errors twice, or even have rules conflicts, you need to integrate it with your ESLint.

還不夠。 為了使ESLint能夠同步工作并且不會(huì)兩次發(fā)出相同的錯(cuò)誤,甚至不會(huì)發(fā)生規(guī)則沖突,您需要將其與ESLint集成。

npm i --save-dev prettier eslint-plugin-prettier

In the official docs, they recommend that you use yarn , but npm will do for now. To your .eslintrc.json file add:

在官方文檔中,他們建議您使用yarn,但是npm現(xiàn)在可以使用。 在您的.eslintrc.json文件中添加:

... sourceType: "module"},plugins: ["react", "prettier"],extends: ["eslint:recommended", "plugin:react/recommended"],rules: { indent: ["error", 2], "linebreak-style": ["error", "unix"], quotes: ["warn", "single"], semi: ["error", "always"], "prettier/prettier": "error"}...

Now we want to extend our ESLint rules to include prettier rules:

現(xiàn)在,我們想擴(kuò)展我們的ESLint規(guī)則,使其包含更漂亮的規(guī)則:

npm i --save-dev eslint-config-prettier

and add some extends to your eslint config:

并將一些擴(kuò)展添加到您的eslint配置中:

...extends: [ "eslint:recommended", "plugin:react/recommended", "prettier", "plugin:prettier/recommended"]...

Let’s add some more configurations to it. You should do this in order to avoid mismatches between default Prettier rules and your ESLint rules, like the one I have now:

讓我們?yōu)槠涮砑痈嗯渲?。 您應(yīng)該這樣做,以避免默認(rèn)的Prettier規(guī)則與您的ESLint規(guī)則不匹配,就像我現(xiàn)在所擁有的那樣:

Prettier borrows ESLint’s override format. This allows you to apply configuration to specific files.

漂亮的借用了ESLint的替代格式 。 這使您可以將配置應(yīng)用于特定文件。

You can now create a config file for it in the form of a .js file.

您現(xiàn)在可以以.js文件的形式為其創(chuàng)建配置文件。

nano prettier.config.js

Now, paste in that file:

現(xiàn)在,粘貼該文件:

module.exports = { printWidth: 80, tabWidth: 2, semi: true, singleQuote: true, bracketSpacing: true};

Now when you press save, you see your code being automatically formatted. Isn’t that way prettier? Pun very much intended.

現(xiàn)在,當(dāng)您按保存時(shí),您會(huì)看到代碼被自動(dòng)格式化。 這樣不是更漂亮嗎? 雙關(guān)語(yǔ)非常有意。

My package.json looks like this:

我的package.json看起來(lái)像這樣:

{ "name": "post", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build": "webpack --mode production", "dev": "webpack-dev-server --mode development --open" }, "author": "", "license": "ISC", "devDependencies": { "babel-cli": "^6.26.0", "babel-core": "^6.26.0", "babel-loader": "^7.1.4", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "babel-runtime": "^6.26.0", "clean-webpack-plugin": "^0.1.19", "eslint": "^4.19.1", "eslint-config-prettier": "^2.9.0", "eslint-plugin-prettier": "^2.6.0", "eslint-plugin-react": "^7.7.0", "html-webpack-plugin": "^3.2.0", "prettier": "^1.12.1", "react": "^16.3.2", "react-dom": "^16.3.2", "webpack": "^4.6.0", "webpack-cli": "^2.0.13", "webpack-dev-server": "^3.1.4", "webpack-md5-hash": "0.0.6" }}

Now that we have this all set up, let’s quickly recap: ESLint watches your code for errors, and Prettier is a style formatting tool. ESLint has many more ways to catch errors, while Prettier formats your code nicely.

現(xiàn)在我們已經(jīng)完成了所有的設(shè)置,讓我們快速回顧一下:ESLint監(jiān)視您的代碼中是否有錯(cuò)誤,而Prettier是一種樣式格式化工具。 ESLint具有更多捕獲錯(cuò)誤的方法,而Prettier可以很好地格式化代碼。

// webpack v4const path = require('path');const HtmlWebpackPlugin = require('html-webpack-plugin');const WebpackMd5Hash = require('webpack-md5-hash');const CleanWebpackPlugin = require('clean-webpack-plugin');module.exports = { entry: { main: './src/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] }, plugins: [ new CleanWebpackPlugin('dist', {} ), new HtmlWebpackPlugin({ inject: false, hash: true, template: './src/index.html', filename: 'index.html' }), new WebpackMd5Hash() ]};

問(wèn)題:Prettier不會(huì)自動(dòng)格式化Visual Studio Code中的代碼 (Issue: Prettier does not automatically format code in Visual Studio Code)

A few people have pointed out that VS Code does not work with Prettier.

少數(shù)人指出VS Code不適用于Prettier。

If your Prettier plugin does not format the code automatically on save, you ca fix it by adding this code to VS Code settings:

如果您的Prettier插件沒(méi)有在保存時(shí)自動(dòng)格式化代碼,則可以通過(guò)將以下代碼添加到VS Code設(shè)置中進(jìn)行修復(fù):

"[javascript]": { "editor.formatOnSave": true }

as described here.

作為描述在這里 。

將ESLint加載程序添加到管道中 (Adding ESLint loader to your pipeline)

Since ESLint is configured in the project, it will also complain in your terminal once you run dev server.

由于ESLint是在項(xiàng)目中配置的,因此一旦運(yùn)行dev服務(wù)器,它也會(huì)在您的終端中發(fā)出投訴。

Note: Although it is possible to do, at this moment I do not recommend using ESLint as a loader. It will break source map setup, which I described in greater details in my previous article How to solve Webpack problems. The Practical Case. I will show how to set it up here, in case the guys have already fixed the bug they had.

注意 :盡管可以這樣做,但目前不建議將ESLint用作加載程序。 它將破壞源映射的設(shè)置,我在上一篇文章“ 如何解決Webpack問(wèn)題”中對(duì)此進(jìn)行了更詳細(xì)的描述。 實(shí)際案例。 如果這些家伙已經(jīng)修復(fù)了他們的錯(cuò)誤,我將在這里展示如何設(shè)置它。

Webpack has its own ESLint loader.

Webpack有其自己的ESLint加載程序 。

npm install eslint-loader --save-dev

You have to add ESLint to rules. When using with transpiling loaders (like babel-loader), make sure they are in the correct order (bottom to top). Otherwise, the files will be checked after being processed by babel-loader

您必須將ESLint添加到規(guī)則中。 與轉(zhuǎn)載式裝載機(jī)(如babel-loader )一起使用時(shí),請(qǐng)確保它們的順序正確(從下到上)。 否則,文件將由babel-loader處理后進(jìn)行檢查

...module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [{ loader: "babel-loader" }, { loader: "eslint-loader" }] } ]},...

Here are some possible issues you might have:

這是您可能遇到的一些問(wèn)題:

  • add an unused variable to your index file

    將未使用的變量添加到索引文件

If you stumble upon this error (no-unused-vars), it is pretty well explained in this issue on GitHub and here.

如果您偶然發(fā)現(xiàn)此錯(cuò)誤(no-unused-vars),則可以在GitHub和此處的 本期中對(duì)此進(jìn)行了很好的解釋。

We can solve this problem by adding some rules, explained here and here.

我們可以通過(guò)添加一些規(guī)則來(lái)解決此問(wèn)題,這些規(guī)則在此處和此處進(jìn)行了說(shuō)明。

As you might have noticed, you get the no-unused-vars error here. You need to make it a warning and not a error, because this way it way easier to do fast development. You need to add a new rule to your ESLint so that you do not get the default error.

您可能已經(jīng)注意到,您在這里遇到了no-unused-vars錯(cuò)誤。 您需要使其成為警告而不是錯(cuò)誤,因?yàn)檫@樣可以更輕松地進(jìn)行快速開(kāi)發(fā)。 您需要向ESLint添加新規(guī)則,以免出現(xiàn)默認(rèn)錯(cuò)誤。

You can read about this setup more here and here.

您可以在此處和此處了解有關(guān)此設(shè)置的更多信息 。

...semi: ['error', 'always'],'no-unused-vars': [ 'warn', { vars: 'all', args: 'none', ignoreRestSiblings: false }],'prettier/prettier': 'error'}...

This way we will get pretty error and warning messages.

這樣,我們將得到漂亮的錯(cuò)誤和警告消息。

I like the idea of having an auto fix feature, but let’s be clear: I am not the biggest fan of having things magically change. To avoid that situation we can commit autofix for now.

我喜歡具有自動(dòng)修復(fù)功能的想法,但請(qǐng)清楚一點(diǎn):我不是對(duì)事物進(jìn)行神奇更改的最大粉絲。 為了避免這種情況,我們現(xiàn)在可以提交自動(dòng)修復(fù)。

預(yù)提交鉤 (Pre commit hook)

People are usually very careful when it comes to using Git tools. But I assure you, this one is very easy and straightforward. Pre commit hooks with Prettier are used so that teams have consistent codebase style across every project file, and nobody can commit unstyled code. Setup Git integration for your project like this:

人們?cè)谑褂肎it工具時(shí)通常非常小心。 但我向您保證,這一步驟非常簡(jiǎn)單明了。 使用帶有Prettier的Pre commit鉤子,以便團(tuán)隊(duì)在每個(gè)項(xiàng)目文件中具有一致的代碼庫(kù)樣式,并且沒(méi)有人可以提交未樣式化的代碼。 為您的項(xiàng)目設(shè)置Git集成,如下所示:

git initgit add .nano .gitignore (add your node_modules there)git commit -m "First commit"git remote add origin your origingit push -u origin master

Here are some great articles on git hooks and using Prettier.

這是一些有關(guān)git hook和使用Prettier的精彩文章。

For people who say you can only do it locally — no, that’s not true!

對(duì)于那些說(shuō)您只能在本地進(jìn)行的人-不,那不是真的!

You can do it using lint-stage tool from this repository by Andrey Okonetchnikov.

您可以使用不起毛的階段工具從做這個(gè)庫(kù)由安德烈Okonetchnikov 。

添加propTypes (Adding propTypes)

Let’s create a new component in our app. So far, our index.js looks like this:

讓我們?cè)趹?yīng)用程序中創(chuàng)建一個(gè)新組件。 到目前為止,我們的index.js看起來(lái)像這樣:

import React from 'react';import { render } from 'react-dom';class App extends React.Component { render() { return <div>Hello</div>; }}render(<App />, document.getElementById('app'));

We will create a new component called Hello.js for demo purposes.

為了演示目的,我們將創(chuàng)建一個(gè)名為Hello.js的新組件。

import React from 'react';class Hello extends React.Component { render() { return <div>{this.props.hello}</div>; }}export default Hello;

Now import it to your index.js file:

現(xiàn)在將其導(dǎo)入到您的index.js文件中:

import React from 'react';import { render } from 'react-dom';import Hello from './Hello';class App extends React.Component { render() { return ( <div> <Hello hello={'Hello, world! And the people of the world!'} /> </div> ); }}render(<App />, document.getElementById('app'));

We were supposed to see the element, but ESLint complains:

我們應(yīng)該看到該元素,但是ESLint抱怨:

Error: [eslint] ‘hello’ is missing in props validation (react/prop-types)

錯(cuò)誤:道具驗(yàn)證中缺少[eslint]'hello'(React/道具類(lèi)型)

In React v16, it is mandatory to add prop types in order to avoid type confusion. You can read more about it here.

在React v16中,為了避免類(lèi)型混淆,必須添加prop類(lèi)型 。 您可以在此處了解更多信息。

import React from 'react';import PropTypes from 'prop-types';class Hello extends React.Component { render() { return <div>{this.props.hello}</div>; }}Hello.propTypes = { hello: PropTypes.string};export default Hello;

熱模塊更換 (Hot module replacement)

Now that you have your code checked, it is time to add more components to your React app. So far you only have two, but in most cases you have dozens.

現(xiàn)在您已經(jīng)檢查了代碼,是時(shí)候向React應(yīng)用程序添加更多組件了。 到目前為止,您只有兩個(gè),但是在大多數(shù)情況下,您只有幾十個(gè)。

Of course, recompiling the entire app on refresh every time you change something in your project is not an option. You need a faster way to do it.

當(dāng)然,每次更改項(xiàng)目中的內(nèi)容時(shí)都不能在刷新時(shí)重新編譯整個(gè)應(yīng)用程序。 您需要一種更快的方法。

So let’s add hot module replacement, aka HMR. In the documentation, it is described as:

因此,讓我們添加熱模塊替換(又名HMR)。 在文檔中 ,它描述為:

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development in a few ways:

熱模塊替換(HMR)在應(yīng)用程序運(yùn)行時(shí)交換,添加或刪除模塊 ,而無(wú)需完全重新加載。 這可以通過(guò)以下幾種方式顯著加快開(kāi)發(fā)速度:

Retain application state which is lost during a full reload.保留在完全重載期間丟失的應(yīng)用程序狀態(tài)。 Save valuable development time by only updating what’s changed.僅更新更改內(nèi)容即可節(jié)省寶貴的開(kāi)發(fā)時(shí)間。 Tweak styling faster — almost comparable to changing styles in the browser’s debugger.調(diào)整樣式的速度更快-幾乎可以與瀏覽器調(diào)試器中樣式的更改相提并論。

I am not going into the technicalities of how it works here: that would be the subject of a separate post. But here is how to configure it:

我不打算討論它在這里如何工作的技術(shù)性:那將是一個(gè)單獨(dú)帖子的主題。 但是這里是如何配置它:

...output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash].js'},devServer: { contentBase: './dist', hot: true},module: { rules: [...

解決HMR的小問(wèn)題 (Solving small issues with HMR)

We had to replace chunkhash with hash, because evidently webpack has fixed that issue since the last time. Now we have hot module replacement working!

我們必須用hash替換chunkhash,因?yàn)樽陨洗我詠?lái),顯然webpack已解決了該問(wèn)題。 現(xiàn)在我們可以進(jìn)行熱模塊更換了!

...module.exports = { entry: { main: './src/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[hash].js' }, devServer: { contentBase: './dist',...

解決錯(cuò)誤 (Solving bugs)

If we run the dev script here:

如果我們?cè)诖颂庍\(yùn)行開(kāi)發(fā)腳本:

then use tips from this issue to fix it.

然后使用此問(wèn)題的技巧進(jìn)行修復(fù)。

Next, add — hot flag to dev script in package.json:

接下來(lái),在package.json中添加—熱標(biāo)記到開(kāi)發(fā)腳本:

..."scripts": { "build": "webpack --mode production", "dev": "webpack-dev-server --hot"}...

源圖: (Source maps:)

As I mentioned above, source maps will not work together with ESLint loader. I have filed an issue here.

如上所述, 源映射無(wú)法與ESLint加載器一起使用。 我在這里提了一個(gè)問(wèn)題。

Usually, you would not want them in your project anyway (since you want to debug your project from ESLint error messages). They are also known for making HMR slower.通常,您無(wú)論如何都不希望它們出現(xiàn)在您的項(xiàng)目中(因?yàn)槟霃腅SLint錯(cuò)誤消息中調(diào)試項(xiàng)目)。 它們還以降低HMR速度而聞名。

You can read about it more here and here.

您可以在這里和這里了解更多。

But if you want source maps anyway, the easiest way to add them is through the devtools option.

但是,無(wú)論如何,如果想要源映射,添加它們的最簡(jiǎn)單方法是通過(guò)devtools選項(xiàng)。

...module.exports = { entry: { main: './src/index.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[hash].js' }, devtool: 'inline-source-map', devServer: { contentBase: './dist', hot: true }, ...

Note: source maps will not work until you specify the environment the right way. You can read about my process of debugging here. Below I will provide you with a spoiler and explanation of how I solved that issue.

注意:在您以正確的方式指定環(huán)境之前,源地圖將無(wú)法工作。 您可以在此處閱讀有關(guān)我的調(diào)試過(guò)程的信息 。 下面,我將為您提供擾流器并解釋如何解決該問(wèn)題。

If we now go and create an error in our code, this will be displayed in the console and will point us to the right place:

如果現(xiàn)在我們?cè)诖a中創(chuàng)建錯(cuò)誤,它將顯示在控制臺(tái)中,并將我們指向正確的位置:

…or so we thought. But nope:

……所以我們認(rèn)為。 但沒(méi)有:

You need to change the environment variable like this:

您需要像這樣更改環(huán)境變量:

..."main": "index.js","scripts": { "build": "webpack --mode=production", "start": "NODE_ENV=development webpack-dev-server --mode=development --hot"},"author": ""...

webpack.config.js

webpack.config.js

...devtool: 'inline-source-map',devServer: { contentBase: './dist', open: true}...

Now it works!

現(xiàn)在可以了!

Now you have successfully setup the development environment for your project!

現(xiàn)在,您已經(jīng)為項(xiàng)目成功設(shè)置了開(kāi)發(fā)環(huán)境!

Lets recap:

讓我們回顧一下:

  • We set up webpack

    我們?cè)O(shè)置了webpack
  • We created our first React component

    我們創(chuàng)建了第一個(gè)React組件
  • We included ESLint to check the code for mistakes

    我們包含了ESLint來(lái)檢查代碼是否有錯(cuò)誤
  • We set up hot module replacement

    我們?cè)O(shè)置熱模塊更換
  • We (maybe) added source maps

    我們(也許)添加了源地圖

Note: since a lot of npm dependencies might change by the time you read this, the same config might not work for you. I kindly ask you to leave your errors in the comments below so that I can edit it later.

注意 :由于許多npm依賴(lài)項(xiàng)在您閱讀本文時(shí)可能會(huì)更改,因此相同的配置可能對(duì)您不起作用。 懇請(qǐng)您在下面的評(píng)論中保留您的錯(cuò)誤,以便稍后進(jìn)行編輯。

Please, Subscribe and Clap for this article! Thanks!

請(qǐng)訂閱并拍擊本文! 謝謝!

More materials:

更多材料:

SurviveJS — WebpackAfter weeks failing at configuring webpack, I stumbled upon SurviveJS book while looking for yet another tutorial…survivejs.comA Beginner’s Guide to Webpack 4 and Module Bundling — SitePointWebpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also…www.sitepoint.com

SurviveJS — Webpack 在配置Webpack數(shù)周后失敗后,我偶然發(fā)現(xiàn)了SurviveJS的書(shū),同時(shí)又尋找了另一篇教程…… Survivive.com Webpack 4和模塊捆綁的初學(xué)者指南— SitePoint Webpack是一個(gè)模塊捆綁器。 它的主要目的是捆綁JavaScript文件以供在瀏覽器中使用,但它也是…… www.sitepoint.com

翻譯自: https://www.freecodecamp.org/news/how-to-develop-react-js-apps-fast-using-webpack-4-3d772db957e4/

總結(jié)

以上是生活随笔為你收集整理的如何使用Webpack 4简化React.js开发过程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。