webpack配置
基本配置
- 新建文件夾,起名react1
- 打開終端,打開至文件夾,輸入命令:npm init
- 一路回車,直至完成
- 創建webpack.config.js文件,並在其中書寫以下內容(摘自官網)
const path = require('path');
module.exports = {
entry: './app/main.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
}
};
babel配置
- 前往https://github.com/babel/babel-loader
- 將以下內容(摘自官網)粘貼至output下方
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
}
]
}
- 因未安裝babel-loader,所以安裝babel-loader:npm i babel-loader -D
- 提示未安裝babel-core,所以安裝babel-core:npm i babel-core -D
- 運行webpack時報錯,提示未安裝preset,去安裝preset:npm i babel-preset-es2015 -D
配置React
- 安裝React npm包,npm i react -D
- 安裝React-dom包,npm i react-dom -D
- 因需要翻譯JSX語法,webpack的loader的preset中需添加react,上方代碼變更爲
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015','react']
}
}
}
]
}
- 此時配置的react其實並未生效,因爲其並未被安裝,此時應運行命令:npm i babel-preset-react
- 記得要想查看效果需要編寫index.html文件並引入js文件呦。
- 此時已配置完成,但要想讓webpack持續監聽js變化自動打包,在modules的後面添加watch:true
完整的webpack.config.js如下
const path = require('path');
module.exports = {
entry: './app/main.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015','react']
}
}
}
]
},
watch: true
};