Table of Contents
Before starting
The final effect
Initialization
Webpack
In order to be able to use
React
CSS
图片
总结
Home Web Front-end JS Tutorial Knowledge about Webpack, Babel and React

Knowledge about Webpack, Babel and React

Oct 25, 2017 pm 02:14 PM
babel react webpack

Before starting

Before writing the article, I assume that everyone already has JavaScript, Node package management tool, Linux terminal operation These basic skills, next, I will guide you step by step to build a React project from scratch

The final effect

We will use Webpack To build a React application with Babel, our purpose is very clear, which is to better understand and master the use of these tools

We create The application should not only be minimum, but also follow best practices to consolidate the foundation for students who are not particularly skilled

Initialization

Create your project and add your configuration file package.json

mkdir webpack-babel-react-revisited
cd webpack-babel-react-revisited

yarn init
Copy after login

Webpack

We first install Webpack, it is currently very The popular module packager, which packages each module included in the application into a small number of chunks so that these codes are loaded from the server into the browser

yarn add webpack --dev
Copy after login

Next, we start writing some modules. We save the source file app.js to the src directory

/** app.js */

console.log('Hello from 枫上雾棋!');
Copy after login

Then, we run Webpack

./node_modules/webpack/bin/webpack.js ./src/app.js --output-filename ./dist/app.bundle.js
Copy after login

If you open the generated app.bundle.js, you will find that the above is the module processing code of webpack, and the following is the console.log## we wrote

#This instruction is to use our

app.js as the entry file of Webpack, and output the result to the dist file folder, the instructions are a bit lengthy. In actual development, we use the webpack configuration file instead. In order to make the document structure look clearer, refer to the Directory as follows

├── config
│   ├── paths.js
│   ├── webpack.config.prod.js
├── src
│   ├── app.js
├── package.json
Copy after login

The following is a reference

Configuration

paths.js

const path = require('path');
const fs = require('fs');

const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

module.exports = {
  appDist: resolveApp('dist'),
  appSrc: resolveApp('src'),
};
Copy after login

This file is not necessary, but as the project grows, its significance becomes instantaneous Out

webpack.config.prod.js

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

const paths = require('./paths');

const plugins = [
  new HtmlWebpackPlugin({
    title: 'webpack babel react revisited',
    filename: path.join(paths.appDist, 'index.html'),
  }),
];

const config = {
  entry: {
    app: path.join(paths.appSrc, 'app'),
  },
  output: {
    path: paths.appDist,
    filename: 'assets/js/[name].js',
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins,
};

module.exports = config;
Copy after login

Here we also added a html-webpack-plugin, which simplifies our

HTML We won’t go into details about the creation and installation of files here. If you don’t know yet, you can click on the link to view

Among them, we also use a

syntax sugar, so that when we import .js, .jsx, there is no need to specify the extension

Next, we specify the configuration file and run it again

Webpack

./node_modules/webpack/bin/webpack.js --config config/webpack.config.prod.js
Copy after login

found that in addition to achieving the above effect, it also automatically generated an

index.html for us. We can click on this html to view the effect in the console. Compared with Isn’t the above a lot more convenient?

Of course, in the end we definitely don’t use this method to

build. Open package.json and add the following script Command , and then execute yarn build, do you feel nice instantly?

"scripts": {
  "clean": "rimraf dist *.log .DS_Store",
  "build": "yarn run clean && webpack --config config/webpack.config.prod.js --progress"
}
Copy after login

Webpack dev server

In addition,

Webpack provides us with a dev server, which also supports module hot replacement

First, install

webpack-dev- server

yarn add --dev webpack-dev-server
Copy after login

Add the configuration file

webpack.config.dev.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OpenBrowserPlugin = require('open-browser-webpack-plugin');

const paths = require('./paths');

const hostname = process.env.HOST || 'localhost';
const port = process.env.PORT || 3000;

const plugins = [
  new HtmlWebpackPlugin({
    title: 'webpack babel react revisited',
    filename: path.join(paths.appDist, 'index.html'),
  }),
  new OpenBrowserPlugin({ url: `http://${hostname}:${port}` }),
];

const config = {
  entry: {
    app: path.join(paths.appSrc, 'app'),
  },
  output: {
    path: paths.appDist,
    filename: 'assets/js/[name].js',
  },
    resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins,
  devServer: {
    contentBase: paths.appDist,
    compress: true,
    port,
  },
};

module.exports = config;
Copy after login
in the config

directory. On the basis of config.prod.js

, we added the open-browser-webpack-plugin plug-in and the devServer configuration. The open-browser-webpack-plugin plug-in, as the name suggests, will Help us automatically open the dev server and finally return the address to usUpdate

package.json

<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&quot;scripts&quot;: { &quot;clean&quot;: &quot;rimraf dist *.log .DS_Store&quot;, &quot;webpack:dev&quot;: &quot;NODE_ENV=development webpack-dev-server --config config/webpack.config.dev.js --progress&quot;, &quot;webpack:prod&quot;: &quot;NODE_ENV=production webpack --config config/webpack.config.prod.js --progress&quot;, &quot;start&quot;: &quot;yarn run clean &amp;&amp; yarn run webpack:dev&quot;, &quot;build&quot;: &quot;yarn run clean &amp;&amp; yarn run webpack:prod&quot; }</pre><div class="contentsignin">Copy after login</div></div>Now, we can do it in the following way Starting

yarn start
Copy after login

After starting, is there a moment when you feel great

Babel

In order to be able to use

ES6

and higher, we need a Conversion compiler, we choose Babel, which can convert ES6 into code that can run in the browser. In addition, it also has built-in React JSX extension, it can be said that its emergence has promoted the development of JavaSciptAll, we install the following dependency packages

yarn add --dev babel-loader babel-core babel-preset-env babel-preset-react
Copy after login

Create

Babel

Default configuration file.babelrc<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>{ &quot;presets&quot;: [&quot;env&quot;, &quot;react&quot;] }</pre><div class="contentsignin">Copy after login</div></div>This tells

Babel

to use the two presets## we just installed #Next, update the webpack

configuration file

config.module = {
  rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: [&#39;babel-loader&#39;],
    },
  ],
}
Copy after login
After the update, although we can’t see any changes, in fact we can use ES6

