webpack 教程一 安装和基本配置
webpack 中文文档:http://www.css88.com/doc/webpack2/guides/code-splitting-require/
1. 新建目录webpack/,新建index.js 和 index.html
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
index.js
var app = document.getElementById('app');
app.innerHTML = 'hello world';
2. npm init 初始化 package.json,package.json name字段不可以叫webpack 改成其他
3. npm view webpack version 查看最新版本, npm install webapck@2.2.1 --save-dev
4. 执行命令 ./node_modules/webpack/bin/webpack.js ./index.js bundle.js
根目录下会生成一个bundle.js 文件
5.将html中引入的index.js 改成 bundle.js 保存,刷新浏览器
另一种方法:
1. 编辑package.json scripts字段
"scripts": {
"build": "webpack index.js bundle.js"
},
与执行./node_modules/webpack/bin/webpack.js ./index.js bundle.js 同理
2. 删掉bundle.js 并执行命令 npm run build
npm run 执行 scripts 字段
自动删除bundle.js ,并执行打包命令,生成新的bundle.js:
1. npm install rimraf --save-dev
rimraf 插件 like "rm -rf"
2. 修改package.json scripts 字段:
"scripts": {
"build": "rimraf bundle.js && webpack index.js bundle.js"
},
先删除 bundle.js 然后打包
okkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk!
让项目更正规一些,还需要一些简单操作:
1. 创建dist , src 目录, 将index.js移动到src下,
mkdir dist , mkdir src , mv index.js src
2. 删除bundle.js , rm -rf bundle.js
3. package.json scripts字段修改:
"scripts": {
"build": "rimraf dist && webpack src/index.js dist/bundle.js"
},
4. index.html 修改bundle.js -> dist/bundle.js
5. 执行 npm run build 查看是否生效

浙公网安备 33010602011771号