Home  >  Article  >  Web Front-end  >  How to introduce webpack in react framework

How to introduce webpack in react framework

藏色散人
藏色散人Original
2020-12-22 09:38:372891browse

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