如何使用Webpack 4和Babel 7设置React

news/2024/7/1 18:27:00

介绍 (Introduction)

A common way to learn React is to use create-react-app, which is a lightweight way to bootstrap any React project. But in order to achieve a particular purpose, it is sometimes necessary to configure your application from scratch. In this tutorial, we will be setting up React using Webpack and Babel.

学习React的一种常见方法是使用create-react-app ,这是一种引导任何React项目的轻量级方法。 但是为了达到特定的目的,有时必须从头开始配置您的应用程序。 在本教程中,我们将使用Webpack和Babel设置React。

第1步-设置项目 (Step 1 — Setting Up the Project)

Before you can get started, make sure to have an installed editor and terminal on your machine. In addition, you will need an installed version of Node.js with npm. Make sure to have everything set up before you continue to read.

开始使用之前,请确保计算机上已安装编辑器和终端。 另外,您将需要安装带有npm的Node.js版本。 在继续阅读之前,请确保已完成所有设置。

Before we start writing any code, let’s create a new directory where our project will stay. In any location on your computer, run the following in your terminal:

在开始编写任何代码之前,让我们创建一个新目录,项目将保留在该目录中。 在计算机上的任何位置,在终端中运行以下命令:

  • mkdir webpack-babel-react-starter

    mkdir webpack-babel-react-starter
  • cd webpack-babel-react-starter

    cd webpack-babel-react-starter

We need to initialize our project with a package.json file, since we are going to install some packages that are vital for the setup. Run the following:

我们需要使用package.json文件初始化项目,因为我们将安装一些对于安装至关重要的软件包。 运行以下命令:

  • yarn init -y

    纱线初始化

Note: For this tutorial, we will be making use of yarn as our package manager. If you are using npm, make sure you run the corresponding command.

注意:在本教程中,我们将使用yarn作为我们的程序包管理器。 如果使用npm,请确保运行相应的命令。

第2步-设置Webpack (Step 2 — Setting up Webpack)

Webpack is one of the most popular bundlers for web development. It internally builds a dependency graph when it processes your application. This graph maps every module your project needs and generates one or more bundles. Since version 4.0.0, webpack does not require a configuration file to bundle your project; nevertheless it is configurable to better fit your needs.

Webpack是最受欢迎的Web开发捆绑软件之一。 在处理您的应用程序时,它将在内部构建依赖关系图 。 该图映射了项目所需的每个模块,并生成一个或多个捆绑包。 从4.0.0版开始,webpack不需要配置文件来捆绑项目。 不过,它可以进行配置以更好地满足您的需求。

Let’s install it by running:

让我们通过运行以下命令进行安装:

  • yarn add webpack --dev

    纱线添加webpack --dev

We also need to install the webpack CLI:

我们还需要安装webpack CLI:

  • yarn add webpack-cli --dev

    纱线添加webpack-cli --dev

After installing these two packages, you will notice a new addition to our project, the node_modules and devDependencies section in our package.json file.

安装这两个软件包后,您会在package.json文件中注意到对我们项目的新添加,即node_modulesdevDependencies部分。

Next thing to do is to add the webpack you just installed into the package.json file.

下一步是将刚安装的Webpack添加到package.json文件中。

"scripts": {
  "build": "webpack --mode production"
}

At this point you don’t need a configuration file to get started.

此时,您不需要配置文件即可开始。

步骤3 —设置Babel (Step 3 — Setting up Babel)

Modern JavaScript is written in ES6 or ES7, but not every browser understands this. Here we need babel to do the heavy lighting for us. Babel is a tool-chain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments. Checkout the Babel docs for more info about what they can do for you.

现代JavaScript是用ES6或ES7编写的,但并非每个浏览器都理解这一点。 在这里,我们需要通天塔为我们做繁重的照明工作。 Babel是一个工具链,主要用于在当前和较旧的浏览器或环境中将ECMAScript 2015+代码转换为JavaScript的向后兼容版本。 查阅Babel文档 ,了解有关他们可以为您做什么的更多信息。

