-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopen-vscode-initfn.js
58 lines (49 loc) · 1.62 KB
/
open-vscode-initfn.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
// path-to-your-custom-loader.js
const path = require('path');
const { getOptions } = require('loader-utils');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
// 初始化打开 vscode 的方法
const initOpenVscode = (loaderContext, source) => {
// Vue的变量名称
let vueVariableName = '';
// 解析 JavaScript 代码为 AST
const ast = parser.parse(source, {
sourceType: 'module',
plugins: ['jsx'],
});
// 遍历 AST
traverse(ast, {
ImportDeclaration(path) {
// 检查导入的模块是否为 'vue'
if (path.node.source.value === 'vue') {
// 获取导入的 Vue 变量名称
vueVariableName = path.node.specifiers[0].local.name;
}
},
});
source = `${source} \n
${vueVariableName}.prototype.$openVscode = function (path) { \n
window.open( \n
"vscode://file/" + path, "_self"\n
);\n
};\n `
return source;
}
module.exports = function (source) {
if (!source) {
return source;
}
const loaderContext = this;
const resourcePath = loaderContext.resourcePath;
const fileName = path.basename(resourcePath);
// 获取option 参数
const options = getOptions(loaderContext) || loaderContext.getOptions();
const bindOpenVscodeFile = options.bindOpenVscodeFile || 'main.js';
// debugger
// 初始化打开 vscode 的方法
if (fileName === bindOpenVscodeFile && !source.includes('$openVscode')) {
source = initOpenVscode(loaderContext, source,)
}
return source;
};