首先最好了解一下webpack的原理和优点,网上很多文章都有很详细的相关介绍,推荐 webpack概念,这里就不提了,这里只是通过一个demo展示一下webpack的使用效果
站点结构如下
---root
---dist
---index.html
---src
---index.js
---hello.js
index.html
<!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>Document</title>
</head>
<body>
<div id='root'>
</div>
<script src="bundle.js"></script>
</body>
</html>
hello.js
module.exports = function() {
alert("hello")
};
index.js
const hello = require('./hello.js');
hello()
创建命令
npm init
执行命令之后新增文件package.json,此时站点结构:
---root
---dist
---index.html
---src
---index.js
---hello.js
---package.json
package.json文件(一切都默认就可以)
{
"name": "test1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
}
}
安装命令
npm install --save-dev webpack
执行命令之后新增文件夹node_modules, 此时站点结构:
---root
---dist
---index.html
---src
---index.js
---hello.js
---package.json
---node_modules
package.json文件(新增webpack结点)
{
"name": "test1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.8.1" //新增结点
}
}
目前只是找到手动创建方式,手动创建webpack.config.js文件之后,站点结构:
---root
---dist
---index.html
---src
---index.js
---hello.js
---package.json
---node_modules
---webpack.config.js
module.exports = {
entry: __dirname + "/src/index.js",
output:{
path:__dirname + "/dist/",
filename:"bundle.js"
}
}
entry:是打包文件入口
output:是打包的文件所在的地方和文件名
配置的含义:通过入口文件将文件打包成bundle.js,然后放在dist文件夹下面
package.json文件
{
"name": "test1",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack"
},
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^3.8.1"
}
}
scripts结点下面添加“start”属性
在终端运行npm start命令,新生成bundle.js,文件结构
---root
---dist
---index.html
---bundle.js
---src
---index.js
---hello.js
---package.json
---node_modules
---webpack.config.js