0%

webpack(一)--基础知识

来嗑打包工具

基础三连

  1. 是什么?
  2. 干什么?
  3. 怎么干?
  1. 是模块打包工具
  2. 打包模块,包括js、css静态文件等。
  3. 通过配置文件去配置

安装和基本操作

npm init

使这个项目符合node规范,可以用webpack来管理这个项目。它在项目中生成一个package.json文件。

1
2
3
4
5
6
[package.json]
{
...
+ 'private':true//表示是私人仓库,不会被发布到npm仓库中去
- 'main':'index.js' //向外暴露一个js文件以便被引用
}

安装webpack

npm install webpack webpack-cli -D -D=–save-dev

不推荐全局安装。不便于使用不同版本

npx:node提供的在项目内使用webpack命令。直接使用webpack命令时会从全局查找而报错。

3种运行webpack的方式

  1. global webpack index.js 不推荐,可能不同项目用的webpack版本不同。
  2. local npx webpack index.js 配置文件在webpack.config.js中配置。
  3. npm scripts 在package.json文件中添加配置,再用npm run bundle 即是2的效果
1
2
3
4
5
6
7
[package.json]
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"bundle": "wabpack"
//配置后可用npm run bubdle 代替npx wabpack,优先查找node_modules里安装的webpack

},

实际都是运行webpack命令,webpack-cli包就是能在命令行运行webpack命令。

When installing a package that will be bundled into your production bundle, you should use npm install --save. If you’re installing a package for development purposes (e.g. a linter, testing libraries, etc.) then you should use npm install --save-dev. More information can be found in the npm documentation.

打包输出的内容

image-20200629152904382

Asset:打包生成的js文件

size:文件大小

Chunks:入口文件的chunk id

Chunk Names:入口文件的Chunk name:

1
2
3
4
5
6
7
8
9
[webpack.config.js]
mudule.exports={
mode:'production'
enrty:'./src/index.js'
//是以下的简写
entry:{
main:'./src/index.js'
}
}

这个main就是默认的chunk name

缺少mode字段的wanning

image-20200629152758065

默认的mode是’production’。此时打包出的文件会被压缩(变成了1行)

这个提示会告诉你在配置文件中没有定义mode,但其实缺省时,webpack也会使用默认值。

mode:development时,代码就不会被压缩