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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)