前言
- 本文采用cnpm去安装模块,在国内的网络环境比npm好用,具体请自行查找cnpm的安装方法
- 本文采用分步引导安装,建议不要跳过操作,成功率99%
- 本文只安装基本的es6开发环境,足够日常的普通开发,点到即止,后期需要用到其他模块可自行扩展
1.初始化npm
npm init
一直按回车就好
2.安装webpack核心包
cnpm install webpack webpack-cli --save-dev
3.根目录下新建 webpack.dev.config.js
写基本配置(入口和输出):
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
}
}
4.修改package.json里的命令
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "webpack --config ./webpack.dev.config.js --mode development"
},
添加了dev命令,指定webpack的配置文件,以及指定了mode为development开发模式
5.测试命令
先在src里的index.js里随便写几行js代码,然后打开命令行工具,进入项目,运行:
npm run dev
至此没有报错一般是ok的了
6.安装浏览器测试的插件
cnpm install webpack-dev-server html-webpack-plugin --save-dev
然后在根目录下新建个index.html文件,作为备用模板,简单内容如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>webpack开发环境安装</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
7.修改webpack.dev.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
},
plugins:[
new HtmlWebpackPlugin({
template:'./index.html'
})
],
devServer:{
contentBase: path.join(__dirname,'./release'),
open:true,
port:9000
}
}
HtmlWebpackPlugin配置里填写注入的模板地址
devServer配置里填写服务器解释的根目录地址,指定端口9000,指定open为自动打开。
8.修改package.json里的dev命令
"dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
9.测试命令
假如你在index.js里填写alert(666),这时候在命令行输入:
npm run dev
以上步骤都没错的情况下,浏览器会自动打开index.html,并弹出666。至此js注入到模板里并解释成功。
10.安装babel环境
cnpm install babel-loader babel-core babel-preset-env --save-dev
11.新建.babelrc文件
在项目根目录下新建.babelrc文件,里面只需输入"babel"属性的值即可:
{
"presets": ["env"]
}
12.在webpack.dev.config.js里添加配置规则
module:{
rules:[
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
}
13.修改index.js,写入一些es6语法测试
class Person {
constructor(name){
this.name = name
}
getName(){
return this.name
}
}
let p = new Person('精神小伙')
alert(p.getName())
14.编译测试
命令行执行:
npm run dev
能正常弹出"精神小伙",到此,webpackage的es6开发环境安装完毕。
15.完整目录结构
|--src
|--index.js
|--release
|--bundle.js
index.html
package.json
webpack.dev.config.js
.babelrc
16.webpack.dev.config.js完整配置
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
filename: './release/bundle.js'
},
module:{
rules:[
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
plugins:[
new HtmlWebpackPlugin({
template:'./index.html'
})
],
devServer:{
contentBase: path.join(__dirname,'./release'),
open:true,
port:9000
}
}
PS.遇到问题
在执行最后一步时发现编译错误,根据错误提示,babel-core的版本是6.x的情况下,babel-loader需要安装7.x版本,而自动安装的是8.x版本(2020年5月测)。此时打开命令行工具重新单独安装babel-loader:
cnpm install babel-loader@7 --save-dev