这次给大家带来parcel.js+vue 2.x快速配置打包的方法,parcel.js+vue 2.x快速配置打包的注意事项有哪些,下面就是实战案例,一起来看一下。
继 browserify、webpack 之后,又一款打包工具 parcel 横空出世
parcel.js 的官网有这样的自我介绍 “极速零配置web应用打包工具”
简单接触了一下,单从效率上来说,确实要比 webpack 强上不少,可坑也挺多,未来升级之后应该会逐渐普及
官方文档:https://parceljs.org/getting_started.html
官方 github:https://github.com/parcel-bundler/parcel
一、基本用法
parcel 可以用 npm 或 yarn 安装,个人习惯用 npm,这篇博客将基于 npm 讲解
首先需要全局安装 parcel.js // 当前版本 1.3.0
npm install -g parcel-bundler
然后写一个配置文件...不对,这不是 webpack,这是 parcel, 零配置打包
直接创建项目目录,用写个一个简单的传统页面
然后在项目根目录打开命令行工具,输入以下命令
parcel index.html -p 3030
然后在浏览器中打开 http://localhost:3030/ 就能打开刚才开发的页面
上面的命令中 -p 用于设置端口号,如果不设置,则默认启动 1234 端口
parcel 支持热更新,会监听 html、css、js 的改变并即时渲染
// 实际上通过 src 引入的 css、js 无法热更新
开发完成后,输入以下命令进行打包
parcel build index.html
打包后会生成 dist 目录
桥豆麻袋,说好的打包呢?怎么还是这么多文件?
骚年莫急,这是用传统写法写的页面,连 package.json 都没有,接下来改造成模块化的项目,就能看到打包的效果了
好吧,那我先手动打开 index.html 看看效果...等等...为啥 css 没被加载?
这是因为打包后的路径都是绝对路径,放在服务器上没问题,如果需要本地打开,就得手动修改为相对路径
二、应用在模块化项目中
正片开始,首先将上面的项目改造成模块化项目
通过 npm init -y 命令创建一个默认的 package.json,并修改启动和打包命令
这样就可以直接通过 npm run dev 启动项目,npm run build 执行打包了
之前是全局安装的 parcel,实战中更推荐在项目中添加依赖
npm install parcel-bundler -s
上面是一个传统页面,使用 link 引入的 css
既然要改造为模块化项目,那就只需要引入一个 main.js,然后在 main.js 中引入其他的 css 和 js 文件
所以需要用到 import 等 es6 语法,那就安装一个 babel 吧
npm install babel-preset-env -s
然后在根目录创建一个 .babelrc 文件,添加以下配置:
{
presets: [env]
}
再安装一个 css 转换工具,比如 autoprefixer
npm install postcss-modules autoprefixer -s
创建 .postcssrc 文件:
{
modules: true,
plugins: {
autoprefixer: {
grid: true
}
}
}
官方文档还推荐了一款编译 html 资源的插件 posthtml,不过这里暂时不需要
自行改造代码,最后 npm run build 打包
可以看到 js 和 css 已经整合,其内容也经过了 babel 和 autoprefixer 的编译
三、在 vue 项目中使用 parcel
官方文档给出了适用于 react 项目的配方
但我常用的是 vue,研究了好久,终于找到了方法
依旧使用 index.html 作为入口,以 script 引入 main.js:
<!-- index.html -->
<body>
<p id="app"></p>
<script src="./src/main.js"></script>
</body>
// main.js
import 'babel-polyfill'
import vue from 'vue'
import app from './app.vue'
import router from './router'
import './css/common.css'
vue.config.productiontip = false
const vm = new vue({
el: '#app',
router,
render: h => h(app)
})
这里要推荐一个很厉害的插件 parcel-plugin-vue,它让 parcel 和 vue 成功牵手
再加上之前提到的 babel、autoprefixer,最后的 package.json 是这样的:
{
name: parcelvue,
version: 1.0.0,
description: the project of parcel & vue created by wise wrong,
main: main.js,
scripts: {
dev: parcel index.html -p 3030,
build: parcel build index.html
},
keywords: [
parcel,
vue
],
author: wisewrong,
license: isc,
devdependencies: {
autoprefixer: ^7.2.3,
babel-polyfill: ^6.26.0,
babel-preset-env: ^1.6.1,
parcel-bundler: ^1.3.0,
parcel-plugin-vue: ^1.4.0,
postcss-modules: ^1.1.0,
vue-loader: ^13.6.1,
vue-style-loader: ^3.0.3,
vue-template-compiler: ^2.5.13
},
dependencies: {
vue: ^2.5.13,
vue-router: ^3.0.1
}
}
一定记得在根目录创建 .postcssrc 和 .babelrc 文件
然后 npm install 安装依赖, npm run dev 启动项目,npm run build 打包项目
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
怎么提速优化vue-cli的代码
html+js实现滚动数字的时钟
以上就是parcel.js+vue 2.x快速配置打包的方法的详细内容。