Skip to content

Commit

Permalink
refactor: optimized code
Browse files Browse the repository at this point in the history
  • Loading branch information
tikazyq committed Jun 24, 2024
1 parent 7ea23d5 commit a8de38e
Show file tree
Hide file tree
Showing 34 changed files with 1,002 additions and 977 deletions.
173 changes: 87 additions & 86 deletions scripts/gen-dts.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import path from 'path'
import fs from 'fs'
import {Project} from 'ts-morph'
import vueCompiler from '@vue/compiler-sfc'
import klawSync from 'klaw-sync'
import chalk from 'chalk'
import path from 'path';
import fs from 'fs';
import { Project } from 'ts-morph';
import vueCompiler from '@vue/compiler-sfc';
import klawSync from 'klaw-sync';
import chalk from 'chalk';

import {dirname} from 'path';
import {fileURLToPath} from 'url';
import { dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));

const TSCONFIG_PATH = path.resolve(__dirname, '../tsconfig.dts.json')
const DEMO_RE = /\/demo\/\w+\.vue$/
const TEST_RE = /__test__|__tests__/
const TSCONFIG_PATH = path.resolve(__dirname, '../tsconfig.dts.json');
const DEMO_RE = /\/demo\/\w+\.vue$/;
const TEST_RE = /__test__|__tests__/;
const excludedFiles = [
'mock',
'package.json',
Expand All @@ -21,18 +21,18 @@ const excludedFiles = [
'tests',
'css',
'.DS_Store',
]
const includedFiles = [
'.vue',
'.ts',
]
const exclude = (path) => !excludedFiles.some(f => path.includes(f))
const include = (path) => includedFiles.some(f => path.includes(f))
];
const includedFiles = ['.vue', '.ts'];
const exclude = path => !excludedFiles.some(f => path.includes(f));
const include = path => includedFiles.some(f => path.includes(f));

