1. 初体验
很乱,数不清的配置
2. 安装
创建目录
1
2
3mkdir webpack-demo
cd webpack-demo
npm init //创建一个package.jsoncopy Github上webpack官网的文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22//安装webpack
npm install --save-dev webpack
//配置
touch webpack.config.js
vi webpack.config.js
//在里面写以下内容
/*
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};*/
//创建文件
touch src/index.js
//运行webpack
npx webpack //这时会多出dist目录,里面有bundle.js文件
3. 使用
在index.js里写
1
2
3
4
5
6console.log(1)
//再运行webpack:
npx webpack
//再看bundle.js,这时会多出来一行console.log(1)安装babel-loader自动转换es6,我用的是 7.x branch for docs with Babel v6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43//安装v6,命令行
npm install babel-loader babel-core babel-preset-env webpack
//将这个复制到webpack的配置文件webpack.config.js里,加在output的下面
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
//加在output的下面,复制完后成这样
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}
]
}
};
运行npx webpack
若出现can't find '...'
或can't resolve '...'
的报错,则安装省略号里的东西npm i '省略号'
注意:若是Couldn't find preset "env"
,不要安装env,而是npm i babel-preset-env
- 使用babel
1
2
3//当你在写index.js里写
let a=1
//它就会帮你自动转换成es5了
3. 总结
太乱了太多配置了,希望parcel赶快升级替换掉webpack