React

Finally, let’s add

React

, which may also be the reason why you are reading this article

First, let’s install it first

yarn add react react-dom
Copy after login

Replace

console.log

import React, { Component } from &#39;react&#39;;
import { render } from &#39;react-dom&#39;;

export default class Hello extends Component {
  render() {
    return <h1>Hello from 枫上雾棋!</h1>;
  }
}

render(<Hello />, document.getElementById(&#39;app&#39;));
Copy after login
with the following code because we need to add

, so we need Modify the configuration of

html-webpack-plugin

new HtmlWebpackPlugin({
  template: path.join(paths.appSrc, &#39;index.html&#39;),
}),
Copy after login
Referencetemplate

as follows

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>webpack babel react revisited</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <p id="app"></p>
  </body>
</html>
Copy after login
The next step is to witness the miracle

重新启动服务,你有没有发现搭建一个 React 应用程序就这么简单

接下来,大家就可以 自行探索,添加更多的东西来适应自身应用程序的需要

下面再补充一下如何添加 CSS图片

CSS

每个 web 应用程序都离不开 CSS,我们在 src 目录中创建 style.css

body,
html,
#app {
  margin: 0;
  width: 100%;
  height: 100%;
}

#app {
  padding: 30px;
  font-family: &#39;微软雅黑&#39;;
}
Copy after login

将其添加到应用程序中我们需要使用 css-loader

如果想将 css 注入 style 标签中,我们还需要 style-loader,通常,是将这两个结合使用

我们使用 extract-text-webpack-plugin 将其解压到外部

为此,我们首先安装

yarn add --dev css-loader style-loader extract-text-webpack-plugin
Copy after login

然后在 app.js 中导入 style.css

import &#39;./style.css&#39;;
Copy after login

最后更新 webpack 配置文件

config.module = {
  rules: [
    {
      test: /\.css$/,
      use: ExtractTextPlugin.extract({
        fallback: &#39;style-loader&#39;,
        use: &#39;css-loader&#39;,
      }),
    },
  ],
}

config.plugins.push([
  new ExtractTextPlugin("styles.css"),
])
Copy after login

看起来稍显复杂,但是大功告成,为了更好地使用它,我们都得经历这个过程

重新启动服务,你会发现你的 dist 目录中多了一个 styles.css

图片

最后我们增加 file-loader 来处理我们引入的图片等文件

首先,安装 file-loader

yarn add --dev file-loader
Copy after login

我们在 src/images 中放入一张图片,在 app.js 中导入

import avatar from &#39;./images/avatar.jpg&#39;;

export default class Hello extends Component {
  render() {
    return (
      <p>
        <img src={avatar} alt="avatar" style={{ width: 400, height: 250 }} />
      </p>
    );
  }
}
Copy after login

更新 webpack 配置文件

config.module = {
  rules: [
    {
      test: /\.(png|jpg|gif)$/,
      use: [
        {
          loader: &#39;file-loader&#39;,
          options: {
            name: &#39;[name].[ext]&#39;,
            outputPath: &#39;assets/images/&#39;,
          },
        },
      ],
    },
  ],
}
Copy after login

重启服务,哈哈

总结

如果有什么问题,可以查看 webpack-babel-react-revisited 仓库

现在,大家对搭建 React 应用程序是不是感觉轻松了很多,但 React 整个技术栈并不止包括这些,还有 ReduxReact Router单元测试代码校验 等内容,关于 React 其他内容,欢迎查看日志其他文章


The above is the detailed content of Knowledge about Webpack, Babel and React. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

How to package and deploy front-end applications using React and Docker How to package and deploy front-end applications using React and Docker Sep 26, 2023 pm 03:14 PM

How to use React and Docker to package and deploy front-end applications. Packaging and deployment of front-end applications is a very important part of project development. With the rapid development of modern front-end frameworks, React has become the first choice for many front-end developers. As a containerization solution, Docker can greatly simplify the application deployment process. This article will introduce how to use React and Docker to package and deploy front-end applications, and provide specific code examples. 1. Preparation Before starting, we need to install

How to build real-time data processing applications using React and Apache Kafka How to build real-time data processing applications using React and Apache Kafka Sep 27, 2023 pm 02:25 PM

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

See all articles