/**
* fork = require( https://github.com/egoist/vue-dts-gen/blob/main/src/index.ts
*/
const genVueTypes = async (root, outDir = path.resolve(__dirname, '../typings')) => {
const genVueTypes = async (
root,
outDir = path.resolve(__dirname, '../typings')
) => {
const options = {
compilerOptions: {
allowJs: true,
Expand All @@ -42,21 +42,17 @@ const genVueTypes = async (root, outDir = path.resolve(__dirname, '../typings'))
noEmitOnError: false,
outDir,
paths: {
'@': [
path.resolve(__dirname, '../src')
],
'@/*': [
path.resolve(__dirname, '../src/*')
]
'@': [path.resolve(__dirname, '../src')],
'@/*': [path.resolve(__dirname, '../src/*')],
},
skipLibCheck: true,
},
tsConfigFilePath: TSCONFIG_PATH,
skipAddingFilesFromTsConfig: true,
}
const project = new Project(options)
};
const project = new Project(options);

const sourceFiles = []
const sourceFiles = [];

const filePaths = klawSync(root, {
nodir: true,
Expand All @@ -65,94 +61,99 @@ const genVueTypes = async (root, outDir = path.resolve(__dirname, '../typings'))
.filter(path => !DEMO_RE.test(path))
.filter(path => !TEST_RE.test(path))
.filter(exclude)
.filter(include)
.filter(include);

await Promise.all(
filePaths.map(async file => {
const fileName = file.replace(root + '/', '')

if (file.endsWith('.vue')) {
// .vue file
const content = await fs.promises.readFile(file, 'utf-8')
const sfc = vueCompiler.parse(content)
const {script, scriptSetup} = sfc.descriptor
if (script || scriptSetup) {
let content = ''
let isTS = false
if (script && script.content) {
content += script.content
if (script.lang === 'ts') isTS = true
}
if (scriptSetup) {
const compiled = vueCompiler.compileScript(sfc.descriptor, {
id: 'xxx',
})
content += compiled.content
if (scriptSetup.lang === 'ts') isTS = true
try {
if (file.endsWith('.vue')) {
// .vue file
const content = await fs.promises.readFile(file, 'utf-8');
const sfc = vueCompiler.parse(content);
const { script, scriptSetup } = sfc.descriptor;
if (script || scriptSetup) {
let content = '';
let isTS = false;
if (script && script.content) {
content += script.content;
if (script.lang === 'ts') isTS = true;
}
if (scriptSetup) {
const compiled = vueCompiler.compileScript(sfc.descriptor, {
id: 'xxx',
});
content += compiled.content;
if (scriptSetup.lang === 'ts') isTS = true;
}
const sourceFile = project.createSourceFile(
path.relative(process.cwd(), file) + (isTS ? '.ts' : '.js'),
content
);
sourceFiles.push(sourceFile);
}
const sourceFile = project.createSourceFile(
path.relative(process.cwd(), file) + (isTS ? '.ts' : '.js'),
content,
)
sourceFiles.push(sourceFile)
} else if (file.endsWith('.ts')) {
// .ts file
const sourceFile = project.addSourceFileAtPath(file);
sourceFiles.push(sourceFile);
}
} else if (file.endsWith('.ts')) {
// .ts file
const sourceFile = project.addSourceFileAtPath(file)
sourceFiles.push(sourceFile)
} catch (e) {
console.error(e);
throw e;
}
}),
)
})
);

const diagnostics = project.getPreEmitDiagnostics()
const diagnostics = project.getPreEmitDiagnostics();

console.log(project.formatDiagnosticsWithColorAndContext(diagnostics))
console.log(project.formatDiagnosticsWithColorAndContext(diagnostics));

await project.emit({
emitOnlyDtsFiles: true,
})
});

// iterate source files
for (const sourceFile of sourceFiles) {
const emitOutput = sourceFile.getEmitOutput()
const outputFiles = emitOutput.getOutputFiles()
console.log(chalk.yellow(`Generating definition for file: ${chalk.bold(sourceFile.getBaseName())} (${outputFiles.length})`))
const emitOutput = sourceFile.getEmitOutput();
const outputFiles = emitOutput.getOutputFiles();
console.log(
chalk.yellow(
`Generating definition for file: ${chalk.bold(sourceFile.getBaseName())} (${outputFiles.length})`
)
);

for (const outputFile of outputFiles) {
const filepath = outputFile.getFilePath()
const filepath = outputFile.getFilePath();

await fs.promises.mkdir(path.dirname(filepath), {
recursive: true,
})
});

await fs.promises.writeFile(filepath,
outputFile
.getText(),
'utf8')
await fs.promises.writeFile(filepath, outputFile.getText(), 'utf8');
console.log(
chalk.green(
'Definition for file: ' +
chalk.bold(
sourceFile.getBaseName(),
) +
' generated',
),
)
chalk.bold(sourceFile.getBaseName()) +
' generated'
)
);
}
}

// export interfaces in typings/index.d.ts
const idxFilePath = path.resolve(__dirname, '../typings/index.d.ts')
const idxFilePath = path.resolve(__dirname, '../typings/index.d.ts');
if (fs.existsSync(idxFilePath)) {
let fileContent = fs.readFileSync(idxFilePath)
const exportInterfacesLine = 'export * from \'./interfaces\';'
let fileContent = fs.readFileSync(idxFilePath);
const exportInterfacesLine = "export * from './interfaces';";
if (!fileContent.includes(exportInterfacesLine)) {
fileContent = exportInterfacesLine + '\n' + fileContent
fileContent = exportInterfacesLine + '\n' + fileContent;
}
fs.writeFileSync(idxFilePath, fileContent)
fs.writeFileSync(idxFilePath, fileContent);
}
}
};

