1.用webpack、babel编译es6
先装依赖包:
yarn add webpack @babel/core @babel/preset-env babel-loader
新建.babelrc
{
"presets": ["@babel/preset-env"]
}
新建app.js
const a = 123;
新建webpack.config.js
module.exports = {
entry: {
app: './app.js'
},
output: {
path: __dirname+'/dist',
filename: '[name].bundle.js'
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
}
]
},
mode: 'development',
stats: {
colors: true
},
devtool: 'source-map'
};
/dist/app.bundle.js
使用wepack命令打包之后结果
2.配置webpack编译react
安装依赖包
yarn add react react-dom @babel/preset-react
.bashrc文件配置
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
app.js
import ReactDom from 'react-dom';
ReactDom.render(<div>react is building</div>)
打包编译
/dist/app.bundle.js
3.启动项目
安装依赖包
yarn add weback-cli webpack-dev-server react react-dom html-webpack-plugin
新建src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
src/app.js
import React from 'react';
import ReactDom from 'react-dom';
ReactDom.render(<div>react is building</div>, document.querySelector("#app"));
webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/app.js'
},
output: {
path: __dirname+'/dist',
filename: '[name].bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: __dirname+'/src/index.html',
filename: 'index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
}
]
},
devServer: {
open: true,
port: 8080
},
mode: 'development',
stats: {
colors: true
},
devtool: 'source-map'
};
package.json
"scripts": {
"dev": "webpack-dev-server --config webpack.config.js --color --progress --hot",
"start": "npm run dev",
"test": "echo \"Error: no test specified\" && exit 1"
},
启动项目yarn start
项目启动成功,我们已经成功一半了。接下来请看下一个教程(* ̄︶ ̄)
项目github地址:https://github.com/kakaoG/react-webpack