@varlet/cli 2.0.6 → 2.1.0-alpha.1667210582672

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.en-US.md +2 -2
  2. package/README.md +2 -2
  3. package/cjs/babel.config.cjs +29 -0
  4. package/cjs/babel.sfc.transform.cjs +18 -0
  5. package/cjs/jest.config.cjs +33 -0
  6. package/cjs/jest.media.mock.cjs +1 -0
  7. package/cjs/jest.style.mock.cjs +1 -0
  8. package/client.d.ts +1 -0
  9. package/client.js +1 -0
  10. package/lib/client/appType.d.ts +4 -0
  11. package/lib/client/appType.js +7 -0
  12. package/lib/client/index.d.ts +17 -0
  13. package/lib/client/index.js +106 -0
  14. package/lib/{bin.d.ts → node/bin.d.ts} +0 -0
  15. package/lib/node/bin.js +122 -0
  16. package/lib/{commands → node/commands}/build.d.ts +0 -0
  17. package/lib/node/commands/build.js +15 -0
  18. package/lib/{commands → node/commands}/changelog.d.ts +0 -0
  19. package/lib/node/commands/changelog.js +20 -0
  20. package/lib/{commands → node/commands}/commitLint.d.ts +0 -0
  21. package/lib/node/commands/commitLint.js +45 -0
  22. package/lib/{commands → node/commands}/compile.d.ts +0 -0
  23. package/lib/node/commands/compile.js +35 -0
  24. package/lib/{commands → node/commands}/create.d.ts +0 -0
  25. package/lib/node/commands/create.js +91 -0
  26. package/lib/{commands → node/commands}/dev.d.ts +0 -0
  27. package/lib/node/commands/dev.js +38 -0
  28. package/lib/{commands → node/commands}/gen.d.ts +0 -0
  29. package/lib/node/commands/gen.js +75 -0
  30. package/lib/{commands → node/commands}/jest.d.ts +0 -0
  31. package/lib/node/commands/jest.js +27 -0
  32. package/lib/{commands → node/commands}/lint.d.ts +0 -0
  33. package/lib/node/commands/lint.js +42 -0
  34. package/lib/{commands → node/commands}/preview.d.ts +0 -0
  35. package/lib/node/commands/preview.js +18 -0
  36. package/lib/{commands → node/commands}/release.d.ts +0 -0
  37. package/lib/node/commands/release.js +146 -0
  38. package/lib/{commands → node/commands}/vite.d.ts +0 -0
  39. package/lib/node/commands/vite.js +13 -0
  40. package/lib/{compiler → node/compiler}/compileModule.d.ts +0 -0
  41. package/lib/node/compiler/compileModule.js +74 -0
  42. package/lib/{compiler → node/compiler}/compileSFC.d.ts +0 -0
  43. package/lib/node/compiler/compileSFC.js +79 -0
  44. package/lib/{compiler → node/compiler}/compileScript.d.ts +1 -1
  45. package/lib/node/compiler/compileScript.js +141 -0
  46. package/lib/{compiler → node/compiler}/compileSiteEntry.d.ts +0 -0
  47. package/lib/node/compiler/compileSiteEntry.js +128 -0
  48. package/lib/{compiler → node/compiler}/compileStyle.d.ts +0 -0
  49. package/lib/node/compiler/compileStyle.js +39 -0
  50. package/lib/{compiler → node/compiler}/compileTemplateHighlight.d.ts +0 -0
  51. package/lib/node/compiler/compileTemplateHighlight.js +133 -0
  52. package/lib/{compiler → node/compiler}/compileTypes.d.ts +0 -0
  53. package/lib/node/compiler/compileTypes.js +45 -0
  54. package/lib/{config → node/config}/varlet.config.d.ts +5 -4
  55. package/lib/node/config/varlet.config.js +27 -0
  56. package/lib/node/config/varlet.default.config.d.ts +2 -0
  57. package/lib/node/config/varlet.default.config.js +264 -0
  58. package/lib/node/config/vite.config.d.ts +6 -0
  59. package/lib/node/config/vite.config.js +144 -0
  60. package/lib/node/index.d.ts +1 -0
  61. package/lib/node/index.js +1 -0
  62. package/lib/{shared → node/shared}/constant.d.ts +1 -2
  63. package/lib/node/shared/constant.js +47 -0
  64. package/lib/{shared → node/shared}/fsUtils.d.ts +1 -0
  65. package/lib/node/shared/fsUtils.js +48 -0
  66. package/lib/{shared → node/shared}/logger.d.ts +0 -0
  67. package/lib/node/shared/logger.js +18 -0
  68. package/package.json +22 -20
  69. package/{preset.js → preset.cjs} +1 -1
  70. package/site/components/code-example/CodeExample.vue +2 -1
  71. package/site/components/utils/components.ts +1 -4
  72. package/site/components/utils/elements.ts +1 -1
  73. package/site/mobile/App.vue +27 -26
  74. package/site/mobile/components/AppHome.vue +2 -1
  75. package/site/pc/App.vue +2 -1
  76. package/site/pc/Layout.vue +4 -3
  77. package/site/pc/components/AppHeader.vue +4 -2
  78. package/site/pc/pages/index/index.vue +8 -4
  79. package/site/useProgress.ts +2 -1
  80. package/site/utils.ts +6 -137
  81. package/template/create/index.ts.ejs +1 -1
  82. package/template/generators/config/default/base/{varlet.config.js → varlet.config.mjs} +2 -2
  83. package/template/generators/config/i18n/base/{varlet.config.js → varlet.config.mjs} +2 -2
  84. package/tsconfig.json +2 -9
  85. package/lib/bin.js +0 -102
  86. package/lib/commands/build.js +0 -67
  87. package/lib/commands/changelog.js +0 -27
  88. package/lib/commands/commitLint.js +0 -21
  89. package/lib/commands/compile.js +0 -119
  90. package/lib/commands/create.js +0 -166
  91. package/lib/commands/dev.js +0 -123
  92. package/lib/commands/gen.js +0 -138
  93. package/lib/commands/jest.js +0 -85
  94. package/lib/commands/lint.js +0 -123
  95. package/lib/commands/preview.js +0 -74
  96. package/lib/commands/release.js +0 -305
  97. package/lib/commands/vite.js +0 -69
  98. package/lib/compiler/compileModule.js +0 -190
  99. package/lib/compiler/compileSFC.js +0 -135
  100. package/lib/compiler/compileScript.js +0 -194
  101. package/lib/compiler/compileSiteEntry.js +0 -237
  102. package/lib/compiler/compileStyle.js +0 -91
  103. package/lib/compiler/compileTemplateHighlight.js +0 -193
  104. package/lib/compiler/compileTypes.js +0 -85
  105. package/lib/config/babel.config.d.ts +0 -2
  106. package/lib/config/babel.config.js +0 -31
  107. package/lib/config/babel.sfc.transform.d.ts +0 -1
  108. package/lib/config/babel.sfc.transform.js +0 -18
  109. package/lib/config/jest.config.d.ts +0 -1
  110. package/lib/config/jest.config.js +0 -37
  111. package/lib/config/jest.media.mock.d.ts +0 -0
  112. package/lib/config/jest.media.mock.js +0 -2
  113. package/lib/config/jest.style.mock.d.ts +0 -0
  114. package/lib/config/jest.style.mock.js +0 -2
  115. package/lib/config/varlet.config.js +0 -35
  116. package/lib/config/vite.config.d.ts +0 -5
  117. package/lib/config/vite.config.js +0 -162
  118. package/lib/index.d.ts +0 -1
  119. package/lib/index.js +0 -5
  120. package/lib/shared/constant.js +0 -50
  121. package/lib/shared/fsUtils.js +0 -108
  122. package/lib/shared/logger.js +0 -23
  123. package/site/mobile/components/AppType.vue +0 -22
  124. package/varlet.default.config.js +0 -267
