search
HomeWeb Front-endJS TutorialHow to introduce webpack in react framework

How to introduce webpack into the react framework: first create a folder; then create a "package.json" project file; then install webpack globally; finally install webpack in the project through "npm install". Can.

How to introduce webpack in react framework

The operating environment of this tutorial: windows7 system, react17.0.1&&Webpack3.0 version. This method is suitable for all brands of computers.

Recommended tutorial: react video tutorial

What is webpack?

Webpack is a module packaging tool. In the front-end, modules refer to js, ​​css, pictures and other types of files. Webpack supports multiple module systems and is compatible with multiple writing specifications of js (such as ES6). It can handle the interdependencies between modules and uniformly package and publish static resources.

Installation and use of webpack

First we create a folder such as study, open cmd in the start menu, enter the folder, and then perform the following steps:

1. npm init //Create a package.json project file.

2. npm install -g webpack // Install webpack globally. If it has already been installed, you can skip it.

3. npm install --save-dev webpack //Install webpack in the project.

After the creation is completed, we create two folders in our file directory, dist (the folder placed after packaging) and src (where we write the project). In the src folder, we first create two files called index.js and main.js. In the dist folder, we create an index.html for the browser to read and display. The structure is as follows:

How to introduce webpack in react framework

We write the initial content in dist/index.html, and the imported js file is the bundle.js file. This file is generated after webpack packaging document. As shown below:

How to introduce webpack in react framework

Enter "export code" in index.js:

module.exports = function() {
  var hello = document.createElement('div');
  hello.textContext = "This is index.js file."
  return hello;
}

Export the hello variable, accept the variable in main.js, and then This variable is inserted into the root tag:

const hello = require('./index.js');
document.querySelector('#root').appendChild(hello());

Next we create a webpack.config.js file in the root directory to configure webpack. We first perform a simple configuration. The main thing we do now is to set the content. The entry path and the storage path of the packaged files. Write the following code block in webpack.config.js:

module.exports = {
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
}

entry is the only entry file, that is, webpack should read from here, and output is the output. What is set here is to output to the dist directory. bundle.js file. Then run webpack and run

".\\node_modules\\.bin\\webpack" in cmd. This is run in windows. If it is installed globally, you can also use "webpack".

Furthermore, we do not need the above input method, and add "start": "webpack" to the scripts in package.json to enable webpack through the npm start command.

The script part in package.json has the ./node_modules/.bin path added by default, so we do not need to enter the detailed path address. start is a special script name. We can also give it other names, but if it does not correspond to start, then we must use npm run {the name you used in the script} when we want to start it, such as npm run build.

The specific functions of webpack during development and production

We need to debug the code during development. If an error occurs after packaging, we need debugging tools to help us correct the error. Source Map helps us solve this problem. It needs to be configured in our webpack.config.js file. The attribute name is devtool. It has four options for users to choose.

1. Source-map: Generate a complete and fully functional file in a separate file. This file has the best source map, but it will slow down the construction of the packaged file;

2. cheap-module-source-map: Generate a map without column mapping in a separate file Without column mapping, the project construction speed is improved, but the browser developer tools can only correspond to specific rows and cannot correspond to specific columns (symbols), which will cause inconvenience in debugging;

3. eval-source-map: Use eval to package the source file module and generate a clean and complete source map in the same file. This option can generate a complete sourcemap without affecting the build speed, but it has performance and security risks for the execution of the packaged output JS files. However, this is a very good option during the development phase, but this option must not be used during the production phase;

4. cheap-module-eval-source-map: This is the fastest generation when packaging files. With the source map method, the generated Source Map will be displayed alongside the packaged JavaScript file, without column mapping, and has similar shortcomings to the eval-source-map option.

We use the third method here. Configure the following in webpack.config.js:

module.exports = {
  devtool: 'eval-source-map',
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
}

这四种方式从上到下打包速度回越来越快,当然隐患越来越多,所以在生产阶段还是用第一种为好。

使用webpack构建本地服务器

webpack提供一个可选的可以检测代码的修改并自动刷新页面的本地服务器。该服务器是基于node.js的,不过我们需要单独安装它作为项目依赖。

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

devserver作为webpack配置选项中的一项,以下是它的一些主要配置选项:

