Sådan opsættes og implementeres din React-app fra bunden ved hjælp af Webpack og Babel

Så du har brugt create-react-app aka CRA i et stykke tid nu. Det er fantastisk, og du kan komme direkte til kodning. Men hvornår skal du skubbe ud fra create-react-app og begynde at konfigurere din egen React-applikation? Der vil være et tidspunkt, hvor vi er nødt til at give slip på sikkerhedskontrollen og begynde at vove os ud alene.

Denne guide dækker den mest enkle React-konfiguration, som jeg personligt har brugt til næsten alle mine React-projekter. Ved afslutningen af ​​denne tutorial får vi vores egen personlige kedelplade og lærer nogle konfigurationer af den.

Indholdsfortegnelse

  • Hvorfor oprette din egen konfiguration?
  • Konfiguration af webpack 4
  • Konfiguration af Babel 7
  • Tilføjer smukkere
  • Tilføjelse af kildekort for bedre fejllogfiler
  • Opsætning af ESLint
  • Jeg fandt fejl! Hvad skal jeg gøre?
  • Tilføjelse af CSS MINDRE processor
  • Implementering af React-appen til Netlify
  • Konklusion

Hvorfor oprette din egen konfiguration?

Der er visse grunde, der giver mening at oprette din egen React-konfiguration. Du er sandsynligvis god med React, og du vil lære at bruge værktøjer som webpack og Babel alene. Disse byggeværktøjer er kraftfulde, og hvis du har lidt ekstra tid, er det altid godt at lære om dem.

Udviklere er naturligvis nysgerrige mennesker, så hvis du føler, du gerne vil vide, hvordan ting fungerer, og hvilken del der gør hvad, så lad mig hjælpe dig med det.

Desuden er skjuling af React-konfiguration med create-react-app beregnet til udviklere, der begynder at lære React, da konfiguration ikke skal være i vejen for at komme i gang. Men når tingene bliver alvorlige, har du selvfølgelig brug for flere værktøjer til at integrere i dit projekt. Tænke over:

  • Tilføjelse af webpack-læssere til mindre, sass
  • Gør server-side gengivelse
  • Brug af nye ES-versioner
  • Tilføjelse af MobX og Redux
  • Lav din egen konfiguration bare for at lære skyld

Hvis du kigger rundt på Internettet, er der nogle hacks til at komme rundt på CRA-begrænsninger som create-react-app rewired. Men virkelig, hvorfor ikke bare lære React-konfiguration på egen hånd? Jeg hjælper dig med at komme derhen. Trin for trin.

Nu hvor du er overbevist om at lære nogle konfigurationer, lad os starte med at initialisere et React-projekt fra bunden.

Åbn kommandolinjen eller Git bash, og opret en ny mappe

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

Initialiser NPM-projektet ved at køre:

npm init -y

Installer nu reagere

npm install react react-dom

Du kan også se kildekoden på GitHub, mens du læser denne vejledning for at få forklaringer om indstillingerne.

Konfiguration af webpack 4

Vores første stop er webpakken. Det er et meget populært og kraftfuldt værktøj til at konfigurere ikke kun React, men næsten alle front-end-projekter. Kernefunktionen i webpack er, at det tager en masse JavaScript-filer, vi skriver i vores projekt, og forvandler dem til en enkelt, minificeret fil, så den bliver hurtig at servere. Fra og med webpack 4 er vi slet ikke forpligtet til at skrive en konfigurationsfil for at bruge den, men i denne vejledning skriver vi en, så vi kan forstå den bedre.

Lad os først installere noget

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

Dette vil installere:

  • webpack-modul - som inkluderer al kerne-webpack-funktionalitet
  • webpack-dev-server - denne udviklingsserver kører automatisk webpack igen, når vores fil ændres
  • webpack-cli - aktiver kørsel af webpack fra kommandolinjen

Lad os prøve at køre webpack ved at tilføje følgende script til package.json

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

Opret nu en index.htmlfil i dit rodprojekt med følgende indhold:

   My React Configuration Setup 

Opret en ny mappe med navnet, srcog opret en ny index.jsfil inde i den

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

Skriv derefter en React-komponent i filen:

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

Kør webpakken ved hjælp af npm run start... Og der udløses en fejl.

You may need an appropriate loader to handle this file type

Konfiguration af Babel 7

React-komponenten, som vi skrev ovenfor, brugte classsyntaksen, som er en funktion af ES6. Webpack har brug for Babel til at behandle ES6 til ES5-syntakser for at denne klasse skal fungere.

Lad os installere Babel i vores projekt

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

Hvorfor har vi brug for disse pakker?

  • @ babel / core er den vigtigste afhængighed, der inkluderer script til transformering af 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.