安装webpack
-
初始化环境,引入package.json
npm init -y
-
安装webpack
npm i webpack -g
-
安装webpack-cli
npm i webpack-cli -g
-
创建
index.html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--加这个-->
<div id="app"></div>
<script src="./dist/bundle.js"></script>
<!--加这个-->
</body>
</html>
- 创建
main.js
const show = require('./show');
show('tail');
- 创建
show.js
文件
function show(content) {
window.document.getElementById('app').innerText = 'hello ' + content;
}
module.exports = show;
- 创建
webpack.config.js
文件
const path = require('path');
module.exports = {
entry: './main.js',
output: {
// 将所有依赖的模块合并输出到一个 bundle.js 文件
filename: 'bundle.js',
// 将输出文件都放在 dist 目录下
path: path.resolve(__dirname,'./dist'),
}
}
-
目录结构
–node_modules
–index.html
–main.js
–webpack.config.js
–show.js
–package.json
-
运行
webpack --config webpack.config.js
生成了一个dist/bundle.js
Loader
引入css
- 创建
main.css
#app {
text-align: center;
}
- 修改
main.js
require('./main.css');
const show = require('./show.js');
show('tail');
- 修改
webpack.config.js
const path = require('path');
module.exports = {
entry: './main.js',
output: {
// 将所有依赖的模块合并输出到一个 bundle.js 文件
filename: 'bundle.js',
// 将输出文件都放在 dist 目录下
path: path.resolve(__dirname,'./dist'),
},
module: {
rules: [
{
// 用正则表达式去匹配要用该Loader转换的css文件
test: /\.css$/,
use:['style-loader','css-loader'],
}
]
}
}
- 运行
webpack --config webpack.config.js