-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (58 loc) · 2.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
const {Transform} = require('stream');
const PluginError = require('plugin-error');
const path = require('path');
const {createDefaultCompiler, assemble} = require('@vue/component-compiler');
const applySourceMap = require('vinyl-sourcemaps-apply');
const PLUGIN_NAME = 'vue-file';
module.exports = function (opts) {
// compiler options
const {script, style, template, resolve,
// assemble options
normalizer, styleInjector, styleInjectorSSR} = opts || {};
const vueCompiler = createDefaultCompiler({script, style, template, resolve});
return new Transform({
objectMode: true,
transform: function(file, enc, cb) {
if (file.isStream()) {
this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming is not supported'));
return;
}
if (file.isBuffer()) {
if (file.extname === '.vue') {
const content = file.contents.toString();
// need to use localPath instead of file.relative (relative to file.base)
// as vue compiler needs the path to be related to process.cwd() in order
// for additional resources locating.
const localPath = path.relative(file.cwd, file.path);
const result = assemble(
vueCompiler,
localPath,
vueCompiler.compileToDescriptor(localPath, content),
{normalizer, styleInjector, styleInjectorSSR}
);
file.extname = '.js';
file.contents = Buffer.from(result.code);
const {map} = result;
if (file.sourceMap) {
// With .vue file only contains <template> node,
// @vue/component-compiler doesn't insert sourcesContent.
// I don't quite understand.
if (!map.sourcesContent) map.sourcesContent = [content];
// Normalize file path to relative to base.
// This is to match the default behaviour of gulp source map.
map.sources = map.sources.map(f =>
normalize(path.relative(file.base, path.resolve(file.cwd, f)))
);
map.file = normalize(file.relative);
applySourceMap(file, map);
}
}
}
cb(null, file);
}
});
};
function normalize(path) {
return path.replace(/\\/g, '/');
}