1、创建目录初始化npm,并安装webpack和webpack-cli
mkdir webpack-demo && cd webpack-demo npm init -y npm install webpack webpack-cli --save-dev
2、工程目录更如下
webpack-demo
|- webpack.config.js // webpack配置文件
|- package.json
|- index.html // 新增html
|- /src // 新增src源代码文件夹
|- index.js // 新增js文件
3、修改webpack.config.js文件
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve('__dirname', 'dist')
}
}
4、修改package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
--"main": "index.js", //移除 main 入口。这可以防止意外发布你的代码。
"private": true, // 确保我们安装包是私有的
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack" // npm run build 运行webpack脚本
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.32.0",
"webpack-cli": "^3.3.2"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
5、dist路径下放入index.html
<!doctype html>
<html>
<head>
<title>起步</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
6、修改index.js文件
const _ = require('lodash');
function component() {
var element = document.createElement('div');
element.innerHTML = _.join(['Hello', 'webpack'], '--');
return element;
}
document.body.appendChild(component());
7、运行npm run build编译工程,运行dist/index.html文件,显示运行结果
※需要按装lodash
npm install --save lodash