用Webpack(npm install -g webpack)代碼打包,Webpack大體須要知道三件事:html
1)讓Webpack知道應用程序或js文件的根目錄
2)讓Webpack知道作何種轉換
3)讓Webpack知道轉換後的文件保存在哪裏react
具體來講,大體要作如下幾件事情:webpack
1)在項目根目錄下有一個webpack.config.js文件,這個是慣例
2)確保webpack.config.js能導出一個對象git
module.exports = {};
3)告訴Webpack入口js文件在哪裏web
module.exports = { entry: ['./app/index.js'] }
4)告訴Webpack須要哪些轉換插件npm
module.exports = { entry: ['./app/index.js'], module: { loaders: [] } }
全部的轉換插件放在loaders數組中。json
5)設置轉換插件的細節數組
module.exports = { entry: ['./app/index.js'], module: { loaders: [ { test: /\.coffee$/, include: __dirname + 'app', loader: "coffee-loader" } ] } }
6)告訴Webpack導出到哪裏babel
module.exports = { entry: ['./app/index.js'], module: { loaders: [ { test: /\.coffee$/, include: __dirname + 'app', loader: "coffee-loader" } ] }, output: { filename: "index_bundle.js", path: __dirname + '/dist' } }
【文件結構】app
app/
.....components/
.....containers/
.....config/
.....utils/
.....index.js
.....index.html
dist/
.....index.html
.....index_bundle.js
package.json
webpack.config.js
.gitignore
咱們不由要問,如何保證app/index.html和dist/index.html同步呢?
若是,咱們每次運行webpack命令後,把app/index.html拷貝到dist/index.html中就行了。
解決這個問題的人是:html-webpack-plugin(npm install --save-dev html-webpack-plugin)。
引入html-webpack-plugin以後,webpack.config.js看起來是這樣的:
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' }); module.exports = { entry: ['./app/index.js'], module: { loaders: [ { test: /\.coffee$/, include: __dirname + 'app', loader: "coffee-loader" } ] }, output: { filename: "index_bundle.js", path: __dirname + '/dist' }, plugins: [HTMLWebpackPluginConfig] }
【Webpack的一些指令】
webpack webpack -w //監測文件變化 webpack -p //不只包括轉換,還包括最小化文件
【Babel】
Babel能夠用來把JSX文件轉換成js文件。與Babel相關的安裝包括:
npm install --save-dev babel-core npm install --save-dev babel-loader npm install --save-dev babel-preset-react
在項目根文件夾下建立.babelrc文件。
{ "presets": ["react"] }
把babel-loader放到webpack.config.js文件的設置中去。
var HtmlWebpackPlugin = require('html-webpack-plugin'); var HtmlWebpackPluginConfig = new HtmlWebpackPlugin({ template: __dirname + '/app/index.html', filename: 'index.html', inject: 'body' }); module.exports = { entry: ['./app/index.js'], module: { loaders: [ { test: /\.js$/, include: __dirname + 'app', loader: "babel-loader" } ] }, output: { filename: "index_bundle.js", path: __dirname + '/dist' }, plugins: [HTMLWebpackPluginConfig] }
參考:http://tylermcginnis.com/react-js-tutorial-1-5-utilizing-webpack-and-babel-to-build-a-react-js-app/