(async function () {
await genVueTypes(path.resolve(__dirname, '../src'), path.resolve(__dirname, '../typings'))
})()
await genVueTypes(
path.resolve(__dirname, '../src'),
path.resolve(__dirname, '../typings')
);
})();
17 changes: 16 additions & 1 deletion src/components/button/Button.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
<script setup lang="ts">
defineOptions({ name: 'ClButton' });
import { computed } from 'vue';
import { ButtonProps } from '@/components/button/button';
interface ButtonProps {
tooltip?: string;
type?: BasicType;
size?: BasicSize;
round?: boolean;
circle?: boolean;
plain?: boolean;
disabled?: boolean;
isIcon?: boolean;
loading?: boolean;
onClick?: () => void;
className?: string;
id?: string;
noMargin?: boolean;
}
const props = withDefaults(defineProps<ButtonProps>(), {
type: 'primary',
Expand Down
19 changes: 17 additions & 2 deletions src/components/button/FaIconButton.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
<script setup lang="ts">
defineOptions({ name: 'ClFaIconButton' });
import { computed } from 'vue';
import { ButtonProps } from '@/components/button/button';
interface ButtonProps {
tooltip?: string;
type?: BasicType;
size?: BasicSize;
round?: boolean;
circle?: boolean;
plain?: boolean;
disabled?: boolean;
isIcon?: boolean;
loading?: boolean;
onClick?: () => void;
className?: string;
id?: string;
noMargin?: boolean;
}
const props = defineProps<
ButtonProps & {
Expand Down Expand Up @@ -35,7 +50,7 @@ const cls = computed<string>(() => {
is-icon
:id="id"
:class-name="cls"
@click="event => emit('click', event)"
@click="(event: Event) => emit('click', event)"
>
<cl-icon :icon="icon" :spin="spin" />
<div v-if="badgeIcon" class="badge-icon">
Expand Down
17 changes: 16 additions & 1 deletion src/components/button/IconButton.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
<script setup lang="ts">
defineOptions({ name: 'ClIconButton' });
import { ButtonProps } from '@/components/button/button';
interface ButtonProps {
tooltip?: string;
type?: BasicType;
size?: BasicSize;
round?: boolean;
circle?: boolean;
plain?: boolean;
disabled?: boolean;
isIcon?: boolean;
loading?: boolean;
onClick?: () => void;
className?: string;
id?: string;
noMargin?: boolean;
}
defineProps<
ButtonProps & {
Expand Down
17 changes: 16 additions & 1 deletion src/components/button/LabelButton.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
<script setup lang="ts">
defineOptions({ name: 'ClLabelButton' });
import { ButtonProps } from '@/components/button/button';
interface ButtonProps {
tooltip?: string;
type?: BasicType;
size?: BasicSize;
round?: boolean;
circle?: boolean;
plain?: boolean;
disabled?: boolean;
isIcon?: boolean;
loading?: boolean;
onClick?: () => void;
className?: string;
id?: string;
noMargin?: boolean;
}
defineProps<
ButtonProps & {
Expand Down
2 changes: 1 addition & 1 deletion src/components/chart/LineChart.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { computed, onMounted, onUnmounted, ref, watch, StyleValue } from 'vue';
import { init } from 'echarts';
import { translate } from '@/utils/i18n';
export interface LineChartProps {
interface LineChartProps {
config: EChartsConfig;
width?: string;
height?: string;
Expand Down
11 changes: 10 additions & 1 deletion src/components/chart/MetricLineChart.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@
defineOptions({ name: 'ClMetricLineChart' });
import { computed } from 'vue';
import { plainClone } from '@/utils/object';
import { LineChartProps } from '@/components/chart/LineChart.vue';
interface LineChartProps {
config: EChartsConfig;
width?: string;
height?: string;
theme?: string;
labelKey?: string;
valueKey?: string;
isTimeSeries?: boolean;
}
const props = defineProps<
LineChartProps & {
Expand Down
2 changes: 1 addition & 1 deletion src/components/context-menu/ContextMenu.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
defineOptions({ name: 'ClContextMenu' });
import { ClickOutside as vClickOutside } from 'element-plus';
export interface ContextMenuProps {
interface ContextMenuProps {
visible?: boolean;
placement: string;
clicking?: boolean;
Expand Down
2 changes: 1 addition & 1 deletion src/components/context-menu/ContextMenuList.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<script setup lang="ts">
defineOptions({ name: 'ClContextMenuList' });
export interface ContextMenuItem {
interface ContextMenuItem {
title: string;
icon?: Icon;
action?: () => void;
Expand Down
Loading

0 comments on commit a8de38e

Please sign in to comment.