webpack基本原理(1)

概念

本质上,webpack是一个现代JavaScript应用程序的静态块打包器(module bundler)
当webpack处理应用程序时,它会递归地构建一个依赖关系图(dependency graph),其中包含应用程序需要的每个模块,然后将所有这些模块打包成一个或多个bundle

安装

确保安装了nodejs
项目文件环境

cd mypack
//进入你的项目目录 mypack目录可自由创建
npm init
//初始化项目文件夹 会创建一个package.js

本地安装

npm install --save-dev webpack
npm install --save-dev webpack-cli

对于大多数项目,建议选择本地安装

准备文件

-- dist 文件生成目录
---- index.html 

-- index.js 主入口文件
----header.js 需要被index引入的文件
# index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>第一个webpack页面</title>
</head>
<body>
	<script src="main.js"></script>
</body>
</html>	
<!--打包好的js名称默认是main.js-->

# index.js
import {header} from './header.js'
document.body.append(header);

# header.js
var header = ducument.createElement("div");
header.innerHTMl = '你好webpack from header';
export {header};

执行命令 打开index.html

npx webpack index.js
//在你的项目目录执行 这里的名称是 mypack

然后打开你的dist/index.html 查看网页文件
同事你会发现在dist目录多个main.js这个打包生成好的js文件

使用配置文件

在项目目录 新建一个webpack.config.js webpack默认配置文件

const path = require('path')
//引入node的 path路径模块
module.exports={
	entry:'./index.js',
	//指定文件的入口
	output:{
		filename:'main.js',
		//定义文件名
		path:path.resolve(__dirname,'dist')
		//定义文件夹
		//__dirname获取当前目录
		//path.resolve方法将路径或路径的序列解析为绝对路径
	}
	//制定打包好的出口
}
//module.export node中导出模块的意思
# 以下为纯净版本
const path = require('path')
module.exports={
	entry:'./index.js',
	output:{
		filename:'main.js'
		path:path.resolve(__dirname,'dist')
	}
	
}

执行命令npx webpack 实现打包

配置scripts
找到package.js配置scripts

"scripts":{
	start:"webpack"
}

这样我们就可以执行

npm run start
//yarn start

配置模式

const path = require('path')
module.exports = {
	mode:'development',//开发模式
	//mode:'production',//产品模式
	entry:'./index.js',
	output:{
		filename:'main.js',
		path:path.resolve(__dirname,'dist')
	}
}

产品模式打包的大小要被生产模式要小的多

"scripts":{
	"dev":"webpack --mode developnment"
	"build":"webpack --mode production"
},

核心概念

  • 入口(entry)
  • 输出(output)
发布了16 篇原创文章 · 获赞 9 · 访问量 275

猜你喜欢

转载自blog.csdn.net/webblock/article/details/105254646