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
};