概念
本质上,webpack 是一个用于现代 JavaScript 应用程序的 静态模块打包工具。当 webpack 处理应用程序时,它会在内部从一个或多个入口点构建一个 依赖图(dependency graph),然后将你项目中所需的每一个模块组合成一个或多个 bundles,它们均为静态资源,用于展示你的内容。
安装
使用cmd(最好是使用管理员身份运行)打开命令提示符,使用(前提拥有nmp)
npm install webpack -g
和
npm install webpack-cli -g
进行安装,安装完成后使用
webpack -v
可以查看版本号。
使用
新建一个文件件。在idea中打开此文件夹 ,创建这样的文件夹格式
1.hello.js: 可以定义多个方法
//暴露一个方法
exports.sayhi = function () {
document.write("<h1>666</h1>")
}
exports.sayhi2 = function () {
document.write("<h1>666</h1>")
}
exports.sayhi3 = function () {
document.write("<h1>666</h1>")
}
exports.sayhi4 = function () {
document.write("<h1>666</h1>")
}
2.main.js:
var hello = require("./hello");//调动hello文件夹成为hello对象
hello.sayhi();//调用sayhi()方法
3.webpack.config.js(必须这样命名):
module.exports = {
entry:'./modules/main.js',//程序入口
output:{
filename:"./js/bundle.js"//打包到哪里
}
}
4.使用webpack进行打包,成功后会有一个dist文件夹被新建
打包的代码就存放于bundle.js中
5.测试打包代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
<!--前端模块化开发-->
<script src="dist/js/bundle.js"></script>
运行此html会输出