一、安装全局组件
用于转译 es6、react 到 es5,打包工程,启动 webpack-dev-server 服务
npm install babel-core babel-loader babel-preset-es2015 babel-preset-react webpack-dev-server -g
二、安装构建所需组件
用于处理 css
npm install css-loader file-loader style-loader webpack --save-dev
三、安装项目依赖组件
打包时会包含到打包文件中
npm install react react-css-modules react-dom react-router --save
package.json demo:
{
"name": "testReact",
"version": "0.0.1",
"description": "test react",
"main": "app.js",
"dependencies": {
"react": "^15.3.2",
"react-css-modules": "^3.7.10",
"react-dom": "^15.3.2",
"react-router": "^2.8.1"
},
"devDependencies": {
"babel-core": "^6.17.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.16.0",
"babel-preset-react": "^6.16.0",
"clean-webpack-plugin": "^0.1.13",
"copy-webpack-plugin": "^3.0.1",
"css-loader": "^0.25.0",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"html-webpack-plugin": "^2.22.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.2"
},
"scripts": {
"build": "webpack --config webpack.config.js",
"dev": "webpack-dev-server --inline --hot --content-base ./"
},
"author": "wangxiang",
"license": ""
}
webpack.config.js demo:
var path = require('path');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var Webpack = require('webpack');
module.exports = {
entry: './app/js/page/app.jsx',
output: {
path: './web',
filename: 'app.js',
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: [
new CleanWebpackPlugin(['web'], {
root: '',
verbose: true,
dry: false,
exclude: []
}),
new Webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new CopyWebpackPlugin([{
from: 'app/image',
to: './image'
}, {
from: 'app/css',
to: './css'
}]),
new ExtractTextPlugin("./styles.css"),
new Webpack.optimize.UglifyJsPlugin({
output: {
comments: false,
},
compress: {
warnings: false
}
}),
new HtmlWebpackPlugin({
template: './template.html',
filename: './index.html',
minify: {
removeComments: true,
collapseWhitespace: true
}
})
],
module: {
loaders: [{
test: /\.jsx?$/,
query: {
presets: ['es2015', 'react'],
compact: false
},
loader: 'babel'
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules')
}, {
test: /\.(png|jpg)$/,
loader: 'file?name=[path][name]_[sha512:hash:base64:7].[ext]'
}]
}
};
注意事项:
虽然使用了 babel,但是并不代表会把所有的 es6 语法转换成 es5,在使用 es6 新的 api 之前需查询 api 是否已经转换,若没有转换,则需查询该 api 的兼容性,以免出错。如:Array.from、Object.assign。