@@ -0,0 +1,75 @@
1
+ import logger from '../shared/logger.js';
2
+ import fse from 'fs-extra';
3
+ import inquirer from 'inquirer';
4
+ import { resolve } from 'path';
5
+ import { CLI_PACKAGE_JSON, CWD, GENERATORS_DIR } from '../shared/constant.js';
6
+ const { copy, pathExistsSync, readFileSync, writeFileSync, rename } = fse;
7
+ const { prompt } = inquirer;
8
+ function syncVersion(name) {
9
+ const file = resolve(CWD, name, 'package.json');
10
+ const pkg = JSON.parse(readFileSync(file, 'utf-8'));
11
+ const cliPkg = JSON.parse(readFileSync(CLI_PACKAGE_JSON, 'utf-8'));
12
+ Object.keys(pkg.devDependencies).forEach((key) => {
13
+ if (key.startsWith('@varlet')) {
14
+ pkg.devDependencies[key] = `^${cliPkg.version}`;
15
+ }
16
+ });
17
+ pkg.files = ['es', 'lib', 'umd', 'highlight', 'types'];
18
+ writeFileSync(file, JSON.stringify(pkg, null, 2));
19
+ }
20
+ export async function gen(options) {
21
+ logger.title('\n📦📦 Generate cli application ! \n');
22
+ const { name } = options.name
23
+ ? options
24
+ : await prompt({
25
+ name: 'name',
26
+ message: 'Name of the generate application: ',
27
+ default: 'varlet-cli-app',
28
+ });
29
+ const dest = resolve(CWD, name);
30
+ if (pathExistsSync(dest)) {
31
+ logger.error(`${name} already exists and cannot be recreated...`);
32
+ return;
33
+ }
34
+ let codeStyle;
35
+ // Determine whether the parameter carries a coding style
36
+ if (options.sfc || options.tsx) {
37
+ codeStyle = options.sfc ? 'sfc' : 'tsx';
38
+ }
39
+ else {
40
+ const { style } = await prompt({
41
+ name: 'style',
42
+ type: 'list',
43
+ message: 'Please select your component library programming format',
44
+ choices: ['sfc', 'tsx'],
45
+ });
46
+ codeStyle = style;
47
+ }
48
+ const { i18n } = options.i18n
49
+ ? options
50
+ : await prompt({
51
+ name: 'i18n',
52
+ type: 'confirm',
53
+ message: 'Whether to use i18n?',
54
+ default: false,
55
+ });
56
+ const dirName = i18n ? 'i18n' : 'default';
57
+ const base = resolve(GENERATORS_DIR, 'base');
58
+ const configBase = resolve(GENERATORS_DIR, 'config', dirName, 'base');
59
+ const code = resolve(GENERATORS_DIR, 'config', dirName, codeStyle);
60
+ await copy(base, dest);
61
+ await copy(configBase, dest);
62
+ await copy(code, dest);
63
+ await rename(resolve(dest, '_gitignore'), resolve(dest, '.gitignore'));
64
+ syncVersion(name);
65
+ logger.success('✨ Application generated successfully!');
66
+ logger.info(`\
67
+ cd ${name}
68
+ pnpm install
69
+ pnpm dev`);
70
+ logger.success(`\
71
+ =======================
72
+ Good luck have fun
73
+ =======================\
74
+ `);
75
+ }
File without changes
@@ -0,0 +1,27 @@
1
+ import logger from '../shared/logger.js';
2
+ import jestModule from 'jest';
3
+ import { CWD, JEST_CONFIG } from '../shared/constant.js';
4
+ import { buildSiteEntry } from '../compiler/compileSiteEntry.js';
5
+ const { runCLI } = jestModule;
6
+ export async function jest(cmd) {
7
+ process.env.NODE_ENV = 'test';
8
+ const config = {
9
+ rootDir: CWD,
10
+ watch: cmd.watch,
11
+ watchAll: cmd.watchAll,
12
+ clearCache: cmd.clearCache,
13
+ config: JEST_CONFIG,
14
+ testRegex: cmd.component && `${cmd.component}/__tests__/.*.spec.[jt]s?$`,
15
+ };
16
+ await buildSiteEntry();
17
+ try {
18
+ const response = await runCLI(config, [CWD]);
19
+ if (!response.results.success && !cmd.watch) {
20
+ process.exit(1);
21
+ }
22
+ }
23
+ catch (e) {
24
+ logger.error(e.toString());
25
+ process.exit(1);
26
+ }
27
+ }
File without changes
@@ -0,0 +1,42 @@
1
+ import execa from 'execa';
2
+ import ora from 'ora';
3
+ import { CWD, ESLINT_EXTENSIONS } from '../shared/constant.js';
4
+ import { isDir } from '../shared/fsUtils.js';
5
+ import { resolve } from 'path';
6
+ export async function lint() {
7
+ let spinner;
8
+ try {
9
+ spinner = ora('prettier starting...').start();
10
+ await execa('prettier', ['--write', '--cache', '.']);
11
+ spinner.succeed('prettier success');
12
+ spinner = ora('stylelint starting...').start();
13
+ const stylelintPattern = ['./src/**/*.vue', './src/**/*.css', './src/**/*.less'];
14
+ const hasPackages = isDir(resolve(CWD, 'packages'));
15
+ hasPackages && stylelintPattern.push('./packages/**/*.vue', './packages/**/*.css', './packages/**/*.less');
16
+ await execa('stylelint', [...stylelintPattern, '--fix', '--cache']);
17
+ spinner.succeed('stylelint success');
18
+ spinner = ora('eslint starting...').start();
19
+ const eslintPatterns = [
20
+ './src',
21
+ './packages/varlet-cli/src',
22
+ './packages/varlet-ui/src',
23
+ './packages/varlet-icons/lib',
24
+ './packages/varlet-markdown-vite-plugin',
25
+ './packages/varlet-touch-emulator',
26
+ './packages/varlet-vscode-extension/src',
27
+ ];
28
+ const { stdout } = await execa('eslint', [
29
+ ...eslintPatterns.filter((pattern) => isDir(resolve(CWD, pattern))),
30
+ '--fix',
31
+ '--cache',
32
+ '--ext',
33
+ ESLINT_EXTENSIONS.join(),
34
+ ]);
35
+ const type = stdout ? 'warn' : 'succeed';
36
+ spinner[type](stdout || 'eslint success');
37
+ }
38
+ catch (e) {
39
+ spinner.fail(e.toString());
40
+ process.exit(1);
41
+ }
42
+ }
File without changes
@@ -0,0 +1,18 @@
1
+ import fse from 'fs-extra';
2
+ import logger from '../shared/logger.js';
3
+ import execa from 'execa';
4
+ import { SITE_OUTPUT_PATH } from '../shared/constant.js';
5
+ const { pathExistsSync } = fse;
6
+ export async function preview() {
7
+ var _a;
8
+ if (!pathExistsSync(SITE_OUTPUT_PATH)) {
9
+ logger.warning('Cannot find the site folder, you must first run the build command to build the document site');
10
+ return;
11
+ }
12
+ try {
13
+ await ((_a = execa.command('live-server --port=5500', { cwd: SITE_OUTPUT_PATH }).stdout) === null || _a === void 0 ? void 0 : _a.pipe(process.stdout));
14
+ }
15
+ catch (e) {
16
+ logger.error(e.toString());
17
+ }
18
+ }
File without changes
@@ -0,0 +1,146 @@
1
+ import ora from 'ora';
2
+ import fse from 'fs-extra';
3
+ import execa from 'execa';
4
+ import logger from '../shared/logger.js';
5
+ import semver from 'semver';
6
+ import glob from 'glob';
7
+ import inquirer from 'inquirer';
8
+ import { CWD } from '../shared/constant.js';
9
+ import { resolve } from 'path';
10
+ import { changelog } from './changelog.js';
11
+ const { writeFileSync, readJSONSync } = fse;
12
+ const { prompt } = inquirer;
13
+ const releaseTypes = ['premajor', 'preminor', 'prepatch', 'major', 'minor', 'patch'];
14
+ async function isWorktreeEmpty() {
15
+ const ret = await execa('git', ['status', '--porcelain']);
16
+ return !ret.stdout;
17
+ }
18
+ async function publish(preRelease) {
19
+ const s = ora().start('Publishing all packages');
20
+ const args = ['-r', 'publish', '--no-git-checks', '--access', 'public'];
21
+ preRelease && args.push('--tag', 'alpha');
22
+ const ret = await execa('pnpm', args);
23
+ if (ret.stderr && ret.stderr.includes('npm ERR!')) {
24
+ throw new Error('\n' + ret.stderr);
25
+ }
26
+ else {
27
+ s.succeed('Publish all packages successfully');
28
+ ret.stdout && logger.info(ret.stdout);
29
+ }
30
+ }
31
+ async function pushGit(version, remote = 'origin') {
32
+ const s = ora().start('Pushing to remote git repository');
33
+ await execa('git', ['add', '.']);
34
+ await execa('git', ['commit', '-m', `v${version}`]);
35
+ await execa('git', ['tag', `v${version}`]);
36
+ await execa('git', ['push', remote, `v${version}`]);
37
+ const ret = await execa('git', ['push']);
38
+ s.succeed('Push remote repository successfully');
39
+ ret.stdout && logger.info(ret.stdout);
40
+ }
41
+ function updateVersion(version) {
42
+ const packageJsons = glob.sync('packages/*/package.json');
43
+ packageJsons.push('package.json');
44
+ packageJsons.forEach((path) => {
45
+ const file = resolve(CWD, path);
46
+ const config = readJSONSync(file);
47
+ config.version = version;
48
+ writeFileSync(file, JSON.stringify(config, null, 2));
49
+ });
50
+ }
51
+ async function confirmRegistry() {
52
+ const registry = (await execa('npm', ['config', 'get', 'registry'])).stdout;
53
+ const name = 'Registry confirm';
54
+ const ret = await prompt([
55
+ {
56
+ name,
57
+ type: 'confirm',
58
+ message: `Current registry is: ${registry}`,
59
+ },
60
+ ]);
61
+ return ret[name];
62
+ }
63
+ async function confirmVersion(currentVersion, expectVersion) {
64
+ const name = 'Version confirm';
65
+ const ret = await prompt([
66
+ {
67
+ name,
68
+ type: 'confirm',
69
+ message: `All packages version ${currentVersion} -> ${expectVersion}:`,
70
+ },
71
+ ]);
72
+ return ret[name];
73
+ }
74
+ async function confirmRefs(remote = 'origin') {
75
+ var _a;
76
+ const { stdout } = await execa('git', ['remote', '-v']);
77
+ const reg = new RegExp(`${remote}\t(.*) \\(push`);
78
+ const repo = (_a = stdout.match(reg)) === null || _a === void 0 ? void 0 : _a[1];
79
+ const { stdout: branch } = await execa('git', ['branch', '--show-current']);
80
+ const name = 'Refs confirm';
81
+ const ret = await prompt([
82
+ {
83
+ name,
84
+ type: 'confirm',
85
+ message: `Current refs ${repo}:refs/for/${branch}`,
86
+ },
87
+ ]);
88
+ return ret[name];
89
+ }
90
+ async function getReleaseType() {
91
+ const name = 'Please select release type';
92
+ const ret = await prompt([
93
+ {
94
+ name,
95
+ type: 'list',
96
+ choices: releaseTypes,
97
+ },
98
+ ]);
99
+ return ret[name];
100
+ }
101
+ export async function release(options) {
102
+ try {
103
+ const currentVersion = readJSONSync(resolve(CWD, 'package.json')).version;
104
+ if (!currentVersion) {
105
+ logger.error('Your package is missing the version field');
106
+ return;
107
+ }
108
+ if (!(await isWorktreeEmpty())) {
109
+ logger.error('Git worktree is not empty, please commit changed');
110
+ return;
111
+ }
112
+ if (!(await confirmRefs(options.remote))) {
113
+ return;
114
+ }
115
+ if (!(await confirmRegistry())) {
116
+ return;
117
+ }
118
+ const type = await getReleaseType();
119
+ const isPreRelease = type.startsWith('pre');
120
+ let expectVersion = semver.inc(currentVersion, type, `alpha.${Date.now()}`);
121
+ expectVersion = isPreRelease ? expectVersion.slice(0, -2) : expectVersion;
122
+ if (!(await confirmVersion(currentVersion, expectVersion))) {
123
+ return;
124
+ }
125
+ updateVersion(expectVersion);
126
+ await publish(isPreRelease);
127
+ if (!isPreRelease) {
128
+ await changelog();
129
+ await pushGit(expectVersion, options.remote);
130
+ }
131
+ logger.success(`Release version ${expectVersion} successfully!`);
132
+ if (isPreRelease) {
133
+ try {
134
+ await execa('git', ['restore', '**/package.json']);
135
+ await execa('git', ['restore', 'package.json']);
136
+ }
137
+ catch (_a) {
138
+ logger.error('Restore package.json has failed, please restore manually');
139
+ }
140
+ }
141
+ }
142
+ catch (error) {
143
+ logger.error(error.toString());
144
+ process.exit(1);
145
+ }
146
+ }
File without changes
@@ -0,0 +1,13 @@
1
+ import vue from '@vitejs/plugin-vue';
2
+ import jsx from '@vitejs/plugin-vue-jsx';
3
+ import { build, createServer } from 'vite';
4
+ export async function vite(mode) {
5
+ const run = mode === 'build' ? build : createServer;
6
+ const result = await run({
7
+ plugins: [vue(), jsx()],
8
+ });
9
+ if (mode === 'dev') {
10
+ await result.listen();
11
+ result.printUrls();
12
+ }
13
+ }
@@ -0,0 +1,74 @@
1
+ import fse from 'fs-extra';
2
+ import { build } from 'vite';
3
+ import { resolve } from 'path';
4
+ import { EXAMPLE_DIR_NAME, TESTS_DIR_NAME, DOCS_DIR_NAME, SRC_DIR, ES_DIR, STYLE_DIR_NAME, LIB_DIR, } from '../shared/constant.js';
5
+ import { getPublicDirs, isDir, isDTS, isLess, isScript, isSFC } from '../shared/fsUtils.js';
6
+ import { compileSFC } from './compileSFC.js';
7
+ import { compileESEntry, compileCommonJSEntry, compileScriptFile } from './compileScript.js';
8
+ import { compileLess } from './compileStyle.js';
9
+ import { getESMBundleConfig, getUMDConfig } from '../config/vite.config.js';
10
+ import { getVarletConfig } from '../config/varlet.config.js';
11
+ import { generateReference } from './compileTypes.js';
12
+ const { copy, ensureFileSync, readdir, removeSync } = fse;
13
+ export function compileUMD() {
14
+ return new Promise((resolve, reject) => {
15
+ getVarletConfig().then((varletConfig) => {
16
+ build(getUMDConfig(varletConfig))
17
+ .then(() => resolve())
18
+ .catch(reject);
19
+ });
20
+ });
21
+ }
22
+ export function compileESMBundle() {
23
+ return new Promise((resolve, reject) => {
24
+ getVarletConfig().then((varletConfig) => {
25
+ build(getESMBundleConfig(varletConfig))
26
+ .then(() => resolve())
27
+ .catch(reject);
28
+ });
29
+ });
30
+ }
31
+ export async function compileDir(dir) {
32
+ const dirs = await readdir(dir);
33
+ await Promise.all(dirs.map((filename) => {
34
+ const file = resolve(dir, filename);
35
+ [TESTS_DIR_NAME, EXAMPLE_DIR_NAME, DOCS_DIR_NAME].includes(filename) && removeSync(file);
36
+ if (isDTS(file) || filename === STYLE_DIR_NAME) {
37
+ return Promise.resolve();
38
+ }
39
+ return compileFile(file);
40
+ }));
41
+ }
42
+ export async function compileFile(file) {
43
+ isSFC(file) && (await compileSFC(file));
44
+ isScript(file) && (await compileScriptFile(file));
45
+ isLess(file) && (await compileLess(file));
46
+ isDir(file) && (await compileDir(file));
47
+ }
48
+ export async function compileModule(modules = false) {
49
+ if (modules === 'umd') {
50
+ await compileUMD();
51
+ return;
52
+ }
53
+ if (modules === 'esm-bundle') {
54
+ await compileESMBundle();
55
+ return;
56
+ }
57
+ process.env.BABEL_MODULE = modules === 'commonjs' ? 'commonjs' : 'module';
58
+ const dest = modules === 'commonjs' ? LIB_DIR : ES_DIR;
59
+ await copy(SRC_DIR, dest);
60
+ const moduleDir = await readdir(dest);
61
+ await Promise.all(moduleDir.map((filename) => {
62
+ const file = resolve(dest, filename);
63
+ isDir(file) && ensureFileSync(resolve(file, './style/index.js'));
64
+ return isDir(file) ? compileDir(file) : null;
65
+ }));
66
+ const publicDirs = await getPublicDirs();
67
+ if (modules === 'commonjs') {
68
+ await compileCommonJSEntry(dest, publicDirs);
69
+ }
70
+ else {
71
+ await compileESEntry(dest, publicDirs);
72
+ }
73
+ generateReference(dest);
74
+ }
File without changes
@@ -0,0 +1,79 @@
1
+ import fse from 'fs-extra';
2
+ import hash from 'hash-sum';
3
+ import { parse, resolve } from 'path';
4
+ import { parse as parseSFC, compileTemplate, compileStyle } from '@vue/compiler-sfc';
5
+ import { replaceExt, smartAppendFileSync } from '../shared/fsUtils.js';
6
+ import { compileScript } from './compileScript.js';
7
+ import { clearEmptyLine, compileLess, extractStyleDependencies, normalizeStyleDependency, STYLE_IMPORT_RE, } from './compileStyle.js';
8
+ import logger from '../shared/logger.js';
9
+ const { readFile, writeFileSync } = fse;
10
+ const NORMAL_EXPORT_START_RE = /export\s+default\s+{/;
11
+ const DEFINE_EXPORT_START_RE = /export\s+default\s+defineComponent\s*\(\s*{/;
12
+ export function injectRender(script, render) {
13
+ if (DEFINE_EXPORT_START_RE.test(script.trim())) {
14
+ return script.trim().replace(DEFINE_EXPORT_START_RE, `${render}\nexport default defineComponent({
15
+ render,\
16
+ `);
17
+ }
18
+ if (NORMAL_EXPORT_START_RE.test(script.trim())) {
19
+ return script.trim().replace(NORMAL_EXPORT_START_RE, `${render}\nexport default {
20
+ render,\
21
+ `);
22
+ }
23
+ return script;
24
+ }
25
+ export async function compileSFC(sfc) {
26
+ const sources = await readFile(sfc, 'utf-8');
27
+ const { descriptor } = parseSFC(sources, { sourceMap: false });
28
+ const { script, scriptSetup, template, styles } = descriptor;
29
+ if (scriptSetup) {
30
+ logger.warning(`\n Varlet Cli does not support compiling script setup syntax\
31
+ \n The error in ${sfc}`);
32
+ return;
33
+ }
34
+ // scoped
35
+ const hasScope = styles.some((style) => style.scoped);
36
+ const id = hash(sources);
37
+ const scopeId = hasScope ? `data-v-${id}` : '';
38
+ if (script) {
39
+ // template
40
+ const render = template &&
41
+ compileTemplate({
42
+ id,
43
+ source: template.content,
44
+ filename: sfc,
45
+ compilerOptions: {
46
+ scopeId,
47
+ },
48
+ });
49
+ let { content } = script;
50
+ if (render) {
51
+ const { code } = render;
52
+ content = injectRender(content, code);
53
+ }
54
+ // script
55
+ await compileScript(content, sfc);
56
+ // style
57
+ for (let index = 0; index < styles.length; index++) {
58
+ const style = styles[index];
59
+ const file = replaceExt(sfc, `Sfc${index || ''}.${style.lang || 'css'}`);
60
+ const { base, dir } = parse(file);
61
+ const dependencyPath = normalizeStyleDependency(base, STYLE_IMPORT_RE);
62
+ const cssFile = resolve(dir, './style/index.js');
63
+ let { code } = compileStyle({
64
+ source: style.content,
65
+ filename: file,
66
+ id: scopeId,
67
+ scoped: style.scoped,
68
+ });
69
+ code = extractStyleDependencies(file, code, STYLE_IMPORT_RE);
70
+ writeFileSync(file, clearEmptyLine(code), 'utf-8');
71
+ smartAppendFileSync(cssFile, process.env.BABEL_MODULE === 'commonjs'
72
+ ? `require('${dependencyPath}.css')\n`
73
+ : `import '${dependencyPath}.css'\n`);
74
+ if (style.lang === 'less') {
75
+ await compileLess(file);
76
+ }
77
+ }
78
+ }
79
+ }
@@ -10,7 +10,7 @@ export declare const replaceVueExt: (script: string) => string;
10
10
  export declare const replaceTSExt: (script: string) => string;
11
11
  export declare const replaceJSXExt: (script: string) => string;
12
12
  export declare const replaceTSXExt: (script: string) => string;
13
- export declare const moduleCompatible: (script: string) => string;
13
+ export declare const moduleCompatible: (script: string) => Promise<string>;
14
14
  export declare function compileScript(script: string, file: string): Promise<void>;
15
15
  export declare function compileScriptFile(file: string): Promise<void>;
16
16
  export declare function compileESEntry(dir: string, publicDirs: string[]): Promise<void>;
@@ -0,0 +1,141 @@
1
+ import fse from 'fs-extra';
2
+ import { transformAsync } from '@babel/core';
3
+ import { bigCamelize } from '@varlet/shared';
4
+ import { replaceExt } from '../shared/fsUtils.js';
5
+ import { extractStyleDependencies, IMPORT_CSS_RE, IMPORT_LESS_RE, REQUIRE_CSS_RE, REQUIRE_LESS_RE, } from './compileStyle.js';
6
+ import { resolve } from 'path';
7
+ import { get } from 'lodash-es';
8
+ import { getVarletConfig } from '../config/varlet.config.js';
9
+ const { writeFileSync, readFileSync, removeSync, writeFile } = fse;
10
+ export const IMPORT_VUE_PATH_RE = /((?<!['"`])import\s+.+from\s+['"]\s*\.{1,2}\/.+)\.vue(\s*['"`]);?(?!\s*['"`])/g;
11
+ export const IMPORT_TS_PATH_RE = /((?<!['"`])import\s+.+from\s+['"]\s*\.{1,2}\/.+)\.ts(\s*['"`]);?(?!\s*['"`])/g;
12
+ export const IMPORT_JSX_PATH_RE = /((?<!['"`])import\s+.+from\s+['"]\s*\.{1,2}\/.+)\.jsx(\s*['"`]);?(?!\s*['"`])/g;
13
+ export const IMPORT_TSX_PATH_RE = /((?<!['"`])import\s+.+from\s+['"]\s*\.{1,2}\/.+)\.tsx(\s*['"`]);?(?!\s*['"`])/g;
14
+ export const REQUIRE_VUE_PATH_RE = /(?<!['"`]\s*)(require\s*\(\s*['"]\s*\.{1,2}\/.+)\.vue(\s*['"`]\))(?!\s*['"`])/g;
15
+ export const REQUIRE_TS_PATH_RE = /(?<!['"`]\s*)(require\s*\(\s*['"]\s*\.{1,2}\/.+)\.ts(\s*['"`]\))(?!\s*['"`])/g;
16
+ export const REQUIRE_JSX_PATH_RE = /(?<!['"`]\s*)(require\s*\(\s*['"]\s*\.{1,2}\/.+)\.jsx(\s*['"`]\))(?!\s*['"`])/g;
17
+ export const REQUIRE_TSX_PATH_RE = /(?<!['"`]\s*)(require\s*\(\s*['"]\s*\.{1,2}\/.+)\.tsx(\s*['"`]\))(?!\s*['"`])/g;
18
+ const scriptReplacer = (_, p1, p2) => `${p1}.js${p2}`;
19
+ export const replaceVueExt = (script) => script.replace(IMPORT_VUE_PATH_RE, scriptReplacer).replace(REQUIRE_VUE_PATH_RE, scriptReplacer);
20
+ export const replaceTSExt = (script) => script.replace(IMPORT_TS_PATH_RE, scriptReplacer).replace(REQUIRE_TS_PATH_RE, scriptReplacer);
21
+ export const replaceJSXExt = (script) => script.replace(IMPORT_JSX_PATH_RE, scriptReplacer).replace(REQUIRE_JSX_PATH_RE, scriptReplacer);
22
+ export const replaceTSXExt = (script) => script.replace(IMPORT_TSX_PATH_RE, scriptReplacer).replace(REQUIRE_TSX_PATH_RE, scriptReplacer);
23
+ export const moduleCompatible = async (script) => {
24
+ const moduleCompatible = get(await getVarletConfig(), 'moduleCompatible', {});
25
+ Object.keys(moduleCompatible).forEach((esm) => {
26
+ const commonjs = moduleCompatible[esm];
27
+ script = script.replace(esm, commonjs);
28
+ });
29
+ return script;
30
+ };
31
+ export async function compileScript(script, file) {
32
+ const modules = process.env.BABEL_MODULE;
33
+ if (modules === 'commonjs') {
34
+ script = await moduleCompatible(script);
35
+ }
36
+ let { code } = (await transformAsync(script, {
37
+ filename: file,
38
+ }));
39
+ code = extractStyleDependencies(file, code, modules === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE);
40
+ code = extractStyleDependencies(file, code, modules === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE);
41
+ code = replaceVueExt(code);
42
+ code = replaceTSXExt(code);
43
+ code = replaceJSXExt(code);
44
+ code = replaceTSExt(code);
45
+ removeSync(file);
46
+ writeFileSync(replaceExt(file, '.js'), code, 'utf8');
47
+ }
48
+ export async function compileScriptFile(file) {
49
+ const sources = readFileSync(file, 'utf-8');
50
+ await compileScript(sources, file);
51
+ }
52
+ export async function compileESEntry(dir, publicDirs) {
53
+ const imports = [];
54
+ const plugins = [];
55
+ const constInternalComponents = [];
56
+ const cssImports = [];
57
+ const publicComponents = [];
58
+ publicDirs.forEach((dirname) => {
59
+ const publicComponent = bigCamelize(dirname);
60
+ publicComponents.push(publicComponent);
61
+ imports.push(`import ${publicComponent}, * as ${publicComponent}Module from './${dirname}'`);
62
+ constInternalComponents.push(`export const _${publicComponent}Component = ${publicComponent}Module._${publicComponent}Component || {}`);
63
+ plugins.push(`${publicComponent}.install && app.use(${publicComponent})`);
64
+ cssImports.push(`import './${dirname}/style'`);
65
+ });
66
+ const install = `
67
+ function install(app) {
68
+ ${plugins.join('\n ')}
69
+ }
70
+ `;
71
+ const indexTemplate = `\
72
+ ${imports.join('\n')}\n
73
+ ${constInternalComponents.join('\n')}\n
74
+ ${install}
75
+ export {
76
+ install,
77
+ ${publicComponents.join(',\n ')}
78
+ }
79
+
80
+ export default {
81
+ install,
82
+ ${publicComponents.join(',\n ')}
83
+ }
84
+ `;
85
+ const styleTemplate = `\
86
+ ${cssImports.join('\n')}
87
+ `;
88
+ const umdTemplate = `\
89
+ ${imports.join('\n')}\n
90
+ ${cssImports.join('\n')}\n
91
+ ${install}
92
+ export {
93
+ install,
94
+ ${publicComponents.join(',\n ')}
95
+ }
96
+
97
+ export default {
98
+ install,
99
+ ${publicComponents.join(',\n ')}
100
+ }
101
+ `;
102
+ await Promise.all([
103
+ writeFile(resolve(dir, 'index.js'), indexTemplate, 'utf-8'),
104
+ writeFile(resolve(dir, 'umdIndex.js'), umdTemplate, 'utf-8'),
105
+ writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'),
106
+ ]);
107
+ }
108
+ export async function compileCommonJSEntry(dir, publicDirs) {
109
+ const requires = [];
110
+ const plugins = [];
111
+ const cssRequires = [];
112
+ const publicComponents = [];
113
+ publicDirs.forEach((dirname) => {
114
+ const publicComponent = bigCamelize(dirname);
115
+ publicComponents.push(publicComponent);
116
+ requires.push(`var ${publicComponent} = require('./${dirname}')['default']`);
117
+ plugins.push(`${publicComponent}.install && app.use(${publicComponent})`);
118
+ cssRequires.push(`require('./${dirname}/style')`);
119
+ });
120
+ const install = `
121
+ function install(app) {
122
+ ${plugins.join('\n ')}
123
+ }
124
+ `;
125
+ const indexTemplate = `\
126
+ ${requires.join('\n')}\n
127
+ ${install}
128
+
129
+ module.exports = {
130
+ install,
131
+ ${publicComponents.join(',\n ')}
132
+ }
133
+ `;
134
+ const styleTemplate = `\
135
+ ${cssRequires.join('\n')}
136
+ `;
137
+ await Promise.all([
138
+ writeFile(resolve(dir, 'index.js'), indexTemplate, 'utf-8'),
139
+ writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'),
140
+ ]);
141
+ }