React components are mostly written in ES6, with the concept of imports, class, and other ES6+ features, which older browsers do not understand. Webpack on its own does not know how to transform or transpile the ES6 code to ES5 code. But it does have the concept of loaders: a webpack loader takes something like the input and produces something else as the output.

React组件主要是用ES6编写的,具有导入,类和其他ES6 +功能的概念,这是旧版浏览器无法理解的。 Webpack本身不知道如何将ES6代码转换或转换为ES5代码。 但是它确实具有加载程序的概念:Webpack加载程序接受类似输入的内容,并产生其他内容作为输出。

For our setup, we will use babel-loader, which is a webpack loader that will transpile our ES6 code for us. Before we start using babel-loader, we need to install some packages and set up the babel preset env, which will target the particular JavaScript version we want to transpile to.

对于我们的设置,我们将使用babel-loader ,这是一个webpack加载器,将为我们转换ES6代码。 在开始使用babel-loader之前,我们需要安装一些软件包并设置babel预设env ,它将针对我们要转换为的特定JavaScript版本。

Let’s install all the dependencies:

让我们安装所有依赖项:

yarn add @babel/core @babel/preset-env @babel/preset-react babel-loader --dev

We also need to set up our Babel config file, create a new file in the root directory called .babelrc, and write the following configuration to it:

我们还需要设置Babel配置文件,在名为.babelrc的根目录中创建一个新文件,并向其中写入以下配置:

{
  "presets": ["@babel/env", "@babel/react"]
}

This configuration will ensure that Babel transpiles our React code, which is JSX and any other ES6+ code we have to ES5 code.

这种配置将确保Babel将我们的React代码(即JSX和我们必须拥有的任何其他ES6 +代码)转换为ES5代码。

Create a webpack.config.js file in the root directory and write the following configuration for it:

在根目录中创建一个webpack.config.js文件,并为其编写以下配置:

module.exports = {
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
}

For every file with a .js or .jsx extension, excluding the node_modules folder and its content, Webpack uses babel-loader to transpile the ES6 code to ES5.

对于每个带有.js.jsx扩展名的文件(不包括node_modules文件夹及其内容),Webpack使用babel-loader将ES6代码转换为ES5。

With this done, let’s head over to writing our React component.

完成之后,让我们开始编写我们的React组件。

步骤4 —设置React (Step 4 — Setting up React)

We will be creating a React component that renders a text and a button, but in order to make use of React we need to install some dependencies: react and react-dom .

我们将创建一个呈现文本和按钮的React组件,但是为了使用React,我们需要安装一些依赖项: reactreact-dom

  • yarn add react react-dom

    纱线添加ReactReact

After installing those, create a new folder in the root directory. Let’s call it src, and inside it create a index.js file.

安装这些文件后,在根目录中创建一个新文件夹。 我们将其称为src ,并在其中创建一个index.js文件。

In the index.js file, write the following code:

index.js文件中,编写以下代码:

import React from "react";
import ReactDOM from "react-dom";

const Index = () => {
  return (
    <div className="full-screen">
      <div>
        <h1>
          React Page {" "}
        </h1>
        <br />
        <a
          className="button-line"
          href="https://github.com/deityhub"
          target="_blank"
        >
          Know more
        </a>
      </div>
    </div>
  );
};

export default Index;

It’s time to test things out. Open up your terminal once again and run:

现在该测试一下了。 再次打开终端并运行:

yarn run build

You will see a dist folder created for us by Webpack, and inside it will be an index.js file, in which we have a minified version of our ES5 code. In our build script in package.json, we specified a --mode production flag after the webpack command; this makes Webpack generate a minified version of our ES5 code. To see a readable format of the transpiled code, you can swap the --mode production with --mode development.

