1. 新建文件夹react-demo:
mkdir react-demo cd react-demo
2. 初始化:npm init,生成package.json文件
3. 接下来安装react 与 webpack
npm install --save react react-dom npm install --save-dev webpack
4. 新建webpack.config.js文件
简单的weback配置如下:
const webpack = require('webpack'); const path = require('path'); const HTMLWebpackPlugn = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: './src/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') }, devServer: { contentBase: './dist', hot: true }, plugins: [ new CleanWebpackPlugin(), new HTMLWebpackPlugn({ template: './index.html' }), new webpack.HotModuleReplacementPlugin() ], module: { rules: [ { test: /.js$/, exclude: /node_modules/, use: [ 'babel-loader' ] }, { test: /.css$/, use: [ 'style-loader', 'css-loader?modules&localIdentName=[path][name]---[local]---[hash:base64:5]' ] } ] }, devtool: 'inline-source-map', };
注意点:
-
html-webpack-plugin,用于自动生成html文件,并将css与编译生成的bundle.js插入到生成的html文件中。另外,可配置template文件,将根据这个template文件来自动生成html文件,需要安装插件:
npm install --save-dev html-webpack-plugin npm install --save-dev html-webpack-template
-
clean-webpack-plugin:每次编译时先将编译目录dist清空
npm install --save-dev clean-webpack-plugin
-
webpack.HotModuleReplacementPlugin,这个插件的作用是,允许模块在运行时更新,页面不需要全部刷新
-
style-loader、css-loader用于处理css文件,通过开启modules可启用CSS Modules,并设置样式类名
npm install --save-dev style-loader css-loader
css-loader?modules&localIdentName=[path][name]---[local]---[hash:base64:5]
-
安装webpack-dev-server,启用热加载
npm install --save-dev webpack-dev-server
-
若使用jsx,需要编译jsx的工具,这儿使用babel,需要安装:
npm install --save-dev babel-core babel-loader babel-preset-react
如果使用es6,需要安装:
npm install --save-dev babel-preset-es2015
并且,需要在根目录下新建.babelrc文件:
{ "presets": ["react", "es2015"] }
- 支持decorator
npm install --save-dev babel-plugin-transform-decorators-legacy
- async/await
npm install --save-dev babel-plugin-transform-async-to-generator
- 如果使用redux & 路由,需要安装redux、react-redux、react-router、react-router-redux
最后,package.json文件如下:
{ "name": "react-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev": "webpack-dev-server", "build": "webpack" }, "author": "", "license": "ISC", "dependencies": { "react": "^15.6.1", "react-dom": "^15.6.1" }, "devDependencies": { "babel-core": "^6.25.0", "babel-loader": "^7.1.1", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "clean-webpack-plugin": "^0.1.16", "css-loader": "^0.28.4", "html-webpack-plugin": "^2.30.1", "html-webpack-template": "^5.6.0", "style-loader": "^0.18.2", "webpack": "^3.4.1", "webpack-dev-server": "^2.6.1" } }
通过设置“scripts”:
npm run dev
相当于执行webpack-dev-server
npm run build
相当于执行webpack