配置 React 开发环境(Babel + Webpack)
1.概述
现代的前端开发已经不是以前那种引入几个库、写几行js代码、刷新一下页面就可以看效果的方式了。为了更新一下个人的技术栈,学习一下前端界大热门的 React 替换以前的jQuery、AngularJS(1.x)以更现代的方式完成工作。断断续续的研究了一阵子nodejs、react、redux、sass、babel、webpack、gulp等相关内容,总算有点入门了的感觉,这里记录一下搭建 React 开发环境的基本步骤以备忘。
[系统]
Windows 10 Pro(1709)、Chrome(62.0.3202.62)
[版本]
node(v8.7.0)、npm(v5.4.2)、babel(v6.26.0)、webpack(v3.8.1)、react(v16.0.0)、redux(v3.7.2)
1) 工具用途
Babel
转换 ES6 代码和 JSX语法
Webpack
JS模块化加载、前端资源打包
2) 项目结构
# 初始化node项目
npm init -y
# 安装 React 全家桶
npm install --save react react-dom prop-types redux react-redux react-router-dom
约定的目录如下
/
├──dist(此目录存放编译打包后的文件)
├──src(此目录存放项目的源码、资源)
│ ├──css(此目录存放.css/.scss类型的样式文件)
│ │ ├──common.scss(通用的css样式)
│ │ └──module1.scss(模块特定的css样式)
│ ├──fonts(此目录存放字体文件)
│ ├──images(此目录存放.png/.jpg/.gif/.svg等类型的图片文件)
│ ├──js(此目录存放.png/.jpg/.gif/.svg等类型的图片文件)
│ │ ├──module1.js(演示模块)
│ │ └──app.js(入口程序)
│ └──index.html
├──.babelrc(Babel配置文件)
├──package-lock.json
├──package.json
├──webpack.common.js(Webpack通用配置)
├──webpack.dev.js(Webpack开发模式配置)
└──webpack.prod.js(Webpack产品模式配置)
JS源码和资源按照功能模块划分目录应该更为合理,请按实际需求制定目录划分方案
2.Babel
1) 安装
必备:
npm install --save-dev babel-core babel-preset-env babel-preset-react
可选插件(用于特定的ES6语法支持):
# https://babeljs.io/docs/plugins/transform-object-rest-spread/
npm install --save-dev babel-plugin-transform-object-rest-spread
# https://babeljs.io/docs/plugins/transform-class-properties/
npm install --save-dev babel-plugin-transform-class-properties
更多插件
https://babeljs.io/docs/plugins/#transform-plugins-experimental
2) 配置(.babelrc)
{
"presets": [
[
"env",
{
"useBuiltIns": true,
"targets": {
"browsers": [
"last 2 versions"
]
}
}
],
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
]
}
3.Webpack
1) 安装
# webpack、开发服务器、配置文件合并工具
npm install --save-dev webpack webpack-dev-server webpack-merge
# 各种模块处理器
npm install --save-dev babel-loader
npm install --save-dev style-loader css-loader file-loader
npm install --save-dev node-sass sass-loader
# JS 压缩插件、分离打包插件
npm install --save-dev uglifyjs-webpack-plugin extract-text-webpack-plugin
# 文件清理插件、Html生成插件
npm install --save-dev clean-webpack-plugin html-webpack-plugin
2) 基本配置
package.json
{
...,
"scripts": {
...,
"start": "webpack-dev-server --open --config webpack.dev.js",
"build": "webpack --config webpack.prod.js",
...
},
...
}
webpack.common.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
vendor: ['react', 'react-dom', 'redux', 'react-redux', 'react-router-dom'],
hello: './src/js/app.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/[name].bundle.js'
},
module: {
rules: [{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
use: 'babel-loader'
}, {
test: /\.scss/,
exclude: path.resolve(__dirname, 'src/css/common.scss'),
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader?modules&minimize!sass-loader",
publicPath: '/'
})
}, {
test: /\.scss/,
include: path.resolve(__dirname, 'src/css/common.scss'),
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader?&minimize!sass-loader",
publicPath: '/'
})
}, {
test: /\.(png|svg|jpg|gif)$/,
use: {
loader: 'file-loader',
options: {
outputPath: 'images/'
}
}
}, {
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: {
loader: 'file-loader',
options: {
outputPath: 'fonts/'
}
}
}]
},
plugins: [
new ExtractTextPlugin({
filename: "css/style.css",
allChunks: true
}),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
minChunks: Infinity
}),
new HtmlWebpackPlugin({
title: 'React App',
template: 'src/index.html'
})
]
};
webpack.dev.js
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
devtool: 'inline-source-map', // cheap-module-eval-source-map
devServer: {
contentBase: './dist'
}
});
webpack.prod.js
const webpack = require('webpack');
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = merge(common, {
devtool: 'source-map',
output: {
//filename: '[name].[hash:8].min.js'
filename: 'js/[name].min.js'
},
plugins: [
new UglifyJSPlugin({
sourceMap: true
}),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new CleanWebpackPlugin(['dist'])
]
});
4.附加代码清单
src/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="root"></div>
</body>
</html>
src/js/app.js
import React from 'react'
import ReactDOM from 'react-dom'
import Module1 from './module1'
import '../css/common.scss'
ReactDOM.render(
<Module1 />,
document.getElementById('root'))
src/js/module1.js
import React from 'react'
import styles from '../css/module1.scss'
const Module1 = () => (
<h1 className={styles.css1}>Hello World</h1>
)
export default Module1;
src/css/common.scss
body {
background-color: yellowgreen;
}
src/css/module1.scss
.css1 {
color: red;
}
5.开发和编译
# 启动开发服务器并监视文件改动
npm start
# 编译产品化版本
npm run build
网友评论