您将看到Webpack为我们创建的dist文件夹,并且在其中将是index.js文件,在其中我们有ES5代码的缩小版本。 在package.json的构建脚本中,我们在webpack命令后指定了--mode production标记; 这使Webpack生成我们ES5代码的精简版。 要查看转译代码的可读格式,可以将--mode --mode production--mode development交换。

The output shows that our code works, but we want our transpiled code to be visible in our browser. To do this, let’s set up HTML and CSS (SCSS) to work with Webpack.

输出显示我们的代码有效,但是我们希望在我们的浏览器中看到我们已编译的代码。 为此,让我们设置HTML和CSS(SCSS)以与Webpack一起使用。

第5步—将React组件连接到DOM (Step 5 — Connecting React Component to the DOM)

We need to set up an HTML file so that our React component can be rendered on the DOM. To achieve this, we need to install the package html-webpack-plugin:

我们需要设置一个HTML文件,以便我们的React组件可以在DOM上呈现。 为此,我们需要安装html-webpack-plugin软件包:

  • yarn add html-webpack-plugin --dev

    纱线添加html-webpack-plugin --dev

Adjust your webpack.config.js file to look like this:

调整您的webpack.config.js文件,使其看起来像这样:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    })
  ]
};

We are adjusting the input and output so we have a bit more control over the naming and target of our files.

我们正在调整输入和输出,因此我们对文件的命名和目标有了更多的控制。

Next up is to create an HTML file inside the src folder; let’s call it index.html and then add the following code to it:

下一步是在src文件夹中创建一个HTML文件。 我们将其称为index.html ,然后向其中添加以下代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>React, Webpack, Babel Starter Pack</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
  </head>
  <body>
    <noscript> You need to enable JavaScript to run this app. </noscript>
    <!-- your react app will render here -->
    <div id="app"></div>
  </body>
</html>

Since we are in the src directory, let’s make some adjustments to our React component. First, create a new folder components, then inside this folder add two files app.js and app.scss. Make the following adjustments to our code.

由于我们位于src目录中,因此让我们对React组件进行一些调整。 首先,创建一个新的文件夹components ,然后在此文件夹中添加两个文件app.jsapp.scss 。 对我们的代码进行以下调整。

In ./src/index.js:

./src/index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./components/app";

ReactDOM.render(<App />, document.getElementById("app"));

In ./src/components/app.js

./src/components/app.js

import React from "react";
import "./app.scss";

const App = () => {
  return (
    <div className="full-screen">
      <div>
        <h1>
          React Page {" "}
        </h1>
        <br />
        <a
          className="button-line"
          href="https://github.com/deityhub"
          target="_blank"
        >
          Know more now
        </a>
      </div>
    </div>
  );
};

export default App;

In ./src/components/app.scss:

./src/components/app.scss