1、contentBase: 默认webpack-dev-server会为根文件夹提供本地服务器,如果想为另外一个目录下的文件提供本地服务器,应该在这里设置其所在目录(本例设置到“public"目录)

2、port: 设置默认监听端口,如果省略,默认为“8080”

3、inline: 设置为true,当源文件改变时会自动刷新页面

4、historyApiFallback: 在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html

代码如下:

module.exports = {
  devtool: 'eval-source-map',
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  devServer:{
    contentBase: "./dist", //读取目录
    port: 8000,   //端口号
    inline: true, //实时刷新
    historyApiFallback: true //单页面不跳转
  },
}

接着我们要在package.json中配置server代码如下:

{
  "name": "study-webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1",
    "server": "webpack-dev-server --open"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^3.8.1",
    "webpack-dev-server": "^2.9.3"
  }
}

接着在cmd中输入 npm run server 即可在浏览器中打开本地服务器。

Loaders

loaders作为webpack的强大功能之一,它的作用就是让webpack调用外部脚本和工具来对不同的格式的文件进行处理。Loaders需要单独安装并且需要在webpack.config.js下的modules关键字下进行配置,Loaders的配置选项包括以下几方面:

1、test:一个匹配loaders所处理的文件的扩展名的正则表达式。

2、loader: loader的名称(必需)。

3、include/exclude:手动添加:手动添加需要的文件夹或者屏蔽掉不需要选择的文件。

4、query: 为loaders提供了额外的设置选项。

babel

babel是一个编译js的平台,它可以帮助你的代码编译称为浏览器识别的代码。并且它还可以把js的扩展语言JSX编译称为浏览器识别的语句。

安装依赖包:

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

下面我们在webpack.config.js中来配置loader和babel:

module.exports = {
  devtool: 'eval-source-map',
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  module: {
    loaders:[{
      test: /\.js$/,   //需要匹配的文件扩展名
      exclude: /node_modules/, // 排除不需要处理的文件夹
      loader: 'babel-loader', //  所用的loader名称
      query:{
            presets: ['es2015', 'react']  // 支持es5与react
      }
    }]
  },
  devServer:{
    contentBase: "./dist", //读取目录
    port: 2333,   //端口号
    inline: true, //实时刷新
    historyApiFallback: true //单页面不跳转
  },
}

完成以上工作后接着来安装react

npm install --save react react-dom

接着修改src文件夹中的Index.js与main.js的代码,react使用的版本"react": "^16.0.0":

以下是Index.js代码:

import React from 'react';
import ReactDOM from 'react-dom';
class Greeter extends React.Component{
  render() {
    return (
      <div>
        <span>my god</span>
      </div>
    );
  }
};
export default Greeter

以下为main.js代码:

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom&#39;;
import Greeter from &#39;./Index&#39;;
ReactDOM.render(<Greeter />, document.getElementById(&#39;root&#39;));

Babel的配置选项

因为babel有非常多的配置选项,在单一的webpack.config.js文件中进行配置往往使得这个文件显得太复杂,因此一些开发者支持把babel的配置选项放在一个单独的名为 ".babelrc" 的配置文件中。因此现在我们就提取出相关部分,分两个配置文件进行配置(webpack会自动调用.babelrc里的babel配置选项)。

将webpack.config.js中的query去掉,建立.babelrc文件写出一下代码:

{
  "presets": ["react", "es2015"]
}

css的相关安装

webpack把所有文件当成模块处理,只要有合适的loaders,它都可以被当做模块来处理。webpack提供两个工具处理样式表css-loader,style-loader,二者处理的任务不同,css-loader使你能够使用类似@import 和 url(…)的方法实现 require()的功能,style-loader将所有的计算后的样式加入页面中,二者组合在一起使你能够把样式表嵌入webpack打包后的JS文件中。

安装loader

npm install --save-dev style-loader css-loader

接着webpack.config.js中添加loaders

module.exports = {
  devtool: &#39;eval-source-map&#39;,
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  module: {
    loaders:[
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: &#39;babel-loader&#39;
      },
      {
        test: /\.css$/,
        loader: &#39;style-loader!css-loader&#39;
      }
    ]
  },
  devServer:{
    contentBase: "./dist", //读取目录
    port: 2333,   //端口号
    inline: true, //实时刷新
    historyApiFallback: true //单页面不跳转
  },
}

接着我们可以创立一个css文件,记好路径,在main.js中(也就是webpack的入口文件)我们导入css文件即可使用。

这里题外说个问题,我们想在react中使用sass,就在此基础上先进行npm下载

加载: npm install sass-loader node-sass –save-dev

之后我们在webpack.config.js中添加loaders

module.exports = {
  devtool: &#39;eval-source-map&#39;,
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  module: {
    loaders:[
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: &#39;babel-loader&#39;
      },
      {
        test: /\.(css|scss)$/,
        loader: &#39;style-loader!css-loader!sass-loader&#39;
      }
    ]
  },
  devServer:{
    contentBase: "./dist", //读取目录
    port: 2333,   //端口号
    inline: true, //实时刷新
    historyApiFallback: true //单页面不跳转
  },
}

