如何使用Webpack 4簡化React.js開發過程

by Margarita Obraztsova

瑪格麗塔(Margarita Obraztsova)

如何使用Webpack 4簡化React.js開發過程 (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.

在現實世界中,我們必須非常快速地添加新功能。 在本教程中,我將向您展示簡化該過程并達到開發速度120%的所有方法。

Why, you might ask?

為什么 ,您可能會問?

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.

因為在編程時進行手工工作會適得其反。 我們希望盡可能地自動化。 因此,我將向您展示我們可以使用Webpack v4.6.0調整React開發過程的哪些部分。

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.

我不會介紹設置Webpack配置的第一步, 因為我在以前的帖子中已經做過 在那里,我詳細介紹了如何配置Webpack。 我假設您已經熟悉Webpack配置基礎知識,因此我們可以從準備就緒的安裝開始。

設置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:

現在,您可以下載節點模塊:

npm i

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

并使用index.htmlindex.jssrc /文件夾添加到您的項目中

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:

讓我們運行dev腳本:

npm run dev

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

在那里,它已編譯! 現在,我們也為其配置React。

設置您的React項目 (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使用稱為JSX的特殊語法,因此我們需要翻譯我們的代碼。 如果我們訪問babel的網站,它具有React的預設 。

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

Our .babelrc file should look like this:

我們的.babelrc文件應如下所示:

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

Add some app initialisation to your index.js:

在您的index.js中添加一些應用程序初始化:

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:

并運行開發腳本:

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!

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

設置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.

從技術上講,我們不必這樣做,因為那里有許多用于前端應用程序的基于節點的服務器。 但是我建議使用webpack-dev-server,因為它旨在與Webpack一起使用,并且支持許多不錯的功能,例如熱模塊替換源映射等

As they mention in the official documentation page:

正如他們在官方文檔頁面中提到的:

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

將webpack與提供實時重載的開發服務器一起使用。 這僅應用于開發。

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

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

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

in your package.json, adjust

package.json中 ,調整

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

現在,它應該啟動服務器,并使用您的應用程序自動打開瀏覽器選項卡。

Your package.json looks like this at this point:

此時您的package.json看起來像這樣:

{ “name”: “post”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: {   "dev": "webpack-dev-server --mode development --open",   "build": "webpack --mode production" }, “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-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.

現在,如果您嘗試修改應用程序中的某些內容,瀏覽器應該會自動刷新頁面。

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

接下來,您需要下載React devtools作為Chrome擴展。

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

這樣,您可以更輕松地從Chrome控制臺調試應用。

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.

我們為什么需要它? 好吧,通常我們不必使用它。 但是ESLint是一個方便的工具。 就我們而言,它將呈現我們的代碼(在編輯器和終端以及在瀏覽器中),并突出顯示我們的錯誤,錯別字和錯誤(如果有)。 這稱為棉絨

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月創建的開源JavaScript linting實用程序。它可以替代,但到目前為止,它與ES6和React兼容,可以發現常見問題,并且可以與生態系統的其他部分集成。

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.

現在,讓我們在本地為我們自己的新項目安裝它。 當然,此時ESLint具有大量設置。 您可以在官方網站上閱讀有關它們的更多信息。

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:

最后一條命令將創建一個配置文件。 系統將提示您選擇三個選項:

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

在本教程中,我選擇了第一個:回答問題。 這是我的答案:

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

這會將.eslintrc.js文件添加到您的項目目錄中。 我生成的文件如下所示:

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.

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

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的幾乎所有主要代碼編輯器都有一個插件,包括Visual Studio Code,Visual Studio,SublimeTextAtom,WebStorm甚至是vim。 因此,繼續為您自己的文本編輯器下載該版本。 我將在此演示中使用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.

現在我們可以看到一些代碼錯誤出現。 這是因為項目具有一個配置文件,該文件可以減少代碼并在未遵守某些規則時進行投訴。

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.

您可以通過檢查錯誤消息來手動調試它,也可以利用它,然后按保存,它將自動修復問題。

You can now go and adjust the ESLint settings:

現在,您可以調整ESLint設置:

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.

如果您錯誤地使用雙引號而不是單引號,則不會破壞構建。 它還將為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是當今最受歡迎的格式化程序之一,并且已被編碼社區廣泛接受。 可以將其添加到您的編輯器 ESLint中,也可以將其安裝為預提交掛鉤。

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.

安裝后,您可以嘗試再次檢查代碼。 如果我們寫一些奇怪的縮進并按保存,它應該立即自動格式化代碼。

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能夠同步工作并且不會兩次發出相同的錯誤,甚至不會發生規則沖突,您需要將其與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現在可以使用。 在您的.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:

現在,我們想擴展我們的ESLint規則,使其包含更漂亮的規則:

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

and add some extends to your eslint config:

并將一些擴展添加到您的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:

讓我們為其添加更多配置 。 您應該這樣做,以避免默認的Prettier規則與您的ESLint規則不匹配,就像我現在所擁有的那樣:

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

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

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

您現在可以以.js文件的形式為其創建配置文件。

nano prettier.config.js

Now, paste in that file:

現在,粘貼該文件:

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.

現在,當您按保存時,您會看到代碼被自動格式化。 這樣不是更漂亮嗎? 雙關語非常有意。

My package.json looks like this:

我的package.json看起來像這樣:

{ "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.

現在我們已經完成了所有的設置,讓我們快速回顧一下:ESLint監視您的代碼中是否有錯誤,而Prettier是一種樣式格式化工具。 ESLint具有更多捕獲錯誤的方法,而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()  ]};

問題:Prettier不會自動格式化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.

少數人指出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插件沒有在保存時自動格式化代碼,則可以通過將以下代碼添加到VS Code設置中進行修復:

"[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是在項目中配置的,因此一旦運行dev服務器,它也會在您的終端中發出投訴。

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用作加載程序。 它將破壞源映射的設置,我在上一篇文章“ 如何解決Webpack問題”中對此進行了更詳細的描述。 實際案例。 如果這些家伙已經修復了他們的錯誤,我將在這里展示如何設置它。

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添加到規則中。 與轉載式裝載機(如babel-loader )一起使用時,請確保它們的順序正確(從下到上)。 否則,文件將由babel-loader處理后進行檢查

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

Here are some possible issues you might have:

這是您可能遇到的一些問題:

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

如果您偶然發現此錯誤(no-unused-vars),則可以在GitHub和此處的 本期中對此進行了很好的解釋。

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

我們可以通過添加一些規則來解決此問題,這些規則在此處和此處進行了說明。

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.

您可能已經注意到,您在這里遇到了no-unused-vars錯誤。 您需要使其成為警告而不是錯誤,因為這樣可以更輕松地進行快速開發。 您需要向ESLint添加新規則,以免出現默認錯誤。

You can read about this setup more here and here.

您可以在此處和此處了解有關此設置的更多信息 。

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

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

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.

我喜歡具有自動修復功能的想法,但請清楚一點:我不是對事物進行神奇更改的最大粉絲。 為了避免這種情況,我們現在可以提交自動修復。

預提交鉤 (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:

人們在使用Git工具時通常非常小心。 但我向您保證,這一步驟非常簡單明了。 使用帶有Prettier的Pre commit鉤子,以便團隊在每個項目文件中具有一致的代碼庫樣式,并且沒有人可以提交未樣式化的代碼。 為您的項目設置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.

這是一些有關git hook和使用Prettier的精彩文章。

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

對于那些說您只能在本地進行的人-不,那不是真的!

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

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

添加propTypes (Adding propTypes)

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

讓我們在應用程序中創建一個新組件。 到目前為止,我們的index.js看起來像這樣:

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.

為了演示目的,我們將創建一個名為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:

現在將其導入到您的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:

我們應該看到該元素,但是ESLint抱怨:

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

錯誤:道具驗證中缺少[eslint]'hello'(React/道具類型)

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中,為了避免類型混淆,必須添加prop類型 。 您可以在此處了解更多信息。

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.

現在您已經檢查了代碼,是時候向React應用程序添加更多組件了。 到目前為止,您只有兩個,但是在大多數情況下,您只有幾十個。

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.

當然,每次更改項目中的內容時都不能在刷新時重新編譯整個應用程序。 您需要一種更快的方法。

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)在應用程序運行時交換,添加或刪除模塊 ,而無需完全重新加載。 這可以通過以下幾種方式顯著加快開發速度:

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

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:

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

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

解決HMR的小問題 (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,因為自上次以來,顯然webpack已解決了該問題。 現在我們可以進行熱模塊更換了!

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

解決錯誤 (Solving bugs)

If we run the dev script here:

如果我們在此處運行開發腳本:

then use tips from this issue to fix it.

然后使用此問題的技巧進行修復。

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

接下來,在package.json中添加—熱標記到開發腳本:

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

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

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.
通常,您無論如何都不希望它們出現在您的項目中(因為您想從ESLint錯誤消息中調試項目)。 它們還以降低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.

但是,無論如何,如果想要源映射,添加它們的最簡單方法是通過devtools選項。

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

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

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:

如果現在我們在代碼中創建錯誤,它將顯示在控制臺中,并將我們指向正確的位置:

…or so we thought. But nope:

……所以我們認為。 但沒有:

You need to change the environment variable like this:

您需要像這樣更改環境變量:

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

現在可以了!

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

現在,您已經為項目成功設置了開發環境!

Lets recap:

讓我們回顧一下:

  • We set up webpack

    我們設置了webpack
  • We created our first React component

    我們創建了第一個React組件
  • We included ESLint to check the code for mistakes

    我們包含了ESLint來檢查代碼是否有錯誤
  • We set up hot module replacement

    我們設置熱模塊更換
  • 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依賴項在您閱讀本文時可能會更改,因此相同的配置可能對您不起作用。 懇請您在下面的評論中保留您的錯誤,以便稍后進行編輯。

Please, Subscribe and Clap for this article! Thanks!

請訂閱并拍擊本文! 謝謝!

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數周后失敗后,我偶然發現了SurviveJS的書,同時又尋找了另一篇教程…… Survivive.com Webpack 4和模塊捆綁的初學者指南— SitePoint Webpack是一個模塊捆綁器。 它的主要目的是捆綁JavaScript文件以供在瀏覽器中使用,但它也是…… www.sitepoint.com

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393979.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393979.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393979.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HDU - 3247 Resource Archiver (AC自動機,狀壓dp)

\(\quad\)Great! Your new software is almost finished! The only thing left to do is archiving all your n resource files into a big one.\(\quad\)Wait a minute… you realized that it isn’t as easy as you thought. Think about the virus killers. They’ll find …

space index.php 7-14,disk_free_space()

disk_free_space()(PHP 4 > 4.1.0, PHP 5, PHP 7)返回目錄中的可用空間說明disk_free_space(string$directory):float給出一個包含有一個目錄的字符串&#xff0c;本函數將根據相應的文件系統或磁盤分區返回可用的字節數。參數$directory文件系統目錄或者磁盤分區。Note:如果…

云專網和云專線的區別_企業更適合互聯網專線還是云專線聯網?

隨著云計算、移動應用及全球化的發展&#xff0c;縱橫企業專網20年的MPLS專線弊端逐漸暴露&#xff0c;MPLS專線越來越難以滿足企業的業務發展需求&#xff0c;而云計算、SaaS及移動應用具有天然的互聯網屬性。為什么“互聯網”可以取代專線?互聯網的持續發展&#xff0c;為取…

composer安裝thinkphp

https://getcomposer.org/Composer-Setup.exe 正常安裝composer以后,執行composer create-project topthink/thinkphp myapp安裝thinkphp.轉載于:https://www.cnblogs.com/lijurui/p/6362012.html

wordpress 插件_如何為您的Web應用程序創建WordPress插件

wordpress 插件by Feedier by Alkalab由Feedier通過Alkalab 如何為您的Web應用程序創建WordPress插件 (How to create a WordPress plugin for your web app) Today, we are going to see how to create a very simple WordPress plugin for any web app that needs to insert…

Android 軟鍵盤相關問題

1. windowSoftInputMode屬性的使用 Android使用windowSoftInputMode來控制Activity 的主窗口與包含屏幕軟鍵盤的窗口的交互方式。 該屬性的設置影響兩個方面&#xff1a; 當 Activity 成為用戶注意的焦點時軟鍵盤的狀態 — 隱藏還是可見。對 Activity 主窗口所做的調整 — 是否…

git php框架,如何用Git安裝TP框架

本篇文章主要給大家介紹如何用Git安裝Thinkphp框架。關于TP框架的安裝&#xff0c;想必大家都知道較為常見的方式是通過composer安裝tp框架。首先簡單的給大家介紹下Git和TP框架。Git是一個開源的分布式版本控制系統&#xff0c;可以快速&#xff0c;高效地處理從小型到大型項目…

C#EF中,使用類似于SQL中的% 模糊查詢

最近在做項目的時候需要使用到模糊查詢,但是后臺使用EF寫的 而不是ADO或者是Dapper,如果是這樣的話,我們就可以使用Sql語句直接進行模糊查詢 現在我們需要在LINQ中使用類似于模糊查詢 在EF中有兩個方法:StartsWith()和EndWith() StartsWith(): 在轉到定義時 我們可以看見,這個方…

android toast居中顯示_Android Toast 設置到屏幕中間,自定義Toast的實現方法,及其說明...

Android Toast用于在手機屏幕上向用戶顯示一條信息&#xff0c;一段時間后信息會自動消失。信息可以是簡單的文本&#xff0c;也可以是復雜的圖片及其他內容(顯示一個view)。1.簡單用法Toast.makeText(midlet.getApplicationContext(), "用戶名不能為空", Toast.LENG…

leetcode103. 二叉樹的鋸齒形層次遍歷(bfs)

給定一個二叉樹&#xff0c;返回其節點值的鋸齒形層次遍歷。&#xff08;即先從左往右&#xff0c;再從右往左進行下一層遍歷&#xff0c;以此類推&#xff0c;層與層之間交替進行&#xff09;。例如&#xff1a; 給定二叉樹 [3,9,20,null,null,15,7],3/ \9 20/ \15 7 返回…

LintCode Find the Weak Connected Component in the Directed Graph

原題鏈接在這里&#xff1a;http://www.lintcode.com/en/problem/find-the-weak-connected-component-in-the-directed-graph/ 題目&#xff1a; Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its…

簡單了解tengine

Tengine是由淘寶網發起的Web服務器項目。它在Nginx的基礎上&#xff0c;針對大訪問量網站的需求&#xff0c;添加了很多高級功能和特性。最終目標是打造一個高效、穩定、安全、易用的Web平臺。1、基本的HTTP服務器特性1.處理靜態文件&#xff0c;索引文件以及自動索引&#xff…

服務器創建多個dhcp服務_如何在15分鐘內創建無服務器服務

服務器創建多個dhcp服務by Charlee Li通過李李 如何在15分鐘內創建無服務器服務 (How to create a serverless service in 15 minutes) The word “serverless” has been popular for quite a while. When Amazon released the AWS Lambda service in 2015, many tools emerg…

php snoopy視頻教程,php的Snoopy類

用了兩天這個類&#xff0c;發現很好用。獲取請求網頁里面的所有鏈接&#xff0c;直接使用fetchlinks就可以&#xff0c;獲取所有文本信息使用fetchtext(其內部還是使用正則表達式在進行處理)&#xff0c;還有其它較多的功能&#xff0c;如模擬提交表單等。使用方法&#xff1a…

網頁解析 css

網頁解析 css轉載于:https://www.cnblogs.com/guozepingboke/p/10792298.html

如何看pg數據庫版本號_查看pg數據庫版本

PostgreSQL 基本命令鏈接&#xff1a;http://blog.itpub.net/28602568/viewspace-1841163/標題&#xff1a;PostgreSQL 基本命令作者&#xff1a;&#xff4c;ōττ&#xff52;&#xff59;©版權所有[文章允許轉載,但必須以鏈接方式注明源地址,否則追究法律責任.]安裝步…

leetcode1091. 二進制矩陣中的最短路徑(bfs)

在一個 N N 的方形網格中&#xff0c;每個單元格有兩種狀態&#xff1a;空&#xff08;0&#xff09;或者阻塞&#xff08;1&#xff09;。一條從左上角到右下角、長度為 k 的暢通路徑&#xff0c;由滿足下述條件的單元格 C_1, C_2, ..., C_k 組成&#xff1a;相鄰單元格 C_i …

lock和synchronized的同步區別與選擇

區別如下&#xff1a; 1. lock是一個接口&#xff0c;而synchronized是java的一個關鍵字&#xff0c;synchronized是內置的語言實現&#xff1b;&#xff08;具體實現上的區別在《Java虛擬機》中有講解底層的CAS不同&#xff0c;以前有讀過現在又遺忘了。&#xff09; 2. syn…

首頁顯示登陸用戶名php,首頁登錄后怎么在首頁顯示用戶名以及隱藏登錄框?

該樓層疑似違規已被系統折疊 隱藏此樓查看此樓index.php&#xff1a;登錄頁面用戶名&#xff1a;密碼&#xff1a;沒有賬號&#xff1f;立即注冊——————————————————————————doaction.php&#xff1a;header("Content-type:text/html;charsetutf…

react中使用構建緩存_通過在React中構建Tic Tac Toe來學習ReasonML

react中使用構建緩存3. 7. 2018: UPDATED to ReasonReact v0.4.23. 7. 2018&#xff1a;更新為ReasonReact v0.4.2 You may have heard of Reason before. It’s a syntax on top of OCaml that compiles to both readable JavaScript code and to native and bytecode as well…