如何不依赖 Webpack 编译 Vue 单文件组件

vueify 体验记录

Posted by Nicodechal on 2018-04-01

起因

通常编译 Vue 的单文件组件时都会使用 vue-loader ,而要使用 vue-loader 就需要在项目中引入 webpack 。
也许你不需要或不想使用 webpack ,但遇到了需要将 Vue 的单文件组件 (*.vue 文件) 转换为普通 js 模块 (*.js 文件) 的情况,此时可以尝试使用 vueify

使用 vueify 编译

vueify 是一个提供给 Browserify 的转换器,可以对 Vue 组件进行转换,同时提供了编译接口可以对 Vue 的单文件组件直接进行编译 (实际上,这套编译接口本来属于 vue-component-compiler 这个库,但是被整合到了这里,同时现在 vue-component-compiler 已经废弃)

安装 vueify

1
2
yarn add vueify #使用yarn
npm install vueify --save-dev #使用npm

vueify 用法

首先需要从 vueify 中取出编译器:

1
const compiler = require('vueify').compiler

之后调用 compiler 的 compile 方法即可进行编译

1
2
3
compiler.compile(fileContent, filePath, function (err, result) {
// result is a common js module string
})

该方法有三个参数:

  1. fileContent: 需要编译的内容的字符串
  2. filePath:文件路径,默认是当前文件夹,需要写绝对路径
  3. callback函数:在编译完成后执行,result是编译结果的字符串

使用 vueify 实例

对于文件 counter.vue :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div>
{{ count }}
<button @click="increment">自增</button>
</div>
</template>

<script lang="babel">
export default {
data () {
return {
count: 0
}
},

methods: {
increment () {
this.count++
}
}
}
</script>

使用下面代码转换为 counter.js :

1
2
3
4
5
6
7
8
const compiler = require('vueify').compiler //通过 vueify 的 compiler 取出编译器
const fs = require('fs')

const content = fs.readFileSync('counter.vue').toString() //使用某种方法读出内容读出文件内容

compiler.compile(content, '/path/..', function(err, res) {
fs.writeFileSync('counter.js', res) //用某种方法写出
})

编译后的文件可以通过这种方式使用:

1
import Counter from './counter.js'

需要注意的

使用 vueify 时,如果要编译 es6 的代码,需要使用 babel ,上面的例子中,使用了 <script lang="babel"> 这样的写法,这时候需要确保自己的项目中正确配置了 babel ,否则会报错。

另外,vueify 转换的单文件组件中的 <style> 中的内容,是通过 require('vueify/lib/insert-css').insert('..style content here..') 引入js文件的,所以如果要运行转换过的文件,需要确保项目中已经安装了 vueify (通常都应该已经安装了,毕竟刚用了它编译) 。