Home  >  Article  >  Web Front-end  >  How to configure the development environment for React? React+webpack development environment configuration steps (with configuration examples)

How to configure the development environment for React? React+webpack development environment configuration steps (with configuration examples)

寻∝梦
寻∝梦Original
2018-09-11 10:53:553201browse

This article mainly introduces you to the details about React webpack development environment configuration steps. Interested students can discuss knowledge about react with each other. Now let’s read this article together

Here we will first break down the methods and reasons for each step, and other articles will explain how to do it. Quickly build webpack.

Directory:
1 Basics
1. Environmental requirements
2. Configuration of NODE_PATH
3. Create project folder
4. Install webpack global package
5. Create package.json document
6.webpack.config.js configuration
Second upgrade
1. Introduce the plug-in that automatically generates HTML
2. webpack-dev-server
3. CSS file support
4. CSS file stripping plug-in
5. Other CSS auxiliary modules

I am using win10 system, and the steps mentioned below are only tried with windows system.
First configure webpack. The following are the configuration steps:

1. Basics:

1. Environmental requirements: nodejs has been installed and computer networking

2.NODE_PATH configuration: cmd brings up the command window, then type path. In the output, there will be
C:\Users\XXX\AppData\Roaming\npm; and then in My Computer->Right-click Properties->Advanced System Settings->Advanced->Environment Variables->Under System Variables->New->Then type the variable name: NODE_PATH, value: C:\Users \XXX\AppData\Roaming\npm\node_modules. After setting, click OK OK OK.

3. Create a project folder (and modify the file name), and right-click shift under the project folder. Select the option to Open a Powershell window here (Chinese system: Open a command window here). In the
side of the pop-up window, enter node -v, the system will return the node version number.
Note: All PowerShell windows below are opened in the root directory of the project folder.

4. Install the global webpack package, command: npm install webpack -g and press Enter
The system will automatically install it. After it is installed, type webpack -v to see the version number of webpack. My current version is version 3.3.0

5. Create a package.json document
Under Powershell, type: npm init and press Enter, and then the system will prompt you to enter relevant content. If you don’t want to configure it, just press Enter to skip it.

下面是系统相关的提示:
name:reactwebpack +回车键 ,reactwebpack是我这个项目的名字
version:1.0.0+回车键description:(项目描述信息),这里按回车键直接跳过
entry point:(入口文件)按回车键跳过。入口文件会在下面讲的webpack.config.js 里面陪置
test command: 跳过就好,会面会重新配置这个指令内容。这里先跳过
git repository:(git 库的链接地址)。这里不涉及到git库,直接跳过keywords:(关键字),直接跳过先
author:(作者),可以输入自己的英文名+回车键license:(ISC 开源许可证号,与git相关) 这里跳过
Is this ok?(yes) 比对下内容,如果没错,直接输入y+回车键

6 webpack.config .js configuration file

Create a webpack.config.js file under the root directory of the project. At the same time, create a src folder to store source files.
The following is the overall folder structure of the project:

   reactwebpack        #项目文件夹
         build         #正式打包用的文件夹(也有人用dist命名),用于生产环境
         node_modules  #npm 指令会自动生成
         src           #用于存放源文件
          app.js       #在src下面建一个app.js
          index.html   #在src下面建一个index.html
        package.json       #webpack 包的项目文件
        webpack.config.js   #webpack包的配置文件
        README.md           # 项目说明文档

webpack.config.js configuration content and description:

var path=require('path');module.exports = {entry:'./src/app.js', //入口文件配置为app.js文件。若入口文件为index.js,这里可以直接写成'./src'//入口文件很多的话,可以写成下面的格式:
/*entry:{    pageOne: './src/pageOne/index.js',    pageTwo: './src/pageTwo/index.js',    pageThree: './src/pageThree/index.js'}
*/output: {    filename:'bundle.js',//js合并后的输出的文件,命名为bundle.js    path:path.resolve(__dirname,'build'),//指令的意思是:把合并的js文件,放到根目录build文件夹下面    //publicPath:'',生成文件的公共路径,‘/work/reactweb/dist’ 生产环境下所有的文件路径将会添加这个公共路径
}//多个入口的输出文件格式
/*output: {    filename:'[name].js',//name相当于变量,等同于pageOne/pageTwo/pageThree    path:path.resolve(__dirname,'build'),//}
*/
}

