Home > Web Front-end > JS Tutorial > body text

How to build a webpack+react development environment

php中世界最好的语言
Release: 2018-05-28 15:41:18
Original
1534 people have browsed it

This time I will show you how to build a webpack react development environment and what are the precautions for building a webpack react development environment. The following is a practical case, let's take a look.

The environment mainly depends on the version

  1. webpack@4.8.1

  2. webpack-cli@2.1 .3

  3. ##webpack-dev-server@3.1.4
  4. react@16.3.2
  5. babel-core@6.26.3
  6. babel-preset-env@1.6.1
  7. ##bable-preset-react@6.24. 1
  8. webpack installation and configuration

1. Getting started

Create a new project directory, initialize npm, and create a new development source directory

mkdir webpack-react && cd webpack-react
npm init -y
mkdir src
Copy after login
2.webpack-cli

Starting from version 4.x, webpack and webpack-cli need to be installed at the same time (this tool is used to run webpack in the command line).

npm install webpack webpack-cli --save-dev
Copy after login
3.wepback

Configuration file

Create a new webpack.config.js file in the project root directory. This file is the core file for running webpack.

webpack.config.js basic configuration

// webpack.config.js
const path = require('path');
module.exports = {
  entry: './src/index.js',              // 入口文件
  output: {                       // webpack打包后出口文件
    filename: 'app.js',               // 打包后js文件名称
    path: path.resolve(dirname, 'dist')  // 打包后自动输出目录
  }
}
Copy after login
package.json file scripts configuration

"scripts": {
  "build": "webpack"
}
Copy after login
At this time, run npm run build on the command line to execute webpack, webpack It will automatically find the webpack.config.js file in the project root directory and perform packaging.

npm run build
// webpack打包后的项目
├── dist
│  └── app.js       // 打包后的app.js
├── package.json
├── src
│  └── index.js      // 源目录入口文件
└── webpack.config.js
Copy after login

webpack.config.js module related configuration

webpack treats all files as modules, pictures, css files, fonts and other static resources will be packaged into js files. Therefore, the loader file will be needed. More Loaders can query the URL. Next, we install some necessary Loader files.

npm install style-loader css-loader url-loader --save-dev
Copy after login
Webpack.config.js adds the module module

module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 }
}
Copy after login
After introducing the loader, you can import the css file or other static resources you want to introduce in your src/index.js file.

cd src && touch main.css
Copy after login
src/index.js file introduces css

import "./main.css";
Copy after login

webpack.config.js plugins configuration

Main js files and static files can be After successfully packaging it into a js file, we need to put the js file into an html file. The webpack plug-in ***html-webpack-plugin*** does this. It can automatically generate an html file and put us Put the packaged js files into html.

npm install html-webpack-plugin --save-dev
Copy after login
webpack.config.js Configure plugins

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // 引入插件
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({title: 'production'}) // 配置plugin
 ]
};
Copy after login
After executing npm run build, we can see that there is an additional index.html file in the dist directory.

<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <title>name</title>
 </head>
 <body>
 // 打包后的app.js已经被自动插入了html文件
 <script type="text/javascript" src="app.js"></script></body>
</html>
Copy after login
At this point, the simplest and most basic requirements of webpack have been configured. At this time, the project structure is:

├── dist            // 生产目录
│  ├── app.js
│  └── index.html
├── package.json
├── src            // 源目录
│  ├── index.js
│  └── main.css
└── webpack.config.js
Copy after login

React's webpack configuration

Install react

npm install react react-dom --save
Copy after login
Install react, wepback conversion dependency

React components are composed of JSX. Browsers cannot recognize JSX and need to be converted by Babel.

babel-croe is the babel core file
  1. babel-preset-env escapes ES6 to ES5
  2. babel-preset-react Escape JSX to js
  3. babel-loader webpack’s babe conversion
  4. Copy Code
The code is as follows:

npm install babel-core babel-preset-env babel-preset-react babel-loader --save-dev

##.babelrc configuration file

Create a new .babelrc file in the project root directory. This file is the core configuration of babel. Babel will automatically recognize it in the project root directory.

// .babelrc
{
 "presets": ["env", "react"]
}
Copy after login
webpack babel-loader configuration

// 在webpack.config.js 的modules.rules中加入此配置
{
 test: /\.(js|jsx)$/,
 exclude: /node_modules/,
 use: {
 loader: 'babel-loader'
 }
}
Copy after login

html-webpack-plugin template configuration

We know that react needs to get a root element of the page, and then render It will take effect. We can create a new html file and let the html-webpack-plugin plug-in package based on this file. So we create a new html file in the root directory and use this file as a template.

// index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>
    // react需要的渲染根元素
 <p id="root"></p>
</body>
</html>
Copy after login

At this time webpack.config.js configuration:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: {
   loader: 'babel-loader'
  }
  },
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({
  title: 'production',
  template: './index.html'  // 模板文件位置
 }) 
 ]
};
Copy after login

Write React and run webpack

// src/index.js
import React from 'react';
import ReactDom from 'react-dom';
import './main.css'
ReactDom.render(
 <h1>hello world</h1>,
 document.getElementById('root')
);
Copy after login

运行npm run build,生成dist目录,打开dist目录中的index.html文件,可以发现浏览器已正常渲染"hello world"。

dev环境热更新配置

react的wepack完成以后,是不是发现每修改一次代码,想看到效果,得重新打包一次才行。webpack-dev-server配置可以帮助我们实现热更新,在开发环境解放我们的生产力。

安装webpack-dev-server

npm install webpack-dev-server --save-dev
Copy after login

webpack.config.js 配置

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
 entry: './src/index.js',
 output: {
 filename: 'app.js',
 path: path.resolve(dirname, 'dist')
 },
 module: {
 rules: [
  {
  test: /\.(js|jsx)$/,
  exclude: /node_modules/,
  use: {
   loader: 'babel-loader'
  }
  },
  {
  test: /\.css$/,
  use: ['style-loader', 'css-loader']
  },
  {
  test: /\.(png|svg|jpg|gif)$/,
  use: ['url-loader']
  },
  {
  test: /\.(woff|woff2|eot|ttf|otf)$/,
  use: ['url-loader']
  }
 ]
 },
 plugins: [
 new HtmlWebpackPlugin({
  title: 'production',
  template: './index.html'  
 }),
 // hot 检测文件改动替换plugin
 new webpack.NamedModulesPlugin(),   
 new webpack.HotModuleReplacementPlugin() 
 ],
    // webpack-dev-server 配置
 devServer: {
 contentBase: './dist',
 hot: true
 },
};
Copy after login

运行webpack-dev-server

在 package.json 文件 加入 scripts 配置:

"scripts": {
 "build": "webpack",
 "dev": "webpack-dev-server --open --mode development" // webpack-dev-server
},
Copy after login

命令行运行 npm run dev

可以在浏览器中输入localhost:8080 内容即为dist目录下的index.html内容。修改src/index.js中的内容或者依赖,即实时在浏览器热更新看到。

至此,react的webpack的基础开发环境已全部配置完毕。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

怎样使用JS实现调用本地摄像头

怎样使用JS实现3des+base64加密解密算法

The above is the detailed content of How to build a webpack+react development environment. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!