1、安裝全局組件javascript
用於轉譯 es六、react 到 es5,打包工程,啓動 webpack-dev-server 服務css
npm install babel-core babel-loader babel-preset-es2015 babel-preset-react webpack-dev-server -ghtml
2、安裝構建所需組件java
用於處理 css node
npm install css-loader file-loader style-loader webpack --save-devreact
3、安裝項目依賴組件webpack
打包時會包含到打包文件中es6
npm install react react-css-modules react-dom react-router --saveweb
package.json demo:npm
{ "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。