PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

react如何配置开发环境?React+webpack 的开发环境配置步骤(深入篇)

寻∝梦
寻∝梦 原创
2018-09-11 10:59:25 1251浏览

本篇文章主要的讲述了关于react+webpack的开发环境配置步骤的深入了解,现在我们来一起阅读本篇文章吧

这里先讲每一步的原因和做法,其他文章会讲怎么快速搭建webpack,不用这么繁琐。配置基础文章链接://m.sbmmt.com/js-tutorial-409770.html

转接上文目录:

目录
二、webpack 升级篇
6. ES6 转ES5模块
7. url和file模块
三、 webpack 高级篇
1.语法检查器eslint
2.uglify 源代码加密压缩
3.moduleconcatenationPlugin
4.devtool
5.happypack
6.dll

6.ES6 转ES5模块

由于部分浏览器对ES6的部分语法没有完全兼容,但nodejs已经支持ES6,所以webpack提供了ES6转ES5 的模块。
安装指令(在开发模式使用):

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

如果要支持react,需要安装下面的模块:

npm install babel-preset-es2015 babel-preset-react babel-preset-stage-3 --save-dev

webpack.config.js 的代码:

module.exports = {...module:{    
    rules:[...
   {
        test:/\.jsx$/,
        exclude:/(node_modules|bower_components)/,//排除XXX类型文件
        use:{
            loader:'babel-loader'           
        }
    }
]
}...}

在根路径下创建.babelrc 文件

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

7.url和file模块
引入url模块处理图片,file模块处理图片外的其他文件类型
指令:

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

webpack.config.js 代码:

module.exports = {...
    {   //配置辅助loader,处理图片  
        test:/\.(png|jpg|gif)$/,
        loader:'url-loader',
        options:{limit:8192,name:"images/[name].[ext]"}
    },
    { //处理图片外的其他文件类型
        test:/\.(appcache|svg|eot|ttf|woff|woff2|mp3|pdf)(\?|$)/,
        include:path.resolve(__dirname,'src'),
        loader:'file-loader?name=[name].[ext]' 
    }...}

三、webpack 高级篇
1.语法检查器eslint
ESLint是一个QA工具,用来避免低级错误和统一代码的风格。
安装指令:

npm install eslint eslint-loader --save-dev

装完eslint,然后通过init指令创建一个规则文件。

指令:
cd 进入项目文件夹根路径,敲./node_modules/.bin/eslint --init  

? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser, Node
? Do you use CommonJS? Yes
? Do you use JSX? Yes
? Do you use React? Yes
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Single? What line endings do you use? Windows
? Do you require semicolons? Yes
? What format do you want your config file to be in? JSON

回答完问题后,在根目录下面会生成一个.eslintrc.json格式的文件,并自动安装相应的包。.eslintrc.json
里面的内容可以根据自己的编程习惯在进行微调。ESLINT中文网站
这里先给个样例:

{    "env": {        "browser": true,        "commonjs": true,        "es6": true,        "node": true
    },    "extends": "plugin:react/recommended",    "parserOptions": {        "ecmaVersion": 8,//ECMAScript syntax 最新版本
        "ecmaFeatures": {            "impliedStrict": true,            "experimentalObjectRestSpread": true,            "jsx": true
        },        "sourceType": "module"
    },    "plugins": [        "react"
    ],    "rules": {        "semi": [            "error",            "always"
        ],              
        "no-debugger": "error",//不允许用debugger这个关键字
        "no-dupe-args": "error",//不允许函数参数同名
        "no-caller": "error",//不允许用callee等,es6严格模式不支持
        "no-unmodified-loop-condition": "error",        "no-with": "error",//不允许用with来声明
        "no-catch-shadow": "error"
    }
}

webpack.config.js 的配置

module: {
        rules: [        ...{
        test:/\.js$/,
        enforce:'pre',
       loader:'eslint-loader',
       include:path.resolve(__dirname,'src')
    }...]
}

2.uglify 源代码加密压缩(想看更多就到PHP中文网React参考手册栏目中学习)

属于webpack的插件,直接使用就行。

webpack.config.js 代码:
module.exports = {   ...
 plugins:[
 ..  
new webpack.optimize.UglifyJsPlugin(
{output: { 
    comments:false,//删除代码中所有注释
},
compress:{
 warnings:false,
}
})
]...}

4.devtool
webpack 提供的辅助工具,调试的时候能正确的显示源代码出错的行数。eval-soure-map用于开发模式下。其他参数使用环境

module.exports = {...devtool:'eval-soure-map'...}

5.happypack
让loader多进程去处理文件,加速webpack构建

安装指令:npm install happypack --save-dev
var os = require('os');//os.cpus().Length 一般会取不到值,这里直接size:4,而不是size:os.cpus().lengthvar Happypack = require('happypack');var happypackThreadPool = Happypack.ThreadPool({size:4});//size:os.cpus().Lengt根据电脑的idle,配置当前最大的线程数量module.config.js 下面的配置module.exports = {
...module:{    rules:[
 {        test:/\.js$/,    
        include:path.resolve(__dirname),        loader:'happypack/loader?id=happybabel'

    }
]
}plugins:[new Happypack({    id:"happybabel",    loaders:['babel-loader'],    threadPool:happypackThreadPool,    cache:true,    verbose:true}),
]
}

6.dll
在根目录上创建一个webpack.dll.config.js文件

//webpack.dll.config.js 的内容:const webpack = require('webpack');const path = require("path");const fs=require('fs');const vendors = [  'react' //这里添加第三方库文件

];module.exports = {  entry: {    vendor: vendors,
  },  output: {    path: path.join(__dirname+'/build'),    filename: '[name].[chunkhash].js',    library: '[name]_[chunkhash]',
  },  plugins: [    new webpack.DllPlugin({      path: path.join(__dirname+"/build"+'/manifest.json'),      name: '[name]_[chunkhash]',      context: __dirname,
    }),
  ],
};//console.log(path.join(__dirname+"/build"));

在Powershell窗口里面敲下面指令:

webpack --config webpack.dll.config.js -p

在build路径下会生成两个文件,一个manifest.json,另一个叫vendor.XXXX.js的文件。vendor.xxx.js 需要在html(这里直接写在html模板里面)里面引入。
webpack.config.js 填加:

 moule.exports = { ...
 plugins:[  ...
 new webpack.DllReferencePlugin({
      context: __dirname,
      manifest: require('./build/manifest.json'),
    }),    ...]
....
}

然后在Powershell 里面敲npm start 就好。

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

以上就是react如何配置开发环境?React+webpack 的开发环境配置步骤(深入篇)的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。