1、初始化npm,会自动创建一个package.json文件
npm intl
2、安装webpack
cnpm install --save-dev webpack webpack-cli
3、编写基础的webpack配置文件
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
4、创建基础的目录结果。测试webpack.config.js配置。
// 目录结构
wangyiyun
|-dist
|-index.html
|-src
|-index.js
// index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>网易云音乐</title>
</head>
<body>
<div id="app"></div>
<script src="./bundle.js"></script>
</body>
</html>
// index.js
document.getElementById('app').innerHTML = "网易云音乐"
命令行执行打包命令:dist目录下会出现 bundle.js文件
npx webpack --config webpack.config.js
浏览器打开index.html文件查看:界面出现 网易云音乐 字样
5、引入babel
先引入 babel-loader 让webpack和babel协同工作
cnpm install --save-dev babel-loader
在 webpack.config.js 中配置 babel-loader
// loader
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
],
},
引入 @babel-core 、@babel/preset-env(解析es5+语法) 、@babel/preset-react(解析JSX语法)
cnpm instal --save-dev @babel-core @babel/preset-env @babel/preset-react
6、引入 react 。
cnpm install react react-dom
7、webpack打包命令优化
每次打包都得执行下面的命令,麻烦。
npx webpack --config webpack.config.js
在package.json中配置
"scripts": {
...
"build": "npx webpack --config webpack.config.js"
},
现在可执行下面的命令打包
npm run build
8、配置webpack-dev-server
配置一个简易的 web server。
cnpm install --seve-dev webpack-dev-server
在webpack.config.js中配置服务器
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
优化服务启动命令
"scripts": {
...
"build": "npx webpack --config webpack.config.js",
"start": "webpack-dev-server --config webpack.config.js"
},
现在可以通过以下命令启动开发服务器。
npm start
未完待续。。