Under the src folder, create a new app.js

var app=document.createElement("p");
app.innerHTML='

Hello World!

';document.body.appendChild(app);

Create index.html under src and introduce the bundle.js file


    
        reactwebpack
        
        
    

Install the webpack local package, type the command below PowerShell: npm install webpack –save-dev
After installation, directly Type webpack. If successful, the following content will be displayed, and bundle.js

Hash: bba9fbe70c8f6bbe2cd1Version: webpack 3.3.0Time: 47ms
    Asset     Size  Chunks             Chunk Names
bundle.js  2.58 kB       0  [emitted]  main
   [0] ./src/app.js 111 bytes {0} [built]

will be generated under the build folder. Open it with a browser and index.html under src. It will display

Hello World!

. This is the simplest webpack packaging configuration.

2. Upgrade

  1. Introducing a plug-in that automatically generates html
    Type the command below the PowerShell window:

npm install html-webpack-plugin --save-dev

Small note: The code running environment is divided into development mode and production mode. Some plug-ins are only used during development.
​ ​ ​ ​ –save: Automatically write dependencies in production mode to json files.
​​​​​—save-dev: Automatically write the dependencies (devDependencies) in development mode to the json file.

After the plug-in is installed, configure the webpack.config.js file. Import the module and set the plugins object value in module.exports.

 var HtmlwebpackPlugin = require('html-webpack-plugin'); module.exports = {
...//前面的对象后面需要添加逗号隔开plugins:[new HtmlwebpackPlugin({    title:'reactwebpack'
   /* 全部都是可选项    title:"reactwebpack",   配置html 的title    filename: , html文件的名字,默认是index    template:'', 模板文件路径    inject:true|'body'|'head'|'false', 设置为 true|'body':js文件引入的位置为body的结束标签之前    favicon:'',  设置html的icon图标    minify:{}|false, 暂时不理解这个参数的使用    hash:true|false,  将添加唯一的webpack编译hash到所有包含的脚本和css文件    cache:true|false, 默认为true,仅仅在文件修改之后才会发布    showErrors:true|false, 默认为true,错误信息写入HTML页面中    chunks: 允许添加某些块(比如unit test)    chunksSortMode: 允许控制块在添加到页面之前的排序方式    excludeChunks: 允许跳过模型块,比如单元测试块
  */
})
],
}

Run webpack in the PowerShell window. After success, index.html will be generated under the path set by the output (here is the build folder). The generated js will automatically import bundle.js, so the template index.html does not need to add bundle.js. (If you want to learn more, go to the PHP Chinese websiteReact Reference Manual column to learn)

  1. webpack-dev-server

When debugging the above, you need to run the webpack command first and then open it with a browser to see the modified results. How to simplify this work? Webpack can introduce the node.js express server, support hot updates, and automatically refresh the browser content after each modification and save.
Instructions for installing webpack-dev-server (used to assist development, so write development mode dependencies):

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

The automatic refresh mode of the server is divided into iframe and inline mode. Here we only talk about the inline mode mode. .

There are two ways to configure webpack's server configuration:
1. Configure directly in the webpack.config.js document.

    在package.json文件里面配置,快捷指令。
    “scripts":{
     "start":"webpack-dev-server --inline --hot" 
}
 指令的意思:在PoweShell窗口下敲npm start 等效于npm webpack-dev-server -- inline --hot

Configuration in webpack.config.js:

var webpack=require('webpack');//用于服务器的配置

