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的人越来越多,对应的插件也会随之开发出来。