Kako postaviti i implementirati svoju React aplikaciju od nule koristeći Webpack i Babel

Dakle, već neko vrijeme upotrebljavate aplikaciju za reagiranje aka CRA. Super je i možete prijeći izravno na kodiranje. Ali kada trebate izbaciti iz create-response-app i započeti konfiguriranje vlastite React aplikacije? Doći će vrijeme kada ćemo morati otpustiti sigurnosnu provjeru i početi se sami odvažiti.

Ovaj će vodič pokrivati ​​najjednostavniju React konfiguraciju koju sam osobno koristio za gotovo sve svoje React projekte. Na kraju ovog vodiča imat ćemo vlastiti osobni obrazac i na njemu ćemo naučiti neke konfiguracije.

Sadržaj

  • Zašto stvoriti vlastitu konfiguraciju?
  • Konfiguriranje webpacka 4
  • Konfiguriranje Babel 7
  • Dodavanje ljepšeg
  • Dodavanje mape izvora za bolje zapisnike pogrešaka
  • Postavljanje ESLinta
  • Pronašao sam pogreške! Što da radim?
  • Dodavanje CSS MANJE procesora
  • Uvođenje aplikacije React u Netlify
  • Zaključak

Zašto stvoriti vlastitu konfiguraciju?

Postoje određeni razlozi zbog kojih stvaranje vlastite React konfiguracije ima smisla. Vjerojatno ste dobri s Reactom i želite naučiti kako samostalno koristiti alate kao što su webpack i Babel. Ovi su alati za izradu moćni i ako imate malo više vremena, uvijek je dobro naučiti o njima.

Programeri su prirodno znatiželjni ljudi, pa ako smatrate da biste željeli znati kako stvari funkcioniraju i koji dio što radi, dopustite mi da vam pomognem s tim.

Nadalje, skrivanje React konfiguracije pomoću create-React-app namijenjeno je programerima koji počinju učiti React, jer konfiguracija ne bi trebala smetati početku. Ali kad stvari postanu ozbiljne, naravno, trebate više alata za integriranje u svoj projekt. Misli o:

  • Dodavanje učitavača webpacka za manje, sass
  • Vrši se prikazivanje na strani poslužitelja
  • Korištenje novih ES verzija
  • Dodavanje MobX-a i Redux-a
  • Izrada vlastite konfiguracije samo radi učenja

Ako pogledate po Internetu, postoje neki hakovi kako biste zaobišli ograničenja CRA-a, poput preoblikovane aplikacije za reagiranje. Ali stvarno, zašto jednostavno ne naučiti React konfiguraciju sami? Pomoći ću vam da stignete tamo. Korak po korak.

Sad kad ste uvjereni da ste naučili neku konfiguraciju, krenimo s inicijalizacijom React projekta od nule.

Otvorite naredbeni redak ili Git bash i stvorite novi direktorij

mkdir react-config-tutorial && cd react-config-tutorial

Inicijalizirajte NPM projekt izvođenjem:

npm init -y

Sada instalirajte reagirajte

npm install react react-dom

Također, izvorni kod možete pogledati na GitHubu dok čitate ovaj vodič za objašnjenja o postavkama.

Konfiguriranje webpacka 4

Naša prva stanica bit će webpack. To je vrlo popularan i moćan alat za konfiguriranje ne samo React, već i gotovo svih front-end projekata. Osnovna funkcija webpack-a je ta da uzima hrpu JavaScript datoteka koje napišemo u našem projektu i pretvara ih u jednu, umanjenu datoteku, tako da će se brzo poslužiti. Polazeći od webpack-a 4, od nas uopće nije potrebno da napišemo konfiguracijsku datoteku da bismo je koristili, ali u ovom uputstvu ćemo napisati jednu kako bismo je bolje razumjeli.

Prvo, napravimo instalaciju

npm install --save-dev webpack webpack-dev-server webpack-cli

Ovo će instalirati:

  • webpack modul - koji uključuje sve osnovne funkcionalnosti webpack-a
  • webpack-dev-server - ovaj razvojni poslužitelj automatski ponovno pokreće webpack kada se naša datoteka promijeni
  • webpack-cli - omogućiti pokretanje webpacka iz naredbenog retka

Pokušajmo pokrenuti webpack dodavanjem sljedeće skripte u package.json

"scripts": { "start": "webpack-dev-server --mode development", },

Sada stvorite index.htmldatoteku u svom root projektu sa sljedećim sadržajem:

   My React Configuration Setup 

Stvorite novi direktorij s imenom srci u njemu stvorite novu index.jsdatoteku

mkdir src && cd src && touch index.js

Zatim u datoteku napišite komponentu React:

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"));

Pokrenite webpack koristeći npm run start... I pokrenut će se pogreška.

You may need an appropriate loader to handle this file type

Konfiguriranje Babel 7

Komponenta React koju smo gore napisali koristi classsintaksu, što je značajka ES6. Webpacku je potreban Babel za obradu ES6 u ES5 sintakse kako bi ova klasa mogla funkcionirati.

Ugradimo Babel u naš projekt

npm install --save-dev @babel/core @babel/preset-env \@babel/preset-react babel-loader

Zašto su nam potrebni ovi paketi?

  • @ babel / core je glavna ovisnost koja uključuje skriptu pretvorbe babel.
  • @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 le> tag in our bundle. This is great for development because it lets us update our style on the fly, without needing to refresh the browser.

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.