module.exports ={...devServer:{
    //contentBase: path.join(__dirname,"dist"),//用于静态文件的目录,不设置默认为当前根目录
   // contentBase:[path.join(__dirname,'public'),path.join(__dirname,'assets')],//支持多路径
   // publicPath:"/assets", 服务器地址:http://localhost:8080 ,output file:http://localhost:8080/assets/bundle.js
    //compress:true,//gzip压缩
    //headers:{"X-Custom-Foo":"bar"},
    hot:true,//是否启用热更新
    port:8080,
    historyApiFallback:true,//html5接口,设置为true,所有路径均转到index.html
    inline:true,//是否实时刷新,即代码有更改,自动刷新浏览器 
    stats:{colors:true},//显示bundle文件信息,不同类型的信息用不同的颜色显示
    /*
    proxy:{     //服务器代理配置        "/api":{  //相对路径已/api打头,将会触发代理
            target:"http://localhost:3000", //代理地址
            pathRewrite:{"^/api":""}, //路径替换
            secure:false //跨域
        }
    }
    */
},...}

配置好后在PowerShell窗口敲npm start 启动服务器。
第一次尝试修改js时,如果浏览器的console控制台显示[HMR]Waitiing for update signal from WDS…,但此时网页内容没有刷新时。可以在PowerShell用ctrl+c来停止当前进程。页面就可以刷新过来。 连按两次ctrl+c,PowerShell 就会提示是否停止服务器,敲y回车就可以停掉服务器。
2. 重新建一个server.js ,专门用于服务器的配置。(推荐使用这种方式)
在根目录上创建一个server.js

  在package.json文件里面配置,快捷指令,指定对应的配置文件。  "scripts": {   "start":"node server.js" 
  },
server.js 的配置:var webpack = require('webpack');//引入webpack模块var webpackDevServer = require('webpack-dev-server');//引入服务器模块var config = require('./webpack.config');//引入webpack配置文件var server = new webpackDevServer(webpack(config),{    //contentBase: path.join(__dirname,"dist"),//用于静态文件的目录,不设置默认为当前根目录
   // contentBase:[path.join(__dirname,'public'),path.join(__dirname,'assets')],//支持多路径
   // publicPath:"/assets", 服务器地址:http://localhost:8080 ,output file:http://localhost:8080/assets/bundle.js
    //compress:true,//gzip压缩
    //headers:{"X-Custom-Foo":"bar"},
    hot:true,//是否启用热更新   
    historyApiFallback:true,//html5接口,设置为true,所有路径均转到index.html
    inline:true,//是否实时刷新,即代码有更改,自动刷新浏览器 
    stats:{colors:true},//显示bundle文件信息,不同类型的信息用不同的颜色显示
    /*
    proxy:{     //服务器代理配置
        "/api":{  //相对路径已/api打头,将会触发代理
            target:"http://localhost:3000", //代理地址
            pathRewrite:{"^/api":""}, //路径替换
            secure:false //跨域
        }
    }
    */});//将其他路由,全部返回index.htmlserver.app.get('*',function(req,res){
    res.sendFile(__dirname+'/build/index.html');
});
server.listen(8080,function(){
 console.log('正常打开8080端口')
});

若要启动node js api 的热更新功能,需要修改webpack.config.json 的entry的代码。
注意:在用webpack生成最终的build文件用于生产环境的时候,请先把热更新代码屏蔽掉,否则运行build里面的index.hmtl 时,会一直报错: GET http://localhost:8080/sockjs-node/info?t=1510883222453 net::ERR_CONNECTION_REFUSED    msgClose @ client:164 abstract-xhr.js:132。