body {
  background: linear-gradient(253deg, #0cc898, #1797d2, #864fe1);
  background-size: 300% 300%;
  -webkit-animation: Background 25s ease infinite;
  -moz-animation: Background 25s ease infinite;
  animation: Background 25s ease infinite;
}

.full-screen {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
//you need to setup file-loader in webpack before you can use images
  background: url("../../assests/image/background.png");
  background-size: cover;
  background-position: center;
  width: 100%;
  height: 100%;
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: column;
  //_ works with row or column_

  flex-direction: column;
  -webkit-align-items: center;
  align-items: center;
  -webkit-justify-content: center;
  justify-content: center;
  text-align: center;
}

h1 {
  color: #fff;
  font-family: "Open Sans", sans-serif;
  font-weight: 800;
  font-size: 4em;
  letter-spacing: -2px;
  text-align: center;
  text-shadow: 1px 2px 1px rgba(0, 0, 0, 0.6);

  &:after {
    display: block;
    color: #fff;
    letter-spacing: 1px;
    font-family: "Poiret One", sans-serif;
    content: "React project powered by webpack and babel with support for sass";
    font-size: 0.4em;
    text-align: center;
  }
}

.button-line {
  font-family: "Open Sans", sans-serif;
  text-transform: uppercase;
  letter-spacing: 2px;
  background: transparent;
  border: 1px solid #fff;
  color: #fff;
  text-align: center;
  font-size: 1.4em;
  opacity: 0.8;
  padding: 20px 40px;
  text-decoration: none;
  transition: all 0.5s ease;
  margin: 0 auto;
  display: block;

  &:hover {
    opacity: 1;
    background-color: #fff;
    color: grey;
  }
}

@-webkit-keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@-moz-keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

@keyframes Background {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

We will be adding some styling in addition to the HTML and React component that we will render in the DOM. Before we run our code to test it, we need to configure our Webpack so it will know how to handle any .css or .scss file being passed through it.

除了将在DOM中呈现HTML和React组件之外,我们还将添加一些样式。 在运行代码进行测试之前,我们需要配置Webpack,以便它知道如何处理通过它的任何.css.scss文件。

  • yarn add css-loader sass-loader mini-css-extract-plugin node-sass --dev

    纱线添加css-loader sass-loader mini-css-extract-plugin节点-sass --dev

sass-loader being installed here is used by Webpack to convert our .scss to a .css file that the browser understands, and under the hood it makes use of node-sass to achieve this. Then mini-css-extract-plugin abstracts all our CSS files into a single CSS file, instead of the normal behavior that Webpack offers, which is to bundle your CSS file with the final .js output file, which then injects the CSS into your rendered HTML output when you run the code.

sass-loader这里正在安装中使用的WebPack我们转换.scss.css浏览器理解文件,引擎盖下它使用的node-sass实现这一目标。 然后mini-css-extract-plugin将我们所有CSS文件抽象为一个CSS文件,而不是Webpack提供的正常行为,后者是将CSS文件与最终的.js输出文件捆绑在一起,然后将CSS注入您的运行代码时呈现HTML输出。

Open up your Webpack config file and adjust your code to look like this:

打开您的Webpack配置文件并调整您的代码,如下所示:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /.(css|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};

Note: The order of your loaders in the Webpack config file matters, because Webpack processes the loaders from right to left. Using the test for CSS files, for example, will run sass-loader first, then css-loader, and finally MiniCssExtractPlugin.

注意: Webpack配置文件中加载程序的顺序很重要,因为Webpack从右到左处理加载程序。 例如,使用CSS文件测试将首先运行sass-loader ,然后运行css-loader ,最后运行MiniCssExtractPlugin

Now let’s install webpack dev server. This will create a development server for us and monitor our files for any changes during development.

现在,让我们安装webpack开发服务器。 这将为我们创建一个开发服务器,并在开发过程中监视我们的文件是否有任何更改。

  • yarn add webpack-dev-server --dev

    纱线添加webpack-dev-server --dev

Then open your package.json file and make the following adjustments in your scripts tag:

然后打开您的package.json文件,并在scripts标记中进行以下调整:

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

Let’s test our code by running yarn run dev.

让我们通过运行yarn run dev测试我们的代码。

You will see something like this in your browser:

您将在浏览器中看到以下内容:

步骤6 —扩展功能 (Step 6 — Extending Features)

Now, let’s add two more features to this project to demonstrate that you can extend or add more features when working on a more advanced React project than this.

现在,让我们向该项目添加两个功能,以演示在处理比此更高级的React项目时可以扩展或添加更多功能。

Open your terminal and install these packages:

打开终端并安装以下软件包:

  • yarn add file-loader @babel/plugin-proposal-class-properties --dev

    纱线添加文件加载器@ babel / plugin-proposal-class-properties --dev

file-loader will handle all the scenarios where we want to import an image or an SVG, while @babel/plugin-proposal-class-properties will handle the React class components and static class properties.

file-loader将处理我们要导入图像或SVG的所有情况,而@ babel / plugin-proposal-class-properties将处理React类组件和静态类属性。

In webpack.config.js adjust it to look like this:

webpack.config.js调整为如下所示:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
  entry: path.join(__dirname, "src", "index.js"),
  output: {
    path: path.join(__dirname, "build"),
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /.(css|scss)$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
      },
      {
        test: /.(jpg|jpeg|png|gif|mp3|svg)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[path][name]-[hash:8].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: path.join(__dirname, "src", "index.html")
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};

In .babelrc file, also adjust it to look like this:

.babelrc文件中,也将其调整为如下所示:

{
  "presets": ["@babel/env", "@babel/react"],
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

Finally, run yarn run dev to make sure everything is stile working.

最后,运行yarn run dev人员以确保一切正常。

结论 (Conclusion)

With this as a base for your React app, you can extend the configuration and build something from it. If you get stuck, check out the GitHub link to the complete code.

以此作为React应用程序的基础,您可以扩展配置并从中构建内容。 如果您遇到困难,请查看GitHub链接以获取完整代码。

翻译自: https://www.digitalocean.com/community/tutorials/settingup-reactjs-using-webpack-4-and-babel-7-the-definitive-guide


http://www.niftyadmin.cn/n/3649483.html

相关文章

两种方法为WordPress添加用户自定义头像功能

一般情况下&#xff0c;WordPress默认都是使用Gravatar头像&#xff0c;如果用户没有注册过Gravatar头像&#xff0c;那就使用网站设置的默认头像&#xff0c;这样用户体验不是很好&#xff1b;再则&#xff0c;如果直接调用远程Gravatar头像&#xff0c;还会影响网站的加载速度…

Android 之 Binder与进程间通信

Binder机制是android中实现的进程间通信的架构&#xff0c;它采用的是c/s架构&#xff0c;client通过代理完成对server的调用。 ServiceManager 既然这里提到了server&#xff0c;那么我们有必要先了解下在android中是怎么来管理server的。先来看一个重要的Native进程&#xff…

如何在Ubuntu 18.04上使用Ansible安装和设置Apache

介绍 (Introduction) Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of aut…

最新版Microsoft Edge——Chromium内核

2015年4月30日&#xff0c;微软在旧金山举行的Build 2015开发者大会上宣布&#xff0c;其最新操作系统——Windows 10内置代号为“Project Spartan”的新浏览器被正式命名为“Microsoft Edge”&#xff0c;其内置于Windows 10版本中。 2018年3月&#xff0c;微软宣布登陆iPad和…

优秀的前端JS框架——AngularJS的安装

AngularJS 诞生于2009年&#xff0c;由Misko Hevery 等人创建&#xff0c;后为Google所收购。是一款优秀的前端JS框架&#xff0c;已经被用于Google的多款产品当中。AngularJS有着诸多特性&#xff0c;最为核心的是&#xff1a;MVC(Model–view–controller)、模块化、自动化双…

Android中的Parcel机制 实现Bundle传递对象

Android中的Parcel机制 实现了Bundle传递对象 使用Bundle传递对象&#xff0c;首先要将其序列化&#xff0c;但是&#xff0c;在Android中要使用这种传递对象的方式需要用到Android Parcel机制&#xff0c;即&#xff0c;Android实现的轻量级的高效的对象序列化和反序列…

Picasso的封装(一)

public class PicassoUtils {//加载本地图片public static void setImg(Context context, int resId, ImageView imgView){Picasso.with(context).load(resId).config(Bitmap.Config.RGB_565)//8位RGB位图.fit().into(imgView);}//按照一定的宽高加载本地图片&#xff0c;带有加…

如何在Ubuntu 18.04上使用Ansible安装和设置Docker

介绍 (Introduction) Server automation now plays an essential role in systems administration, due to the disposable nature of modern application environments. Configuration management tools such as Ansible are typically used to streamline the process of aut…