之后再style文件夹中创立一个scss文件导入到main.js文件中即可使用了。

eslint的安装与使用

首先安装依赖包 npm install –save-dev eslint eslint-loader

通过配置webpack.congfig.js以及创建.eslintrc文件来配置好初始值即可在项目中使用eslint。

webpack.config.js:
module.exports = {
  devtool: &#39;eval-source-map&#39;,
  entry: __dirname + "/src/main.js",
  output:{
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  module: {
    loaders:[
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: &#39;babel-loader!eslint-loader&#39;
      },
      {
        test: /\.(css|scss)$/,
        loader: &#39;style-loader!css-loader!sass-loader&#39;
      }
    ]
  },
  devServer:{
    contentBase: "./dist", //读取目录
    port: 2333,   //端口号
    inline: true, //实时刷新
    historyApiFallback: true //单页面不跳转
  },
};
.eslintrc
{
    "parser": "babel-eslint",
    "rules": {
        "semi": [
            "error",
            "always"
        ]
    }
}

eslint的相关规则根据自己的需求来制定即可。

The above is the detailed content of How to introduce webpack in react framework. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
react中canvas的用法是什么react中canvas的用法是什么Apr 27, 2022 pm 03:12 PM

在react中,canvas用于绘制各种图表、动画等;可以利用“react-konva”插件使用canvas,该插件是一个canvas第三方库,用于使用React操作canvas绘制复杂的画布图形,并提供了元素的事件机制和拖放操作的支持。

react中antd和dva是什么意思react中antd和dva是什么意思Apr 21, 2022 pm 03:25 PM

在react中,antd是基于Ant Design的React UI组件库,主要用于研发企业级中后台产品;dva是一个基于redux和“redux-saga”的数据流方案,内置了“react-router”和fetch,可理解为应用框架。

React是双向数据流吗React是双向数据流吗Apr 21, 2022 am 11:18 AM

React不是双向数据流,而是单向数据流。单向数据流是指数据在某个节点被改动后,只会影响一个方向上的其他节点;React中的表现就是数据主要通过props从父节点传递到子节点,若父级的某个props改变了,React会重渲染所有子节点。

react中为什么使用nodereact中为什么使用nodeApr 21, 2022 am 10:34 AM

因为在react中需要利用到webpack,而webpack依赖nodejs;webpack是一个模块打包机,在执行打包压缩的时候是依赖nodejs的,没有nodejs就不能使用webpack,所以react需要使用nodejs。

react中forceupdate的用法是什么react中forceupdate的用法是什么Apr 19, 2022 pm 12:03 PM

在react中,forceupdate()用于强制使组件跳过shouldComponentUpdate(),直接调用render(),可以触发组件的正常生命周期方法,语法为“component.forceUpdate(callback)”。

react是组件化开发吗react是组件化开发吗Apr 22, 2022 am 10:44 AM

react是组件化开发;组件化是React的核心思想,可以开发出一个个独立可复用的小组件来构造应用,任何的应用都会被抽象成一颗组件树,组件化开发也就是将一个页面拆分成一个个小的功能模块,每个功能完成自己这部分独立功能。

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

react和reactdom有什么区别react和reactdom有什么区别Apr 27, 2022 am 10:26 AM

react和reactdom的区别是:ReactDom只做和浏览器或DOM相关的操作,例如“ReactDOM.findDOMNode()”操作;而react负责除浏览器和DOM以外的相关操作,ReactDom是React的一部分。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),