0%

webpack学习笔记

webpack入门完整demo

安装webpack

1
2
3
mkdir mywp && cd mywp
npm init -y
npm install webpack webpack-cli --save-dev --registry=https://registry.npm.taobao.org

安装Lodashio

lodash是一个一致性、模块化、高性能的 JavaScript 实用工具库。官网: https://www.lodashjs.com/

用来写简单示例

目录结构及文件

1
2
3
4
5
6
7
8
9
10
webpack-demo
|- package.json
|- webpack.config.js
|- /dist
|- bundle.js
|- index.html
|- /src
  |- style.css
|- index.js
|- /node_modules

新建src/index.js:

1
2
3
4
5
6
7
8
9
10
import _ from 'lodash';

function createDomElement() {
var dom = document.createElement('div');
dom.innerHTML = _.join(['aicoder', '.com', ' wow'], '');
dom.className = 'hello';
return dom;
}

document.body.appendChild(createDomElement());

新建dist/index.html

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>起步</title>
</head>
<body>
<script src="./main.js"></script>
</body>
</html>

新建src/style.css

1
2
3
.hello {
color: red;
}

新建 webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const path = require('path');

module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
};

执行webpack命令

当前目录执行

1
npx webpack

查看结果

dist 文件夹中应该生成了main.js,打开index.html看到效果