webpack為JavaScript應用程式靜態模塊打包工具(module bundler)。當webpack處理應用程式,它會遞回建立依懶關係圖(dependency graph),其中包含應用程序需要的模塊,然後將所有模塊打包成一個或多個檔案(bundles)。
webpack有四個主要核心概念:
Babel is a JavaScript compiler
官網標題說明一切,babel可用來轉換js或編譯為webpack可讀js程式碼,webpack才能進行後續的js打包。
建立專案安裝所需模組
mkdir react-webpack
cd .\react-webpack\
npm install webpack webpack-dev-server --save-dev
npm install babel babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev
npm install react react-dom --save
指令裡的參數:安裝同時要求將模組名稱及版本自動加入到package.json中
--save 加入到package.json中的dependencies參數
--save-dev 加入到package.json中的devDependencies參數
加入webpack.config.js執行打包預設執行的設定檔
loaders
webpack.config.js
var path = require('path');
module.exports = {
entry: [path.resolve(__dirname, 'src/index.js')],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
devServer: {
contentBase: path.join(__dirname, "dist"),
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets:['es2015', 'react']
}
}
]
}
};
package.json專案模塊資訊,再這可加入scripts使用npm run可以直接執行。
webpack DevServer(參數資訊)
https://webpack.js.org/configuration/dev-server/
package.json
{
"name": "react-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server --devtool eval --progress --colors"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^3.10.0",
"webpack-dev-server": "^2.10.0"
},
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
本篇先介紹webpack設定檔,下篇說明檔案結構與執行結果