使用 Parcel 和 NPM 脚本进行打包
Parcel
Parcel 是一个零配置的网页应用程序打包工具,主要用于快速构建现代 JavaScript 应用。
- 我们可以使用npm直接安装它
js
npm install --save-dev parcel
//这将把 Parcel 添加到 devDependencies 中,表明它是一个开发工具,而不是应用程序在运行时所需的依赖包。

- 使用npx运行parcel
js
npx parcel index.html
//这里的index.html是入口文件,因为我们的script.js就是由它来引入的


- 成功运行之后,会生成一个用于生产,也就是推送给用户的文件夹

- parcel支持热重载,一旦开发服务器启动,您在代码中所做的任何更改(如 JavaScript、CSS 或 HTML 文件)都会被 Parcel 自动检测到,并在浏览器中实时更新,无需手动刷新。
js
if (module.hot) {
module.hot.accept();
}
注:在 JavaScript 中,对象是通过引用传递的。如果您在使用 lodash
的深度复制方法时,只是复制了对象的引用,之后的修改会影响到原始对象和复制对象。这意味着如果您在热重载时更新了某个模块中的对象,而没有正确处理引用,可能会导致对象内容不断增加。所以如果这不是我们需要的,需要你手动的去初始化对象

- parcel也可以自动的将我们补全一些路径
js
// import cloneDeep from './node_modules/lodash-es/cloneDeep.js';
import cloneDeep from 'lodash-es'; //不需要写上面这么长的路径,parcel也可以自动的找到这个模块的功能;

使用npm脚本的方式启动parcel
使用 npm 脚本启动 Parcel 是一种常见的做法,可以简化开发和构建过程。
js
{
"name": "starter",
"version": "1.0.0",
"main": "clean.js",
"scripts": {
"start": "parcel index.html"
},
- 然后使用npm start或者npm run start启动parcel

- 一般我们也需要使用parcel来生产构建,
build
脚本将使用 Parcel 进行生产构建。
js
"scripts": {
"start": "parcel index.html",
"build": "parcel build index.html"
},

- 运行之后我们会发现一些文件被压缩了

- 注:我们也可以在全局安装parcel,只要在后面加-g参数即可,这样它就跟live-server一样,不管在哪个文件夹,我们始终可以使用它,但是在实际开发中,却不经常使用,因为实际项目中的开发一般都是独立更新和独立管理依赖的;