Tehát egy ideje használja a create-reagál-alkalmazást, más néven CRA-t. Nagyszerű, és rögtön eljuthat a kódoláshoz. De mikor kell eltávolítania a create-react-app alkalmazásból, és el kell kezdenie a saját React alkalmazás konfigurálását? Eljön egy idő, amikor el kell engednünk a biztonsági ellenőrzést, és egyedül kell elindulnunk.
Ez az útmutató a legegyszerűbb React konfigurációt ismerteti, amelyet személyesen használtam szinte az összes React projektemhez. Ennek az oktatóanyagnak a végére lesz egy saját személyes kazánlemezünk, és megtanulunk belőle néhány konfigurációt.
Tartalomjegyzék
- Miért kell saját konfigurációt létrehozni?
- A webcsomag konfigurálása 4
- Bábel beállítása 7
- Szebb hozzáadása
- Forrástérkép hozzáadása a jobb hibanaplók érdekében
- Az ESLint beállítása
- Hibákat találtam! Mit tegyek?
- CSS LESS processzor hozzáadása
- A React alkalmazás telepítése a Netlify-ra
- Következtetés
Miért kell saját konfigurációt létrehozni?
Bizonyos okok miatt van értelme a saját React konfiguráció létrehozásának. Valószínűleg jól állsz a React-szel, és szeretnéd megtanulni, hogyan kell egyedül használni az olyan eszközöket, mint a webpack és a Babel. Ezek a buildeszközök nagy teljesítményűek, és ha van még némi extra ideje, mindig jó megismerni őket.
A fejlesztők természetesen kíváncsi emberek, ezért ha úgy érzi, szeretné tudni, hogyan működnek a dolgok, és melyik rész mit csinál, akkor hadd segítsek ebben.
Ezenkívül a React konfigurációjának elrejtése a create-react-app segítségével a fejlesztők számára, akik elkezdik megtanulni a React-et, mivel a konfiguráció nem akadályozhatja az indítást. De ha a dolgok komolyra fordulnak, akkor természetesen több eszközre van szüksége a projektbe történő integráláshoz. Gondol róla:
- Webpack rakodók hozzáadása kevesebbért, sass
- Szerveroldali renderelés
- Új ES verziók használata
- MobX és Redux hozzáadása
- Saját konfiguráció készítése csak a tanulás kedvéért
Ha körülnéz az interneten, van néhány feltörés a hitelminősítő intézetek korlátozásainak kikerüléséhez, például a létrehozás-reagálás-alkalmazás újravezetése. De valójában miért nem tanulja meg egyedül a React konfigurációt? Segítek eljutni oda. Lépésről lépésre.
Most, hogy meg van győződve arról, hogy megtanul valamilyen konfigurációt, kezdjük azzal, hogy a React projektet nulláról inicializáljuk.
Nyissa meg a parancssort vagy a Git bash-t, és hozzon létre egy új könyvtárat
mkdir react-config-tutorial && cd react-config-tutorial
Az NPM projekt inicializálása a következő futtatással:
npm init -y
Most telepítse a reakciót
npm install react react-dom
Ezenkívül megtekintheti a forráskódot a GitHubon, miközben elolvassa ezt az oktatóanyagot, és elmagyarázza a beállításokat.
A webcsomag konfigurálása 4
Első állomásunk a webpack lesz. Ez egy nagyon népszerű és hatékony eszköz nemcsak a React, hanem szinte az összes front-end projekt konfigurálására. A webpack alapvető funkciója, hogy egy csomó JavaScript-fájlt vesz igénybe, amelyet a projektünkbe írunk, és egyetlen, tömörített fájlokká alakítja őket, így gyors lesz a kiszolgálás. A 4-es webcsomagtól kezdve egyáltalán nem kell konfigurációs fájlt írnunk a használatához, de ebben az oktatóanyagban írunk egyet, hogy jobban megértsük.
Először végezzünk egy kis telepítést
npm install --save-dev webpack webpack-dev-server webpack-cli
Ez telepíti:
- webpack modul - amely magában foglalja az összes alapvető webpack funkciót
- webpack-dev-server - ez a fejlesztőkiszolgáló automatikusan újraindítja a webcsomagot, amikor a fájlunk megváltozik
- webpack-cli - engedélyezze a webpack futtatását a parancssorból
Próbáljuk meg futtatni a webpack csomagot a következő szkript hozzáadásával package.json
"scripts": { "start": "webpack-dev-server --mode development", },
Most hozzon létre egy index.html
fájlt a root projektben a következő tartalommal:
My React Configuration Setup
Hozzon létre egy új könyvtárat, amelynek neve, src
és azon belül hozzon létre egy új index.js
fájlt
mkdir src && cd src && touch index.js
Ezután írjon egy React összetevőt a fájlba:
import React from "react"; import ReactDOM from "react-dom"; class Welcome extends React.Component { render() { return Hello World from React boilerplate
; } } ReactDOM.render(, document.getElementById("root"));
Futtassa a webcsomagot a következővel: npm run start
… És hiba lép fel.
You may need an appropriate loader to handle this file type
Bábel beállítása 7
A fent írt React komponens a class
szintaxist használta , ami az ES6 egyik jellemzője. A Webpack-nak szüksége van a Babelre az ES6 ES5 szintaxisokká történő feldolgozásához, hogy ez az osztály működhessen.
Telepítsük a Bábelt a projektünkbe
npm install --save-dev @babel/core @babel/preset-env \@babel/preset-react babel-loader
Miért van szükségünk ezekre a csomagokra?
- A @ babel / core a fő függőség, amely tartalmazza a babel transzformációs szkriptet.
- @babel/preset-env is the default Babel preset used to transform ES6+ into valid ES5 code. Optionally configures browser polyfills automatically.
- @babel/preset-react is used for transforming JSX and React class syntax into valid JavaScript code.
- babel-loader is a webpack loader that hooks Babel into webpack. We will run Babel from webpack with this package.
To hook Babel into our webpack, we need to create a webpack configuration file. Let’s write a webpack.config.js
file:
module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './dist', }, module: { rules: [ test: /\.(js ] }, };
This webpack config is basically saying that the entry
point of our application is from index.js, so pull everything that’s needed by that file, then put the output
of the bundling process into the dist directory, named bundle.js. Oh, if we’re running on webpack-dev-server
, then tell the server to serve content from contentBase
config, which is the same directory this config is in. For all .js or .jsx files, use babel-loader
to transpile all of them.
In order to use Babel presets, create a new .babelrc
file
touch .babelrc
Write the following content:
{ "presets": [ "@babel/preset-env", "@babel/preset-react" ] }
Now run npm run start
again. This time it will work.
Adding Prettier
To further speed up development, let’s make our code formatter using Prettier. Install the dependency locally and use the — save-exact argument since Prettier introduces stylistic changes in patch releases.
npm install --save-dev --save-exact prettier
Now we need to write the .prettierrc
configuration file:
{ "semi": true, "singleQuote": true, "trailingComma": "es5" }
The rules means that we want to add semicolon for the end of every statement, use a single quote whenever appropriate and put trailing commas for multi-line ES5 code like objects or arrays.
You can run Prettier from the command line with:
npx prettier --write "src/**/*.js"
Or add a new script to our package.json
file:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development", "format": "prettier --write \"src/**/*.js\"" },
Now we can run Prettier using npm run format
.
Additionally, if you’re using VSCode for development, you can install the Prettier extension and run it every time you save your changes by adding this setting:
"editor.formatOnSave": true
Adding source map for better error logs
Since webpack bundles the code, source maps are mandatory to get a reference to the original file that raised an error. For example, if you bundle three source files (a.js
, b.js
, and c.js
) into one bundle (bundler.js
) and one of the source files contains an error, the stack trace will simply point to bundle.js
. This is problematic as you probably want to know exactly if it’s the a, b, or c file that is causing an error.
You can tell webpack to generate source maps using the devtool property of the configuration:
module.exports = { devtool: 'inline-source-map', // … the rest of the config };
Although it will cause a slower build, it has no effect on production. Sourcemaps are only downloaded if you open the browser DevTools.
Setting up ESLint
Linter is a program that checks our code for any error or warning that can cause bugs. JavaScript’s linter, ESLint, is a very flexible linting program that can be configured in many ways.
But before we get ahead, let’s install ESLint into our project:
npm --save-dev install eslint eslint-loader babel-eslint eslint-config-react eslint-plugin-react
- eslint is the core dependency for all functionalities, while eslint-loader enables us to hook eslint into webpack. Now since React used ES6+ syntax, we will add babel-eslint — a parser that enables eslint to lint all valid ES6+ codes.
- eslint-config-react and eslint-plugin-react are both used to enable ESLint to use pre-made rules.
Since we already have webpack, we only have to modify the config slightly:
module.exports = { // modify the module module: { rules: [jsx)$/, exclude: /node_modules/, use: ['babel-loader', 'eslint-loader'] // include eslint-loader ] }, };
Then create an eslint config file named .eslintrc
with this content:
{ "parser": "babel-eslint", "extends": "react", "env": { "browser": true, "node": true }, "settings": { "react": { "version": "detect" } } }
The config is basically saying, “Hey ESLint, please parse the code using babel-eslint
before you check it, and when you’re checking it, please check if all the rules from our React rules config is passed. Take global variables from the environment of browser and node. Oh, and if it’s React code, take the version from the module itself. That way the user won’t have to specify the version manually.”
Rather than specifying our own rules manually, we simply extend react
rules which were made available by eslint-config-react
and eslint-plugin-react
.
I found errors! What do I do?
Unfortunately the only way to really figure out how to fix ESLint errors is by looking at the documentation for rules. There’s a quick way to fix ESLint errors by using eslint--fix
, and it’s actually good for a quick fix. Let’s add a script on our package.json
file:
"scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "webpack-dev-server --mode development", "format": "prettier --write \"src/**/*.js\"", "eslint-fix": “eslint --fix \"src/**/*.js\"", // the eslint script "build": "webpack --mode production" },
Then run it with npm run eslint-fix
. Don’t worry if you’re still fuzzy about ESLint for now. You will learn more about ESLint as you use it.
Adding CSS LESS processor
In order to add the LESS processor into our React application, we will require both less and loader packages from webpack:
npm install --save-dev less less-loader css-loader style-loader
less-loader
will compile our less file into css, while css-loader
will resolve css syntax like import
or url()
. The style-loader
will get our compiled css and load it up into
Now let’s add some css files to create a new style directory in
src/style
cd src && mkdir style && touch header.less && touch main.less
header.less
content:
.header { background-color: #3d3d; }
main.less
content:
@import "header.less"; @color: #f5adad; body { background-color: @color; }
Now import our
main.less
file from index.js
:
import "./style/main.less";
Then update our webpack configuration
module
property:
module: { rules: [ test: /\.(js, { test: /\.less$/, use: [ 'style-loader', 'css-loader', 'less-loader', ], }, ] },
Run the start script and we’re good to go!
Deploying React app to Netlify
All applications need to be deployed for the last step, and for React applications, deployment is very easy.
First, let’s change the build output and development
contentBase
from dist
to build
in our Webpack config.
module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'), // change this publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: "./build", }, //…
Now let’s install a new Webpack plugin named HtmlWebpackPlugin
npm install html-webpack-plugin -D
This plugin will generate
index.html
file in the same directory where our bundle.js
is created by Webpack. In this case, the build
directory.
Why do we need this plugin? Because Netlify requires a single directory to be made the root directory, so we can’t use
index.html
in our root directory using Netlify. You need to update your webpack config to look like this:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: //… output: { //… }, devServer: { contentBase: "./build", }, module: { //… }, plugins: [ new HtmlWebpackPlugin({ template: path.resolve('./index.html'), }), ] };
And please remove the
script
tag from your index.html
:
My React Configuration Setup My React Configuration Setup
Now you can test the config with
npm run build
command. Once it’s done, push your boilerplate into a GitHub repo. It’s time to deploy our application!
Now let’s register a Netlify account. If you haven’t heard of Netlify before, it’s an amazing static site hosting that provides all the tools you need to deploy a static site for free. What’s a static site? It’s a website created from a collection of static HTML pages, without any backend. Our React boilerplate as it is now counts as a static site, because we have no backend configured and its just HTML and JavaScript.
After sign up, select new site from Git and Choose GitHub as your Git provider:

You need to grant permissions for Netlify, and then select your React boilerplate repo.

Now you need to enter the build command and publishing directory. As you can see, this is why we need HtmlWebpackPlugin, because we need to serve everything from one directory only. Rather than manually updating our root index.html
file for changes, we just generate it using the plugin.

Make sure you have the same command as the screenshot above, or your app might not run.

Once the deploys status turns to published
(number 2 above), you can go to the random site name Netlify has assigned for your application (number 1).
Your React application is deployed. Awesome!
Conclusion
You’ve just created your very own React project boilerplate and deploy it live to Netlify. Congratulations! Granted, I didn’t go very deep on webpack configurations, because this boilerplate is meant to be a generic starter. In some cases where we need advanced features like server side rendering, we need to tweak the configuration again.
But relax! You’ve come this far, which means you already understand what webpack, Babel, Prettier and ESLint do. Webpack has many powerful loaders that can help you with many cases you’ll frequently counter when building a web application.
Also, I’m currently writing a book to help software developers learn about React, so you might wanna check it out!

You can read more of my React tutorials at sebhastian.com.