module.exports = {
    entry: {
 app:[ 
              'webpack-dev-server/client?http://localhost:8080',  // 热更新监听此地址                                                     
               'webpack/hot/dev-server',  // 启用热更新
              path.resolve(__dirname, 'src', 'app')  
        ]        
    },...plugins:[...new webpack.HotModuleReplacementPlugin(),//热更新配套插件...]
}

3.CSS 文件的支持

在实现webpack的基本配置和服务器的热更新后,我们将会考虑网页的具体实现(html+CSS+JS)。webpack是基于nodeJS平台,完全支持JS文件不支持css。所以要把css转成JS文件。webpack提供了一个两个模块来支持css文件转编译。
style-loader:将css内容插入到html的style
css-loader:处理css里面的@import 和url() 的内容,需要url-loader 和file-loader的支撑
file-loader: 用MD5 hash加密文件名后返回相应的路径
url-loader 在file-loader 基础上加了额外的功能。当链接的文件小于limit 8192时,可以直接返回DataURL。DataURL是图片格式转换成base64编码的字符串,并存储在URL中。这样可以减少客户端的请求次数

引入这两个loader的方法:
先安装着两个模块,相关的指令(用于开发模式的依赖):

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

修改webpack.config.js 的配置

module.exports ={...module:{
    rules:[{
        test:/\.css$/,
        use:['style-loader','css-loader'],

    },
    {   //配置辅助loader
        test:/\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
        loader:'url-loader',
        options:{limit:8091}
    }
]
},...resolve:{
    extensions:['.js','jsx','less','.css','.scss']//后缀名自动补全
}
}

在src文件夹下面创建两个文件夹:

src
    css
        css.css
    img        7.png

css.css 里面的代码:

p{    background:url('../img/7.png') no-repeat 211px 0px ;  

}

app.js 入口文件导入css文件

require('./css/css');

都配置好后
在PowerShell 下敲npm start 运行服务器,浏览器上输入http://localhost:8080/

  1. CSS 文件剥离插件

css文件和html混合,这不符合html的优化思路。所以要求webpack生成的最终文件css也是单独一个文件。这里webpack提供了extract-text-webpack-plugin插件。
安装的指令:

npm install extract-text-webpack-plugin --save-dev

修改webpack.config.js

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {...module:{
    rules:[{
        test:/\.css$/,
        use:ExtractTextPlugin.extract({    //使用ExtractTextPlugin 插件
            fallback:"style-loader",
            use:"css-loader"
        }),

    },{   //配置辅助loader
        test:/\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
        loader:'url-loader',
        options:{limit:8091}
    }

]
},...plugins:[...new ExtractTextplugin("styles.css"),    //插件声明
],...}

停掉服务器,然后敲webpack 指令就会看到build文件下的styles.css 文件。
5.其他css辅助模块
 less 模块 sass模块 前缀postcss模块
安装指令:

npm install sass-loader node-sass webpack --save-dev
 npm install less-loader less --save-dev
 npm i -D postcss-loader

在src文件夹下创建两个文件夹(less,scss)及相应的文件:

less.less:
@color:#f938ab;p{    color:@color;
}
scss.scss:$font-stack:Helvetica,sans-serif;$primary-color:#333;
p{
    font:100% $font-stack;
    border:1px solid $primary-color;
}

在app.js 里面引用
在根目录上创建postcss.config.js(webpack 会自动找到这个文件):

module.exports = {    plugins:{ 
    'autoprefixer': {},   
    }
}

webpack.config.js 里面配置:

module.exports ={...module:{
    rules:[
        {
        test:/\.css$/,        
        use:ExtractTextPlugin.extract({//使用ExtractTextPlugin 插件
            fallback:"style-loader",//用于开发环境
            use:["css-loader","postcss-loader"]
        }),
    },{   //配置辅助loader
        test:/\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
        loader:'url-loader',
        options:{limit:8091}
    },
      {
        test:/\.less$/,        
        use:ExtractTextPlugin.extract({//使用ExtractTextPlugin 插件
            fallback:"style-loader",//用于开发环境
            use:["css-loader","postcss-loader","less-loader"]
        }),
    },
       {
        test:/\.scss$/,        
        use:ExtractTextPlugin.extract({//使用ExtractTextPlugin 插件
            fallback:"style-loader",//用于开发环境
            use:["css-loader","postcss-loader","sass-loader"]
        }),
    }
]
},...}

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How to configure the development environment for React? React+webpack development environment configuration steps (with configuration examples). 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