webpack 是目前最多人使用的前端打包工具, 但 webpack 功能强大, 导致配置比较复杂 (各种对应转换 loader, 各种插件等), 如果配置不合理还可能导致打包速度过慢.
最近出现了一款新的打包工具 Parcel, 受关注程度不亚于 Webpack. 下面就看下如何具体使用 Parcel.
快速上手
关于安装直接查看 官网 .
1. 文件引用
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="wrap">
<h1 id="title"></h1>
<p id="body"></p>
</div>
<script src="./index.js"></script>
</body>
</html>
这里通过 script 标签引入了 js 的入口文件.
index.js
const posts = require('./posts');
posts.fetchOnePost()
.then(post => {
document.getElementById('title').innerHTML = post.title;
document.getElementById('body').innerHTML = post.body;
})
这里通过 require() 导入当前目录下的 posts.js 文件.
posts.js
module.exports = {
fetchOnePost: function () {
return new Promise((resolve, reject) => {
fetch('http://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(data => {
resolve(data);
})
})
}
}
这里通过 fetch() 方法请求一个 json 数据, index.js 中通过调用该方法对数据进行显示.
命令行执行 $ parcel index.html, 就可以打包生成对应的 dist 文件了, 同时会自动启动一个 Server, 在
http://localhost:1234
看到结果.
dist 文件中会生成一个跟你的项目名称一样的 js 文件, 该 js 文件就是打包后的 js 文件了.
2. 内置转换器
Parcel 相比与 Webpack, 内置了很多常用的转换器, 不需要我们自己去安装和配置这些 loader(诸如 style-loader, CSS-loader 等). 而且还内置了 Babel, 也不需要我们安装 Babel 的各种东西了.
如将文件导入改成 es2015 形式:
index.js import {
posts
}
from './posts';
posts.js export const posts = {...
}
此时刷新
http://localhost:1234
仍然是正常显示的.
3. CSS 文件
CSS 中最常用的插件之一是 PostCSS, 这里不用像 Webpack 那样需要安装 PostCSS 了, Parcel 已经内置有了. 如果我们需要用到 PostCSS 的 autoprefixer 功能, 只需要安装 autoprefixer 插件并配置好. postcssrc 文件就可以了.
Parcel 在模块中找到配置文件 (例如 .babelrc ,.postcssrc) 时会自动运行并进行转换.
安装 PostCSS 插件 autoperfixer:
$ npm install autoprefixer
.postcssrc
{
"plugins": {
"autoprefixer" : true
}
}
style.css
h1 {
color: gray;
border: 1px solid red;
border-radius: 5px;
display: flex;
}
打包后的 css 文件:
dist / b032741df18dc4b3aeb571ee677c350f.css h1 {
color: gray;
border: 1px solid red;
border - radius: 5px;
display: -webkit - box;
display: -ms - flexbox;
display: flex;
}
可以看到浏览器前缀自动加上了. 此外还多出了一个同名的 js 文件
7963b20fc948f008b0e9fbc9750edbe8.js
. 这个应该就是 parcel 将 css 文件转成可导入的文件.
如果使用 scss, 则直接使用后缀为. scss 的 css 文件就可以了, parcel 会自动识别并转换. 记得别忘了把 index.html 中的 css 引入改成
<link rel="stylesheet" href="./style.scss">
4. 第三方模块
这里通过 npm 安装 jquery:
$ npm install jquery
, 然后在 index.js 中引入就可以使用了.
index.js
import { posts } from './posts';
import $ from 'jquery';
posts.fetchOnePost()
.then(post => {
$('#title').html(post.title);
$('#body').html(post.body);
})
5. 插件
官方文档中有说明, 插件统一用 parcel-plugin - 命名, 若要让 parcel 支持 vue 框架, 可以使用 parcel-plugin-vue 插件. 具体使用查看看 parcel-plugin-vue 的 npm .
总的来说, Parcel 确实比 Webpack 简单方便很多, 特别是省了各种转换器和插件的配置, 节省了大部分工作量. 不过从功能上来看目前 Parcel 还不及 Webpack, 如反向代理设置等, 相信随着使用 Parcel 的人越来越多, 对应的插件也会随之开发出来.
来源: https://juejin.im/post/5a6c82db518825733d694d61