From 05d2b380ef9e87c0b40e65f90af3c7aa8df0e2e1 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Thu, 12 Jan 2023 22:34:13 +0800 Subject: [PATCH 01/21] feat(cli): support mjs compiler --- .../varlet-cli/src/node/commands/compile.ts | 8 ++-- .../src/node/compiler/compileModule.ts | 40 +++++++------------ .../src/node/compiler/compileSFC.ts | 2 +- .../src/node/compiler/compileScript.ts | 35 ++++++++++------ .../src/node/compiler/compileStyle.ts | 7 ++-- .../varlet-cli/src/node/config/vite.config.ts | 4 +- packages/varlet-ui/package.json | 4 +- packages/varlet-vite-plugins/src/inlineCss.ts | 4 +- pnpm-lock.yaml | 7 ++-- 9 files changed, 58 insertions(+), 53 deletions(-) diff --git a/packages/varlet-cli/src/node/commands/compile.ts b/packages/varlet-cli/src/node/commands/compile.ts index 162d43da040..be68b5b4dba 100644 --- a/packages/varlet-cli/src/node/commands/compile.ts +++ b/packages/varlet-cli/src/node/commands/compile.ts @@ -34,14 +34,16 @@ export async function compile(options: CompileCommandOptions) { await Promise.all([runTask('types', compileTypes), runTask('template highlight', compileTemplateHighlight)]) process.env.TARGET_MODULE = 'module' + process.env.BABEL_MODULE = 'module' await runTask('module', compileModule) process.env.TARGET_MODULE = 'esm-bundle' - await runTask('esm bundle', () => compileModule('esm-bundle')) + await runTask('esm bundle', compileModule) process.env.TARGET_MODULE = 'commonjs' - await runTask('commonjs', () => compileModule('commonjs')) + process.env.BABEL_MODULE = 'commonjs' + await runTask('commonjs', compileModule) process.env.TARGET_MODULE = 'umd' - !options.noUmd && (await runTask('umd', () => compileModule('umd'))) + !options.noUmd && (await runTask('umd', compileModule)) } diff --git a/packages/varlet-cli/src/node/compiler/compileModule.ts b/packages/varlet-cli/src/node/compiler/compileModule.ts index f8cd7bcc475..d06a61f0c5c 100644 --- a/packages/varlet-cli/src/node/compiler/compileModule.ts +++ b/packages/varlet-cli/src/node/compiler/compileModule.ts @@ -12,7 +12,7 @@ import { } from '../shared/constant.js' import { getPublicDirs, isDir, isDTS, isLess, isScript, isSFC } from '../shared/fsUtils.js' import { compileSFC } from './compileSFC.js' -import { compileESEntry, compileCommonJSEntry, compileScriptFile } from './compileScript.js' +import { compileESEntry, compileCommonJSEntry, compileScriptFile, getScriptExtname } from './compileScript.js' import { clearLessFiles, compileLess } from './compileStyle.js' import { getESMBundleConfig, getUMDConfig } from '../config/vite.config.js' import { getVarletConfig } from '../config/varlet.config.js' @@ -20,24 +20,14 @@ import { generateReference } from './compileTypes.js' const { copy, ensureFileSync, readdir, removeSync } = fse -export function compileUMD() { - return new Promise((resolve, reject) => { - getVarletConfig().then((varletConfig) => { - build(getUMDConfig(varletConfig)) - .then(() => resolve()) - .catch(reject) - }) - }) +export async function compileUMD() { + const varletConfig = await getVarletConfig() + await build(getUMDConfig(varletConfig)) } -export function compileESMBundle() { - return new Promise((resolve, reject) => { - getVarletConfig().then((varletConfig) => { - build(getESMBundleConfig(varletConfig)) - .then(() => resolve()) - .catch(reject) - }) - }) +export async function compileESMBundle() { + const varletConfig = await getVarletConfig() + await build(getESMBundleConfig(varletConfig)) } export async function compileDir(dir: string) { @@ -65,20 +55,20 @@ export async function compileFile(file: string) { isDir(file) && (await compileDir(file)) } -export async function compileModule(modules: 'umd' | 'commonjs' | 'esm-bundle' | boolean = false) { - if (modules === 'umd') { +export async function compileModule() { + const targetModule = process.env.TARGET_MODULE + + if (targetModule === 'umd') { await compileUMD() return } - if (modules === 'esm-bundle') { + if (targetModule === 'esm-bundle') { await compileESMBundle() return } - process.env.BABEL_MODULE = modules === 'commonjs' ? 'commonjs' : 'module' - - const dest = modules === 'commonjs' ? LIB_DIR : ES_DIR + const dest = targetModule === 'commonjs' ? LIB_DIR : ES_DIR await copy(SRC_DIR, dest) const moduleDir: string[] = await readdir(dest) @@ -86,7 +76,7 @@ export async function compileModule(modules: 'umd' | 'commonjs' | 'esm-bundle' | moduleDir.map((filename: string) => { const file: string = resolve(dest, filename) - isDir(file) && ensureFileSync(resolve(file, './style/index.js')) + isDir(file) && ensureFileSync(resolve(file, `./style/index.${getScriptExtname()}`)) return isDir(file) ? compileDir(file) : null }) @@ -94,7 +84,7 @@ export async function compileModule(modules: 'umd' | 'commonjs' | 'esm-bundle' | const publicDirs = await getPublicDirs() - if (modules === 'commonjs') { + if (targetModule === 'commonjs') { await compileCommonJSEntry(dest, publicDirs) } else { await compileESEntry(dest, publicDirs) diff --git a/packages/varlet-cli/src/node/compiler/compileSFC.ts b/packages/varlet-cli/src/node/compiler/compileSFC.ts index fdd0b387652..df85b62efe7 100644 --- a/packages/varlet-cli/src/node/compiler/compileSFC.ts +++ b/packages/varlet-cli/src/node/compiler/compileSFC.ts @@ -93,7 +93,7 @@ export async function compileSFC(sfc: string) { writeFileSync(file, clearEmptyLine(code), 'utf-8') smartAppendFileSync( cssFile, - process.env.BABEL_MODULE === 'commonjs' + process.env.TARGET_MODULE === 'commonjs' ? `require('${dependencyPath}.css')\n` : `import '${dependencyPath}.css'\n` ) diff --git a/packages/varlet-cli/src/node/compiler/compileScript.ts b/packages/varlet-cli/src/node/compiler/compileScript.ts index d9020122b40..3faa5a6ed53 100644 --- a/packages/varlet-cli/src/node/compiler/compileScript.ts +++ b/packages/varlet-cli/src/node/compiler/compileScript.ts @@ -25,7 +25,7 @@ export const REQUIRE_TS_PATH_RE = /(? `${p1}.js${p2}` +const scriptReplacer = (_: any, p1: string, p2: string): string => `${p1}.${getScriptExtname()}${p2}` export const replaceVueExt = (script: string): string => script.replace(IMPORT_VUE_PATH_RE, scriptReplacer).replace(REQUIRE_VUE_PATH_RE, scriptReplacer) @@ -51,9 +51,9 @@ export const moduleCompatible = async (script: string): Promise => { } export async function compileScript(script: string, file: string) { - const modules = process.env.BABEL_MODULE + const targetModule = process.env.TARGET_MODULE - if (modules === 'commonjs') { + if (targetModule === 'commonjs') { script = await moduleCompatible(script) } @@ -61,15 +61,15 @@ export async function compileScript(script: string, file: string) { filename: file, })) as BabelFileResult - code = extractStyleDependencies(file, code as string, modules === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE) - code = extractStyleDependencies(file, code as string, modules === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE) + code = extractStyleDependencies(file, code as string, targetModule === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE) + code = extractStyleDependencies(file, code as string, targetModule === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE) code = replaceVueExt(code as string) code = replaceTSXExt(code as string) code = replaceJSXExt(code as string) code = replaceTSExt(code as string) removeSync(file) - writeFileSync(replaceExt(file, '.js'), code, 'utf8') + writeFileSync(replaceExt(file, `.${getScriptExtname()}`), code, 'utf8') } export async function compileScriptFile(file: string) { @@ -78,23 +78,32 @@ export async function compileScriptFile(file: string) { await compileScript(sources, file) } +export function getScriptExtname() { + if (process.env.TARGET_MODULE === 'module') { + return 'mjs' + } + + return 'js' +} + export async function compileESEntry(dir: string, publicDirs: string[]) { const imports: string[] = [] const plugins: string[] = [] const constInternalComponents: string[] = [] const cssImports: string[] = [] const publicComponents: string[] = [] + const scriptExtname = getScriptExtname() publicDirs.forEach((dirname: string) => { const publicComponent = bigCamelize(dirname) publicComponents.push(publicComponent) - imports.push(`import ${publicComponent}, * as ${publicComponent}Module from './${dirname}'`) + imports.push(`import ${publicComponent}, * as ${publicComponent}Module from './${dirname}/index.${scriptExtname}'`) constInternalComponents.push( `export const _${publicComponent}Component = ${publicComponent}Module._${publicComponent}Component || {}` ) plugins.push(`${publicComponent}.install && app.use(${publicComponent})`) - cssImports.push(`import './${dirname}/style'`) + cssImports.push(`import './${dirname}/style/index.${scriptExtname}'`) }) const install = ` @@ -138,9 +147,9 @@ export default { ` await Promise.all([ - writeFile(resolve(dir, 'index.js'), indexTemplate, 'utf-8'), - writeFile(resolve(dir, 'umdIndex.js'), umdTemplate, 'utf-8'), - writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'), + writeFile(resolve(dir, 'index.mjs'), indexTemplate, 'utf-8'), + writeFile(resolve(dir, 'index.umd.mjs'), umdTemplate, 'utf-8'), + writeFile(resolve(dir, 'style.mjs'), styleTemplate, 'utf-8'), ]) } @@ -154,9 +163,9 @@ export async function compileCommonJSEntry(dir: string, publicDirs: string[]) { const publicComponent = bigCamelize(dirname) publicComponents.push(publicComponent) - requires.push(`var ${publicComponent} = require('./${dirname}')['default']`) + requires.push(`var ${publicComponent} = require('./${dirname}/index.js')['default']`) plugins.push(`${publicComponent}.install && app.use(${publicComponent})`) - cssRequires.push(`require('./${dirname}/style')`) + cssRequires.push(`require('./${dirname}/style/index.js')`) }) const install = ` diff --git a/packages/varlet-cli/src/node/compiler/compileStyle.ts b/packages/varlet-cli/src/node/compiler/compileStyle.ts index 5bdb44c44c3..e2713b82c5d 100644 --- a/packages/varlet-cli/src/node/compiler/compileStyle.ts +++ b/packages/varlet-cli/src/node/compiler/compileStyle.ts @@ -3,6 +3,7 @@ import less from 'less' import glob from 'glob' import { replaceExt, smartAppendFileSync } from '../shared/fsUtils.js' import { parse, resolve } from 'path' +import { getScriptExtname } from './compileScript.js' const { render } = less const { readFileSync, writeFileSync, unlinkSync } = fse @@ -30,14 +31,14 @@ export function normalizeStyleDependency(styleImport: string, reg: RegExp) { export function extractStyleDependencies(file: string, code: string, styleReg: RegExp) { const styleImports = code.match(styleReg) ?? [] - const cssFile = resolve(parse(file).dir, './style/index.js') - const modules = process.env.BABEL_MODULE + const cssFile = resolve(parse(file).dir, `./style/index.${getScriptExtname()}`) + const targetModule = process.env.TARGET_MODULE styleImports.forEach((styleImport: string) => { const normalizedPath = normalizeStyleDependency(styleImport, styleReg) smartAppendFileSync( cssFile, - modules === 'commonjs' ? `require('${normalizedPath}.css')\n` : `import '${normalizedPath}.css'\n` + targetModule === 'commonjs' ? `require('${normalizedPath}.css')\n` : `import '${normalizedPath}.css'\n` ) }) diff --git a/packages/varlet-cli/src/node/config/vite.config.ts b/packages/varlet-cli/src/node/config/vite.config.ts index 54a31450b4b..ea0a7d3b6c9 100644 --- a/packages/varlet-cli/src/node/config/vite.config.ts +++ b/packages/varlet-cli/src/node/config/vite.config.ts @@ -104,7 +104,7 @@ export function getESMBundleConfig(varletConfig: Required): Inline name, formats: ['es'], fileName: () => fileName, - entry: resolve(ES_DIR, 'umdIndex.js'), + entry: resolve(ES_DIR, 'index.umd.mjs'), }, rollupOptions: { external: ['vue'], @@ -136,7 +136,7 @@ export function getUMDConfig(varletConfig: Required): InlineConfig name, formats: ['umd'], fileName: () => fileName, - entry: resolve(ES_DIR, 'umdIndex.js'), + entry: resolve(ES_DIR, 'index.umd.mjs'), }, rollupOptions: { external: ['vue'], diff --git a/packages/varlet-ui/package.json b/packages/varlet-ui/package.json index e65fc604872..9a53fea9d44 100644 --- a/packages/varlet-ui/package.json +++ b/packages/varlet-ui/package.json @@ -2,8 +2,8 @@ "name": "@varlet/ui", "version": "2.6.2", "description": "A material like components library", - "module": "es/index.js", "main": "lib/index.js", + "module": "es/index.mjs", "typings": "types/index.d.ts", "vetur": { "tags": "highlight/tags.json", @@ -80,4 +80,4 @@ "Chrome >= 54", "iOS >= 10" ] -} \ No newline at end of file +} diff --git a/packages/varlet-vite-plugins/src/inlineCss.ts b/packages/varlet-vite-plugins/src/inlineCss.ts index 97ed894e94a..1af3c31c62f 100644 --- a/packages/varlet-vite-plugins/src/inlineCss.ts +++ b/packages/varlet-vite-plugins/src/inlineCss.ts @@ -19,12 +19,14 @@ export function inlineCss(options: InlineCssOptions): Plugin { const { cssFile, jsFile, onEnd } = options if (!pathExistsSync(cssFile)) { - this.error('css file cannot found') + this.warn('css file cannot found') + onEnd?.() return } if (!pathExistsSync(jsFile)) { this.error('js file cannot found') + onEnd?.() return } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f0cc8e4ae6f..e1a9ec5e854 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -85,7 +85,6 @@ importers: '@babel/helper-plugin-utils': 7.18.9 '@babel/preset-env': 7.18.10_@babel+core@7.18.10 '@babel/preset-typescript': 7.18.6_@babel+core@7.18.10 - '@types/inquirer': 9.0.2 '@varlet/shared': link:../varlet-shared '@varlet/vite-plugins': link:../varlet-vite-plugins '@vitejs/plugin-vue': 4.0.0_vite@4.0.4+vue@3.2.25 @@ -125,6 +124,7 @@ importers: '@types/fs-extra': 9.0.13 '@types/glob': 7.2.0 '@types/hash-sum': 1.0.0 + '@types/inquirer': 9.0.2 '@types/lodash-es': 4.17.6 '@types/node': 18.7.20 '@types/semver': 7.3.12 @@ -2378,7 +2378,7 @@ packages: dependencies: '@types/through': 0.0.30 rxjs: 7.5.6 - dev: false + dev: true /@types/istanbul-lib-coverage/2.0.4: resolution: {integrity: sha512-z/QT1XN4K4KYuslS23k62yDIDLwLFkzxOuMplDtObz0+y7VqJCaO2o+SPwHCvLFZh7xazvvoor2tA/hPz9ee7g==} @@ -2488,7 +2488,7 @@ packages: resolution: {integrity: sha512-FvnCJljyxhPM3gkRgWmxmDZyAQSiBQQWLI0A0VFL0K7W1oRUrPJSqNO0NvTnLkBcotdlp3lKvaT0JrnyRDkzOg==} dependencies: '@types/node': 18.7.20 - dev: false + dev: true /@types/unist/2.0.6: resolution: {integrity: sha512-PBjIUxZHOuj0R15/xuwJYjFi+KZdNFrehocChv4g5hu6aFroHue8m0lBP0POdK2nKzbw0cgV1mws8+V/JAcEkQ==} @@ -8536,6 +8536,7 @@ packages: resolution: {integrity: sha512-dnyv2/YsXhnm461G+R/Pe5bWP41Nm6LBXEYWI6eiFP4fiwx6WRI/CD0zbdVAudd9xwLEF2IDcKXLHit0FYjUzw==} dependencies: tslib: 2.4.0 + dev: true /rxjs/7.5.7: resolution: {integrity: sha512-z9MzKh/UcOqB3i20H6rtrlaE/CgjLOvheWK/9ILrbhROGTweAi1BaFsTT9FbwZi5Trr1qNRs+MXkhmR06awzQA==} From a3785c9437ffc0d86719711b035800b8db8508b1 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 12:29:02 +0800 Subject: [PATCH 02/21] feat: expose command and version --- package.json | 4 +- packages/varlet-cli/lib/node/bin.js | 6 +- packages/varlet-cli/lib/node/index.js | 12 ++ packages/varlet-cli/src/node/bin.ts | 7 +- .../varlet-cli/src/node/commands/release.ts | 8 +- .../src/node/compiler/compileScript.ts | 140 +++++++++++++----- .../node/compiler/compileTemplateHighlight.ts | 7 +- packages/varlet-cli/src/node/index.ts | 12 ++ .../varlet-cli/src/node/shared/fsUtils.ts | 21 ++- scripts/bootstrap.mjs | 16 +- scripts/{publish.mjs => release.mjs} | 7 +- 11 files changed, 174 insertions(+), 66 deletions(-) rename scripts/{publish.mjs => release.mjs} (78%) diff --git a/package.json b/package.json index 75f04939749..0d8ba5881d8 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "bootstrap": "pnpm install && node scripts/bootstrap.mjs", "lint": "varlet-cli lint", "changelog": "varlet-cli changelog", - "release": "node scripts/publish.mjs && varlet-cli release" + "release": "node scripts/release.mjs" }, "simple-git-hooks": { "pre-commit": "pnpm exec lint-staged --allow-empty --concurrent false", @@ -89,4 +89,4 @@ "engines": { "pnpm": ">=7.9" } -} \ No newline at end of file +} diff --git a/packages/varlet-cli/lib/node/bin.js b/packages/varlet-cli/lib/node/bin.js index e80fb5eaf87..b8e8be26f81 100755 --- a/packages/varlet-cli/lib/node/bin.js +++ b/packages/varlet-cli/lib/node/bin.js @@ -1,10 +1,8 @@ #!/usr/bin/env node -import fse from 'fs-extra'; import { Command } from 'commander'; -import { CLI_PACKAGE_JSON } from './shared/constant.js'; -const { readJSONSync } = fse; +import { getCliVersion } from './shared/fsUtils.js'; const program = new Command(); -program.version(`varlet-cli ${readJSONSync(CLI_PACKAGE_JSON).version}`).usage(' [options]'); +program.version(`varlet-cli ${getCliVersion()}`).usage(' [options]'); program .command('dev') .option('-f --force', 'Force dep pre-optimization regardless of whether deps have changed') diff --git a/packages/varlet-cli/lib/node/index.js b/packages/varlet-cli/lib/node/index.js index d8f60db3070..ff03b71c0ad 100644 --- a/packages/varlet-cli/lib/node/index.js +++ b/packages/varlet-cli/lib/node/index.js @@ -1 +1,13 @@ export { defineConfig } from './config/varlet.config.js'; +export * from './commands/release.js'; +export * from './commands/dev.js'; +export * from './commands/build.js'; +export * from './commands/compile.js'; +export * from './commands/commitLint.js'; +export * from './commands/gen.js'; +export * from './commands/jest.js'; +export * from './commands/create.js'; +export * from './commands/lint.js'; +export * from './commands/changelog.js'; +export * from './commands/preview.js'; +export * from './commands/vite.js'; diff --git a/packages/varlet-cli/src/node/bin.ts b/packages/varlet-cli/src/node/bin.ts index 0ab67b7b84e..358f7500d68 100644 --- a/packages/varlet-cli/src/node/bin.ts +++ b/packages/varlet-cli/src/node/bin.ts @@ -1,13 +1,10 @@ #!/usr/bin/env node -import fse from 'fs-extra' import { Command } from 'commander' -import { CLI_PACKAGE_JSON } from './shared/constant.js' - -const { readJSONSync } = fse +import { getCliVersion } from './shared/fsUtils.js' const program = new Command() -program.version(`varlet-cli ${readJSONSync(CLI_PACKAGE_JSON).version}`).usage(' [options]') +program.version(`varlet-cli ${getCliVersion()}`).usage(' [options]') program .command('dev') diff --git a/packages/varlet-cli/src/node/commands/release.ts b/packages/varlet-cli/src/node/commands/release.ts index 9b1a79c5451..4bcafb1ec33 100644 --- a/packages/varlet-cli/src/node/commands/release.ts +++ b/packages/varlet-cli/src/node/commands/release.ts @@ -8,6 +8,7 @@ import inquirer from 'inquirer' import { CWD } from '../shared/constant.js' import { resolve } from 'path' import { changelog } from './changelog.js' +import { getVersion } from '../shared/fsUtils.js' const { writeFileSync, readJSONSync } = fse const { prompt } = inquirer @@ -118,11 +119,12 @@ async function getReleaseType() { interface ReleaseCommandOptions { remote?: string + task?(): Promise } export async function release(options: ReleaseCommandOptions) { try { - const currentVersion = readJSONSync(resolve(CWD, 'package.json')).version + const currentVersion = getVersion() if (!currentVersion) { logger.error('Your package is missing the version field') @@ -153,6 +155,10 @@ export async function release(options: ReleaseCommandOptions) { updateVersion(expectVersion) + if (options.task) { + await options.task() + } + await publish(isPreRelease) if (!isPreRelease) { diff --git a/packages/varlet-cli/src/node/compiler/compileScript.ts b/packages/varlet-cli/src/node/compiler/compileScript.ts index 3faa5a6ed53..fa0be196262 100644 --- a/packages/varlet-cli/src/node/compiler/compileScript.ts +++ b/packages/varlet-cli/src/node/compiler/compileScript.ts @@ -1,7 +1,7 @@ import fse from 'fs-extra' import { transformAsync } from '@babel/core' import { bigCamelize } from '@varlet/shared' -import { replaceExt } from '../shared/fsUtils.js' +import { getVersion, isDir, replaceExt } from '../shared/fsUtils.js' import { extractStyleDependencies, IMPORT_CSS_RE, @@ -9,35 +9,80 @@ import { REQUIRE_CSS_RE, REQUIRE_LESS_RE, } from './compileStyle.js' -import { resolve } from 'path' -import type { BabelFileResult } from '@babel/core' +import { resolve, extname, dirname } from 'path' import { get } from 'lodash-es' import { getVarletConfig } from '../config/varlet.config.js' +import type { BabelFileResult } from '@babel/core' -const { writeFileSync, readFileSync, removeSync, writeFile } = fse +const { writeFileSync, readdirSync, readFileSync, removeSync, writeFile, pathExistsSync } = fse -export const IMPORT_VUE_PATH_RE = /((? `${p1}.${getScriptExtname()}${p2}` +export const scriptExtNames = ['mjs', 'vue', 'ts', 'tsx', 'js', 'jsx'] -export const replaceVueExt = (script: string): string => - script.replace(IMPORT_VUE_PATH_RE, scriptReplacer).replace(REQUIRE_VUE_PATH_RE, scriptReplacer) +export const scriptIndexes = ['index.mjs', 'index.vue', 'index.ts', 'index.tsx', 'index.js', 'index.jsx'] -export const replaceTSExt = (script: string): string => - script.replace(IMPORT_TS_PATH_RE, scriptReplacer).replace(REQUIRE_TS_PATH_RE, scriptReplacer) +export const tryMatchExtname = (file: string, extname: string[]) => { + // eslint-disable-next-line no-restricted-syntax + for (const ext of extname) { + const matched = `${file}.${ext}` -export const replaceJSXExt = (script: string): string => - script.replace(IMPORT_JSX_PATH_RE, scriptReplacer).replace(REQUIRE_JSX_PATH_RE, scriptReplacer) + if (pathExistsSync(matched)) { + return ext + } + } +} -export const replaceTSXExt = (script: string): string => - script.replace(IMPORT_TSX_PATH_RE, scriptReplacer).replace(REQUIRE_TSX_PATH_RE, scriptReplacer) +export const resolveDependence = (file: string, script: string) => { + return script.replace(IMPORT_FROM_DEPENDENCE_RE, (source, dependence) => { + dependence = dependence.slice(1, dependence.length - 1) + const ext = extname(dependence) + const targetDependenceFile = resolve(dirname(file), dependence) + const scriptExtname = getScriptExtname() + const inNodeModules = !dependence.startsWith('.') + + if (inNodeModules) { + // e.g. @varlet/shared + return source + } + + if (!ext) { + // e.g. ../button/props -> ../button/props.m?js + const matched = tryMatchExtname(targetDependenceFile, scriptExtNames) + + if (matched) { + return source.replace(dependence, `${dependence}.${scriptExtname}`) + } + } + + if (!ext && isDir(targetDependenceFile)) { + // e.g. ../button + const files = readdirSync(targetDependenceFile) + + const hasScriptIndex = files.some((file) => scriptIndexes.some((name) => file.endsWith(name))) + + if (hasScriptIndex) { + // e.g. -> ../button/index.m?js + return source.replace(dependence, `${dependence}/index.${scriptExtname}`) + } + + const hasStyleIndex = files.some((file) => ['index.less', 'index.css'].some((name) => file.endsWith(name))) + + if (hasStyleIndex) { + // e.g. -> ../button/index.css + return source.replace(dependence, `${dependence}/index.css`) + } + } + + // e.g. ../button/props.ts -> ../button/props.m?js + return source.replace(dependence, dependence.replace(ext, `.${scriptExtname}`)) + }) +} export const moduleCompatible = async (script: string): Promise => { const moduleCompatible = get(await getVarletConfig(), 'moduleCompatible', {} as Record) @@ -61,15 +106,13 @@ export async function compileScript(script: string, file: string) { filename: file, })) as BabelFileResult - code = extractStyleDependencies(file, code as string, targetModule === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE) - code = extractStyleDependencies(file, code as string, targetModule === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE) - code = replaceVueExt(code as string) - code = replaceTSXExt(code as string) - code = replaceJSXExt(code as string) - code = replaceTSExt(code as string) - - removeSync(file) - writeFileSync(replaceExt(file, `.${getScriptExtname()}`), code, 'utf8') + if (code) { + code = extractStyleDependencies(file, code, targetModule === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE) + code = extractStyleDependencies(file, code, targetModule === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE) + code = resolveDependence(file, code) + removeSync(file) + writeFileSync(replaceExt(file, `.${getScriptExtname()}`), code, 'utf8') + } } export async function compileScriptFile(file: string) { @@ -89,19 +132,18 @@ export function getScriptExtname() { export async function compileESEntry(dir: string, publicDirs: string[]) { const imports: string[] = [] const plugins: string[] = [] - const constInternalComponents: string[] = [] + const exports: string[] = [] const cssImports: string[] = [] const publicComponents: string[] = [] const scriptExtname = getScriptExtname() publicDirs.forEach((dirname: string) => { const publicComponent = bigCamelize(dirname) + const module = `'./${dirname}/index.${scriptExtname}'` publicComponents.push(publicComponent) - imports.push(`import ${publicComponent}, * as ${publicComponent}Module from './${dirname}/index.${scriptExtname}'`) - constInternalComponents.push( - `export const _${publicComponent}Component = ${publicComponent}Module._${publicComponent}Component || {}` - ) + imports.push(`import ${publicComponent} from ${module}`) + exports.push(`export * from ${module}`) plugins.push(`${publicComponent}.install && app.use(${publicComponent})`) cssImports.push(`import './${dirname}/style/index.${scriptExtname}'`) }) @@ -112,16 +154,21 @@ function install(app) { } ` + const version = `const version = '${getVersion()}'` + const indexTemplate = `\ ${imports.join('\n')}\n -${constInternalComponents.join('\n')}\n +${exports.join('\n')}\n +${version} ${install} export { + version, install, ${publicComponents.join(',\n ')} } export default { + version, install, ${publicComponents.join(',\n ')} } @@ -134,13 +181,16 @@ ${cssImports.join('\n')} const umdTemplate = `\ ${imports.join('\n')}\n ${cssImports.join('\n')}\n +${version} ${install} export { + version, install, ${publicComponents.join(',\n ')} } export default { + version, install, ${publicComponents.join(',\n ')} } @@ -158,12 +208,15 @@ export async function compileCommonJSEntry(dir: string, publicDirs: string[]) { const plugins: string[] = [] const cssRequires: string[] = [] const publicComponents: string[] = [] + const exports: string[] = [] publicDirs.forEach((dirname: string) => { const publicComponent = bigCamelize(dirname) + const module = `'./${dirname}/index.js'` publicComponents.push(publicComponent) - requires.push(`var ${publicComponent} = require('./${dirname}/index.js')['default']`) + requires.push(`var ${publicComponent} = require(${module})['default']`) + exports.push(`...ignoreDefault(require(${module}))`) plugins.push(`${publicComponent}.install && app.use(${publicComponent})`) cssRequires.push(`require('./${dirname}/style/index.js')`) }) @@ -178,8 +231,21 @@ function install(app) { ${requires.join('\n')}\n ${install} +function ignoreDefault(module) { + return Object.keys(module).reduce((exports, key) => { + if (key !=== 'default') { + exports[key] = module[key] + } + + return exports + }, {}) +} + +exports.install = install + module.exports = { install, + ${exports.join(',\n ')} ${publicComponents.join(',\n ')} } ` diff --git a/packages/varlet-cli/src/node/compiler/compileTemplateHighlight.ts b/packages/varlet-cli/src/node/compiler/compileTemplateHighlight.ts index cec5cdc0790..65df3193627 100644 --- a/packages/varlet-cli/src/node/compiler/compileTemplateHighlight.ts +++ b/packages/varlet-cli/src/node/compiler/compileTemplateHighlight.ts @@ -11,14 +11,13 @@ import { HL_DIR, HL_TAGS_JSON, HL_ATTRIBUTES_JSON, - CLI_PACKAGE_JSON, } from '../shared/constant.js' import { resolve } from 'path' -import { isDir, isMD } from '../shared/fsUtils.js' +import { getCliVersion, isDir, isMD } from '../shared/fsUtils.js' import { get } from 'lodash-es' import { getVarletConfig } from '../config/varlet.config.js' -const { ensureDir, readdirSync, readFileSync, readJSONSync, writeFile } = fse +const { ensureDir, readdirSync, readFileSync, writeFile } = fse const TABLE_HEAD_RE = /\s*\|.*\|\s*\n\s*\|.*---+\s*\|\s*\n+/ const TABLE_FOOT_RE = /(\|\s*$)|(\|\s*\n(?!\s*\|))/ @@ -183,7 +182,7 @@ export async function compileTemplateHighlight() { const webTypes: Record = { $schema: 'https://raw.githubusercontent.com/JetBrains/web-types/master/schema/web-types.json', framework: 'vue', - version: readJSONSync(CLI_PACKAGE_JSON).version, + version: getCliVersion(), name: get(varletConfig, 'title'), contributions: { html: { diff --git a/packages/varlet-cli/src/node/index.ts b/packages/varlet-cli/src/node/index.ts index b6a48c85fe4..603f23e1269 100644 --- a/packages/varlet-cli/src/node/index.ts +++ b/packages/varlet-cli/src/node/index.ts @@ -1 +1,13 @@ export { defineConfig } from './config/varlet.config.js' +export * from './commands/release.js' +export * from './commands/dev.js' +export * from './commands/build.js' +export * from './commands/compile.js' +export * from './commands/commitLint.js' +export * from './commands/gen.js' +export * from './commands/jest.js' +export * from './commands/create.js' +export * from './commands/lint.js' +export * from './commands/changelog.js' +export * from './commands/preview.js' +export * from './commands/vite.js' diff --git a/packages/varlet-cli/src/node/shared/fsUtils.ts b/packages/varlet-cli/src/node/shared/fsUtils.ts index 0e9c2fc5e5a..800ee8830d0 100644 --- a/packages/varlet-cli/src/node/shared/fsUtils.ts +++ b/packages/varlet-cli/src/node/shared/fsUtils.ts @@ -1,10 +1,19 @@ import globSync from 'glob' import fse from 'fs-extra' import { extname, resolve } from 'path' -import { PUBLIC_DIR_INDEXES, SCRIPTS_EXTENSIONS, SRC_DIR } from './constant.js' +import { CLI_PACKAGE_JSON, PUBLIC_DIR_INDEXES, SCRIPTS_EXTENSIONS, SRC_DIR, UI_PACKAGE_JSON } from './constant.js' import { fileURLToPath } from 'url' -const { appendFileSync, ensureFileSync, lstatSync, outputFileSync, pathExistsSync, readdir, readFileSync } = fse +const { + appendFileSync, + ensureFileSync, + lstatSync, + outputFileSync, + pathExistsSync, + readdir, + readFileSync, + readJSONSync, +} = fse export async function getPublicDirs(): Promise { const srcDir: string[] = await readdir(SRC_DIR) @@ -61,3 +70,11 @@ export function glob(pattern: string): Promise { export function getDirname(url: string) { return fileURLToPath(new URL('.', url)) } + +export function getVersion() { + return readJSONSync(UI_PACKAGE_JSON).version +} + +export function getCliVersion() { + return readJSONSync(CLI_PACKAGE_JSON).version +} diff --git a/scripts/bootstrap.mjs b/scripts/bootstrap.mjs index 60572b43e23..a01f031d9ad 100644 --- a/scripts/bootstrap.mjs +++ b/scripts/bootstrap.mjs @@ -1,11 +1,9 @@ import { buildCli, buildIcons, buildShared, buildUI, buildVitePlugins, runTask } from './build.mjs' -(async () => { - await runTask('shared', buildShared) - await Promise.all([ - runTask('cli', buildCli), - runTask('vite plugins', buildVitePlugins), - runTask('icons', buildIcons) - ]) - await runTask('ui', buildUI) -})() +await runTask('shared', buildShared) +await Promise.all([ + runTask('cli', buildCli), + runTask('vite plugins', buildVitePlugins), + runTask('icons', buildIcons) +]) +await runTask('ui', buildUI) diff --git a/scripts/publish.mjs b/scripts/release.mjs similarity index 78% rename from scripts/publish.mjs rename to scripts/release.mjs index a10ba49aff2..75a0f80adbc 100644 --- a/scripts/publish.mjs +++ b/scripts/release.mjs @@ -1,6 +1,7 @@ import { buildCli, buildIcons, buildShared, buildUI, buildVitePlugins, runTask } from './build.mjs' +import { release } from '@varlet/cli' -(async () => { +async function task() { await runTask('shared', buildShared) await Promise.all([ runTask('cli', buildCli), @@ -8,4 +9,6 @@ import { buildCli, buildIcons, buildShared, buildUI, buildVitePlugins, runTask } runTask('icons', buildIcons) ]) await runTask('ui', () => buildUI(false)) -})() +} + +await release({ task }) From c64575b14fa561bf8e8ee90c908fc7054f174e3d Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 20:51:26 +0800 Subject: [PATCH 03/21] refactor(cli): wip --- .../src/node/compiler/compileModule.ts | 2 +- .../src/node/compiler/compileScript.ts | 78 +++++++++++++------ .../src/node/compiler/compileStyle.ts | 2 +- 3 files changed, 56 insertions(+), 26 deletions(-) diff --git a/packages/varlet-cli/src/node/compiler/compileModule.ts b/packages/varlet-cli/src/node/compiler/compileModule.ts index d06a61f0c5c..2ceda7a9ece 100644 --- a/packages/varlet-cli/src/node/compiler/compileModule.ts +++ b/packages/varlet-cli/src/node/compiler/compileModule.ts @@ -76,7 +76,7 @@ export async function compileModule() { moduleDir.map((filename: string) => { const file: string = resolve(dest, filename) - isDir(file) && ensureFileSync(resolve(file, `./style/index.${getScriptExtname()}`)) + isDir(file) && ensureFileSync(resolve(file, `./style/index${getScriptExtname()}`)) return isDir(file) ? compileDir(file) : null }) diff --git a/packages/varlet-cli/src/node/compiler/compileScript.ts b/packages/varlet-cli/src/node/compiler/compileScript.ts index fa0be196262..3cb235636ee 100644 --- a/packages/varlet-cli/src/node/compiler/compileScript.ts +++ b/packages/varlet-cli/src/node/compiler/compileScript.ts @@ -19,18 +19,22 @@ const { writeFileSync, readdirSync, readFileSync, removeSync, writeFile, pathExi // https://regexr.com/765a4 export const IMPORT_FROM_DEPENDENCE_RE = /import\s+?[\w\s{},$*]+\s+from\s+?(".*?"|'.*?')/g // https://regexr.com/764ve -export const IMPORT_DEPENDENCE_RE = /import\s+['"]\s*\.{1,2}\/(.+)\s*['"];?/g +export const IMPORT_DEPENDENCE_RE = /import\s+(".*?"|'.*?')/g // https://regexr.com/764vn -export const REQUIRE_DEPENDENCE_RE = /require\(['"]\s*(\.{1,2}\/.+)\s*['"]\)/g +export const REQUIRE_DEPENDENCE_RE = /require\((".*?"|'.*?')\)/g -export const scriptExtNames = ['mjs', 'vue', 'ts', 'tsx', 'js', 'jsx'] +export const scriptExtNames = ['.vue', '.ts', '.tsx', '.mjs', '.js', '.jsx'] + +export const styleExtNames = ['.less', '.css'] export const scriptIndexes = ['index.mjs', 'index.vue', 'index.ts', 'index.tsx', 'index.js', 'index.jsx'] +export const styleIndexes = ['index.less', 'index.css'] + export const tryMatchExtname = (file: string, extname: string[]) => { // eslint-disable-next-line no-restricted-syntax for (const ext of extname) { - const matched = `${file}.${ext}` + const matched = `${file}${ext}` if (pathExistsSync(matched)) { return ext @@ -39,24 +43,44 @@ export const tryMatchExtname = (file: string, extname: string[]) => { } export const resolveDependence = (file: string, script: string) => { - return script.replace(IMPORT_FROM_DEPENDENCE_RE, (source, dependence) => { + const replacer = (source: string, dependence: string) => { dependence = dependence.slice(1, dependence.length - 1) + const ext = extname(dependence) const targetDependenceFile = resolve(dirname(file), dependence) const scriptExtname = getScriptExtname() const inNodeModules = !dependence.startsWith('.') + const done = (targetDependence: string) => source.replace(dependence, targetDependence) if (inNodeModules) { // e.g. @varlet/shared return source } + if (ext) { + if (scriptExtNames.includes(ext)) { + // e.g. './a.vue' -> './a.m?js' + return done(dependence.replace(ext, scriptExtname)) + } + + if (styleExtNames.includes(ext)) { + // e.g. './a.css' -> './a.css' './a.less' -> './a.less' + return source + } + } + if (!ext) { // e.g. ../button/props -> ../button/props.m?js - const matched = tryMatchExtname(targetDependenceFile, scriptExtNames) + const matchedScript = tryMatchExtname(targetDependenceFile, scriptExtNames) + + if (matchedScript) { + return done(`${dependence}${scriptExtname}`) + } + + const matchedStyle = tryMatchExtname(targetDependenceFile, styleExtNames) - if (matched) { - return source.replace(dependence, `${dependence}.${scriptExtname}`) + if (matchedStyle) { + return done(`${dependence}${matchedStyle}`) } } @@ -68,20 +92,24 @@ export const resolveDependence = (file: string, script: string) => { if (hasScriptIndex) { // e.g. -> ../button/index.m?js - return source.replace(dependence, `${dependence}/index.${scriptExtname}`) + return done(`${dependence}/index${scriptExtname}`) } - const hasStyleIndex = files.some((file) => ['index.less', 'index.css'].some((name) => file.endsWith(name))) + const hasStyleIndex = files.some((file) => styleIndexes.some((name) => file.endsWith(name))) if (hasStyleIndex) { // e.g. -> ../button/index.css - return source.replace(dependence, `${dependence}/index.css`) + return done(`${dependence}/index.css`) } } - // e.g. ../button/props.ts -> ../button/props.m?js - return source.replace(dependence, dependence.replace(ext, `.${scriptExtname}`)) - }) + return '' + } + + return script + .replace(IMPORT_FROM_DEPENDENCE_RE, replacer) + .replace(IMPORT_DEPENDENCE_RE, replacer) + .replace(REQUIRE_DEPENDENCE_RE, replacer) } export const moduleCompatible = async (script: string): Promise => { @@ -107,11 +135,11 @@ export async function compileScript(script: string, file: string) { })) as BabelFileResult if (code) { + code = resolveDependence(file, code) code = extractStyleDependencies(file, code, targetModule === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE) code = extractStyleDependencies(file, code, targetModule === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE) - code = resolveDependence(file, code) removeSync(file) - writeFileSync(replaceExt(file, `.${getScriptExtname()}`), code, 'utf8') + writeFileSync(replaceExt(file, getScriptExtname()), code, 'utf8') } } @@ -123,10 +151,10 @@ export async function compileScriptFile(file: string) { export function getScriptExtname() { if (process.env.TARGET_MODULE === 'module') { - return 'mjs' + return '.mjs' } - return 'js' + return '.js' } export async function compileESEntry(dir: string, publicDirs: string[]) { @@ -139,13 +167,13 @@ export async function compileESEntry(dir: string, publicDirs: string[]) { publicDirs.forEach((dirname: string) => { const publicComponent = bigCamelize(dirname) - const module = `'./${dirname}/index.${scriptExtname}'` + const module = `'./${dirname}/index${scriptExtname}'` publicComponents.push(publicComponent) imports.push(`import ${publicComponent} from ${module}`) exports.push(`export * from ${module}`) plugins.push(`${publicComponent}.install && app.use(${publicComponent})`) - cssImports.push(`import './${dirname}/style/index.${scriptExtname}'`) + cssImports.push(`import './${dirname}/style/index${scriptExtname}'`) }) const install = ` @@ -221,6 +249,8 @@ export async function compileCommonJSEntry(dir: string, publicDirs: string[]) { cssRequires.push(`require('./${dirname}/style/index.js')`) }) + const version = `const version = '${getVersion()}'` + const install = ` function install(app) { ${plugins.join('\n ')} @@ -229,11 +259,12 @@ function install(app) { const indexTemplate = `\ ${requires.join('\n')}\n +${version} ${install} function ignoreDefault(module) { return Object.keys(module).reduce((exports, key) => { - if (key !=== 'default') { + if (key !== 'default') { exports[key] = module[key] } @@ -241,11 +272,10 @@ function ignoreDefault(module) { }, {}) } -exports.install = install - module.exports = { + version, install, - ${exports.join(',\n ')} + ${exports.join(',\n ')}, ${publicComponents.join(',\n ')} } ` diff --git a/packages/varlet-cli/src/node/compiler/compileStyle.ts b/packages/varlet-cli/src/node/compiler/compileStyle.ts index e2713b82c5d..85ad78d4262 100644 --- a/packages/varlet-cli/src/node/compiler/compileStyle.ts +++ b/packages/varlet-cli/src/node/compiler/compileStyle.ts @@ -31,7 +31,7 @@ export function normalizeStyleDependency(styleImport: string, reg: RegExp) { export function extractStyleDependencies(file: string, code: string, styleReg: RegExp) { const styleImports = code.match(styleReg) ?? [] - const cssFile = resolve(parse(file).dir, `./style/index.${getScriptExtname()}`) + const cssFile = resolve(parse(file).dir, `./style/index${getScriptExtname()}`) const targetModule = process.env.TARGET_MODULE styleImports.forEach((styleImport: string) => { From 1178457d5466996330454c71c2fd6e9aedbf9d97 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 23:02:25 +0800 Subject: [PATCH 04/21] refactor: wip --- packages/varlet-cli/lib/node/bin.js | 5 +- packages/varlet-cli/src/node/bin.ts | 5 +- .../varlet-cli/src/node/commands/compile.ts | 14 ++-- .../src/node/compiler/compileModule.ts | 46 ++++++++----- .../varlet-cli/src/node/config/vite.config.ts | 67 ++++++------------- packages/varlet-ui/package.json | 2 +- packages/varlet-vite-plugins/src/inlineCss.ts | 3 +- scripts/build.mjs | 2 +- scripts/release.mjs | 2 +- 9 files changed, 65 insertions(+), 81 deletions(-) diff --git a/packages/varlet-cli/lib/node/bin.js b/packages/varlet-cli/lib/node/bin.js index b8e8be26f81..7ab4f8af36e 100755 --- a/packages/varlet-cli/lib/node/bin.js +++ b/packages/varlet-cli/lib/node/bin.js @@ -42,10 +42,9 @@ program program .command('compile') .description('Compile varlet components library code') - .option('-nu, --noUmd', 'Do not compile umd target code') - .action(async (options) => { + .action(async () => { const { compile } = await import('./commands/compile.js'); - return compile(options); + return compile(); }); program .command('lint') diff --git a/packages/varlet-cli/src/node/bin.ts b/packages/varlet-cli/src/node/bin.ts index 358f7500d68..4de725dce20 100644 --- a/packages/varlet-cli/src/node/bin.ts +++ b/packages/varlet-cli/src/node/bin.ts @@ -55,11 +55,10 @@ program program .command('compile') .description('Compile varlet components library code') - .option('-nu, --noUmd', 'Do not compile umd target code') - .action(async (options) => { + .action(async () => { const { compile } = await import('./commands/compile.js') - return compile(options) + return compile() }) program diff --git a/packages/varlet-cli/src/node/commands/compile.ts b/packages/varlet-cli/src/node/commands/compile.ts index be68b5b4dba..9a825cd7ac3 100644 --- a/packages/varlet-cli/src/node/commands/compile.ts +++ b/packages/varlet-cli/src/node/commands/compile.ts @@ -23,11 +23,7 @@ export async function runTask(taskName: string, task: () => any) { } } -interface CompileCommandOptions { - noUmd?: boolean -} - -export async function compile(options: CompileCommandOptions) { +export async function compile() { process.env.NODE_ENV = 'compile' await removeDir() @@ -37,13 +33,11 @@ export async function compile(options: CompileCommandOptions) { process.env.BABEL_MODULE = 'module' await runTask('module', compileModule) - process.env.TARGET_MODULE = 'esm-bundle' - await runTask('esm bundle', compileModule) - process.env.TARGET_MODULE = 'commonjs' process.env.BABEL_MODULE = 'commonjs' await runTask('commonjs', compileModule) - process.env.TARGET_MODULE = 'umd' - !options.noUmd && (await runTask('umd', compileModule)) + process.env.BABEL_MODULE = '' + process.env.TARGET_MODULE = 'bundle' + await runTask('bundle', compileModule) } diff --git a/packages/varlet-cli/src/node/compiler/compileModule.ts b/packages/varlet-cli/src/node/compiler/compileModule.ts index 2ceda7a9ece..b026c64889a 100644 --- a/packages/varlet-cli/src/node/compiler/compileModule.ts +++ b/packages/varlet-cli/src/node/compiler/compileModule.ts @@ -9,25 +9,46 @@ import { ES_DIR, STYLE_DIR_NAME, LIB_DIR, + UMD_DIR, } from '../shared/constant.js' import { getPublicDirs, isDir, isDTS, isLess, isScript, isSFC } from '../shared/fsUtils.js' import { compileSFC } from './compileSFC.js' import { compileESEntry, compileCommonJSEntry, compileScriptFile, getScriptExtname } from './compileScript.js' import { clearLessFiles, compileLess } from './compileStyle.js' -import { getESMBundleConfig, getUMDConfig } from '../config/vite.config.js' +import { BundleBuildOptions, getBundleConfig } from '../config/vite.config.js' import { getVarletConfig } from '../config/varlet.config.js' import { generateReference } from './compileTypes.js' +import { get } from 'lodash-es' +import { kebabCase } from '@varlet/shared' const { copy, ensureFileSync, readdir, removeSync } = fse -export async function compileUMD() { +export async function compileBundle() { const varletConfig = await getVarletConfig() - await build(getUMDConfig(varletConfig)) -} - -export async function compileESMBundle() { - const varletConfig = await getVarletConfig() - await build(getESMBundleConfig(varletConfig)) + const name = kebabCase(get(varletConfig, 'name')) + const buildOptions: BundleBuildOptions[] = [ + { + format: 'es', + fileName: `${name}.esm.js`, + output: ES_DIR, + emptyOutDir: false, + }, + { + format: 'cjs', + fileName: `${name}.cjs.js`, + output: LIB_DIR, + emptyOutDir: false, + }, + { + format: 'umd', + fileName: `${name}.js`, + output: UMD_DIR, + emptyOutDir: true, + }, + ] + const tasks = buildOptions.map((options) => build(getBundleConfig(varletConfig, options))) + + await Promise.all(tasks) } export async function compileDir(dir: string) { @@ -58,13 +79,8 @@ export async function compileFile(file: string) { export async function compileModule() { const targetModule = process.env.TARGET_MODULE - if (targetModule === 'umd') { - await compileUMD() - return - } - - if (targetModule === 'esm-bundle') { - await compileESMBundle() + if (targetModule === 'bundle') { + await compileBundle() return } diff --git a/packages/varlet-cli/src/node/config/vite.config.ts b/packages/varlet-cli/src/node/config/vite.config.ts index ea0a7d3b6c9..3768772edb3 100644 --- a/packages/varlet-cli/src/node/config/vite.config.ts +++ b/packages/varlet-cli/src/node/config/vite.config.ts @@ -90,58 +90,44 @@ export function getBuildConfig(varletConfig: Required): InlineConf } } -export function getESMBundleConfig(varletConfig: Required): InlineConfig { - const name = get(varletConfig, 'name') - const fileName = `${kebabCase(name)}.esm.js` - - return { - logLevel: 'silent', - - build: { - emptyOutDir: false, - copyPublicDir: false, - lib: { - name, - formats: ['es'], - fileName: () => fileName, - entry: resolve(ES_DIR, 'index.umd.mjs'), - }, - rollupOptions: { - external: ['vue'], - output: { - dir: ES_DIR, - exports: 'named', - globals: { - vue: 'Vue', - }, - }, - }, - }, - } +export interface BundleBuildOptions { + fileName: string + output: string + format: 'es' | 'cjs' | 'umd' + emptyOutDir: boolean } -export function getUMDConfig(varletConfig: Required): InlineConfig { +export function getBundleConfig(varletConfig: Required, buildOptions: BundleBuildOptions): InlineConfig { + const plugins = [] const name = get(varletConfig, 'name') - const fileName = `${kebabCase(name)}.js` - const jsFile = resolve(UMD_DIR, fileName) - const cssFile = resolve(UMD_DIR, 'style.css') + const { fileName, output, format, emptyOutDir } = buildOptions + + if (format === 'umd') { + plugins.push( + inlineCss({ + jsFile: resolve(output, fileName), + cssFile: resolve(output, 'style.css'), + }) + ) + } return { logLevel: 'silent', build: { - emptyOutDir: true, + minify: format === 'cjs' ? false : 'esbuild', + emptyOutDir, copyPublicDir: false, lib: { name, - formats: ['umd'], + formats: [format], fileName: () => fileName, entry: resolve(ES_DIR, 'index.umd.mjs'), }, rollupOptions: { external: ['vue'], output: { - dir: UMD_DIR, + dir: output, exports: 'named', globals: { vue: 'Vue', @@ -149,16 +135,5 @@ export function getUMDConfig(varletConfig: Required): InlineConfig }, }, }, - - plugins: [ - inlineCss({ - jsFile, - cssFile, - onEnd() { - copyFileSync(cssFile, resolve(LIB_DIR, 'style.css')) - removeSync(cssFile) - }, - }), - ], } } diff --git a/packages/varlet-ui/package.json b/packages/varlet-ui/package.json index 9a53fea9d44..02d4aa42dba 100644 --- a/packages/varlet-ui/package.json +++ b/packages/varlet-ui/package.json @@ -2,7 +2,7 @@ "name": "@varlet/ui", "version": "2.6.2", "description": "A material like components library", - "main": "lib/index.js", + "main": "lib/varlet.cjs.js", "module": "es/index.mjs", "typings": "types/index.d.ts", "vetur": { diff --git a/packages/varlet-vite-plugins/src/inlineCss.ts b/packages/varlet-vite-plugins/src/inlineCss.ts index 1af3c31c62f..df12c7abc44 100644 --- a/packages/varlet-vite-plugins/src/inlineCss.ts +++ b/packages/varlet-vite-plugins/src/inlineCss.ts @@ -1,7 +1,7 @@ import type { Plugin } from 'vite' import fse from 'fs-extra' -const { pathExistsSync, writeFileSync, readFileSync } = fse +const { pathExistsSync, writeFileSync, readFileSync, removeSync } = fse export interface InlineCssOptions { cssFile: string @@ -37,6 +37,7 @@ style.rel='stylesheet';style.appendChild(document.createTextNode(\`${cssCode.rep var head=document.querySelector('head');head.appendChild(style)})();` writeFileSync(jsFile, `${injectCode}${jsCode}`) + removeSync(cssFile) onEnd?.() }, } diff --git a/scripts/build.mjs b/scripts/build.mjs index bcb9c9bc492..7bd3e90fcde 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -17,7 +17,7 @@ export const buildShared = () => execa('pnpm', ['build'], { cwd: PKG_SHARED }) export const buildIcons = () => execa('pnpm', ['build'], { cwd: PKG_ICONS }) -export const buildUI = (noUmd) => execa('pnpm', ['compile', noUmd ? '--noUmd' : ''], { cwd: PKG_UI }) +export const buildUI = () => execa('pnpm', ['compile'], { cwd: PKG_UI }) export async function runTask(taskName, task) { const s = ora().start(`Building ${taskName}`) diff --git a/scripts/release.mjs b/scripts/release.mjs index 75a0f80adbc..c53838c1da6 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -8,7 +8,7 @@ async function task() { runTask('vite plugins', buildVitePlugins), runTask('icons', buildIcons) ]) - await runTask('ui', () => buildUI(false)) + await runTask('ui', buildUI) } await release({ task }) From a27b9fa10207ae443c5cf1134347292418e091ae Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 23:25:44 +0800 Subject: [PATCH 05/21] refactor: wip --- packages/varlet-cli/src/node/compiler/compileTypes.ts | 1 + packages/varlet-ui/src/button/index.ts | 2 ++ packages/varlet-ui/types/button.d.ts | 2 ++ 3 files changed, 5 insertions(+) diff --git a/packages/varlet-cli/src/node/compiler/compileTypes.ts b/packages/varlet-cli/src/node/compiler/compileTypes.ts index 42212198d05..4a9d9032824 100644 --- a/packages/varlet-cli/src/node/compiler/compileTypes.ts +++ b/packages/varlet-cli/src/node/compiler/compileTypes.ts @@ -51,6 +51,7 @@ declare module 'vue' { const template = `\ import type { App } from 'vue' +export const version: string export const install: (app: App) => void ${exports.join('\n')} diff --git a/packages/varlet-ui/src/button/index.ts b/packages/varlet-ui/src/button/index.ts index ea60ae4002b..09acd8f781f 100644 --- a/packages/varlet-ui/src/button/index.ts +++ b/packages/varlet-ui/src/button/index.ts @@ -5,6 +5,8 @@ Button.install = function (app: App) { app.component(Button.name, Button) } +export { props as buttonProps } from './props' + export const _ButtonComponent = Button export default Button diff --git a/packages/varlet-ui/types/button.d.ts b/packages/varlet-ui/types/button.d.ts index dfcc2fe7c5e..ec4f6df586f 100644 --- a/packages/varlet-ui/types/button.d.ts +++ b/packages/varlet-ui/types/button.d.ts @@ -4,6 +4,8 @@ import { ButtonHTMLAttributes, VNode } from 'vue' export { ButtonType, ButtonSize } +export declare const buttonProps: Record + export interface ButtonProps extends BasicAttributes { type?: ButtonType nativeType?: ButtonHTMLAttributes['type'] From bf2d29bc8af8d3550692f3239299deea411254e2 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 23:39:44 +0800 Subject: [PATCH 06/21] refactor: wip --- packages/varlet-cli/src/node/compiler/compileScript.ts | 7 +++++-- packages/varlet-cli/src/node/config/vite.config.ts | 8 +------- packages/varlet-ui/types/index.d.ts | 1 + 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/packages/varlet-cli/src/node/compiler/compileScript.ts b/packages/varlet-cli/src/node/compiler/compileScript.ts index 3cb235636ee..bc090f5b9b5 100644 --- a/packages/varlet-cli/src/node/compiler/compileScript.ts +++ b/packages/varlet-cli/src/node/compiler/compileScript.ts @@ -18,6 +18,8 @@ const { writeFileSync, readdirSync, readFileSync, removeSync, writeFile, pathExi // https://regexr.com/765a4 export const IMPORT_FROM_DEPENDENCE_RE = /import\s+?[\w\s{},$*]+\s+from\s+?(".*?"|'.*?')/g +// https://regexr.com/767e6 +export const EXPORT_FROM_DEPENDENCE_RE = /export\s+?[\w\s{},$*]+\s+from\s+?(".*?"|'.*?')/g // https://regexr.com/764ve export const IMPORT_DEPENDENCE_RE = /import\s+(".*?"|'.*?')/g // https://regexr.com/764vn @@ -108,6 +110,7 @@ export const resolveDependence = (file: string, script: string) => { return script .replace(IMPORT_FROM_DEPENDENCE_RE, replacer) + .replace(EXPORT_FROM_DEPENDENCE_RE, replacer) .replace(IMPORT_DEPENDENCE_RE, replacer) .replace(REQUIRE_DEPENDENCE_RE, replacer) } @@ -206,7 +209,7 @@ export default { ${cssImports.join('\n')} ` - const umdTemplate = `\ + const bundleTemplate = `\ ${imports.join('\n')}\n ${cssImports.join('\n')}\n ${version} @@ -226,7 +229,7 @@ export default { await Promise.all([ writeFile(resolve(dir, 'index.mjs'), indexTemplate, 'utf-8'), - writeFile(resolve(dir, 'index.umd.mjs'), umdTemplate, 'utf-8'), + writeFile(resolve(dir, 'index.bundle.mjs'), bundleTemplate, 'utf-8'), writeFile(resolve(dir, 'style.mjs'), styleTemplate, 'utf-8'), ]) } diff --git a/packages/varlet-cli/src/node/config/vite.config.ts b/packages/varlet-cli/src/node/config/vite.config.ts index 3768772edb3..f788058b160 100644 --- a/packages/varlet-cli/src/node/config/vite.config.ts +++ b/packages/varlet-cli/src/node/config/vite.config.ts @@ -1,18 +1,14 @@ -import fse from 'fs-extra' import vue from '@vitejs/plugin-vue' import jsx from '@vitejs/plugin-vue-jsx' import { markdown, html, inlineCss } from '@varlet/vite-plugins' -import { kebabCase } from '@varlet/shared' import { ES_DIR, - LIB_DIR, SITE_CONFIG, SITE_DIR, SITE_MOBILE_ROUTES, SITE_OUTPUT_PATH, SITE_PC_ROUTES, SITE_PUBLIC_PATH, - UMD_DIR, VITE_RESOLVE_EXTENSIONS, } from '../shared/constant.js' import { InlineConfig } from 'vite' @@ -20,8 +16,6 @@ import { get } from 'lodash-es' import { resolve } from 'path' import { VarletConfig } from './varlet.config' -const { copyFileSync, removeSync } = fse - export function getDevConfig(varletConfig: Required): InlineConfig { const defaultLanguage = get(varletConfig, 'defaultLanguage') const host = get(varletConfig, 'host') @@ -122,7 +116,7 @@ export function getBundleConfig(varletConfig: Required, buildOptio name, formats: [format], fileName: () => fileName, - entry: resolve(ES_DIR, 'index.umd.mjs'), + entry: resolve(ES_DIR, 'index.bundle.mjs'), }, rollupOptions: { external: ['vue'], diff --git a/packages/varlet-ui/types/index.d.ts b/packages/varlet-ui/types/index.d.ts index 466984da40b..aba0407b268 100644 --- a/packages/varlet-ui/types/index.d.ts +++ b/packages/varlet-ui/types/index.d.ts @@ -1,5 +1,6 @@ import type { App } from 'vue' +export const version: string export const install: (app: App) => void export * from './actionSheet' From f2498b2641605aceea61c6cde293012c49bf3c1e Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Fri, 13 Jan 2023 23:57:58 +0800 Subject: [PATCH 07/21] refactor: wip --- scripts/bootstrap.mjs | 10 ++-------- scripts/build.mjs | 12 ++++++++++++ scripts/release.mjs | 14 ++------------ 3 files changed, 16 insertions(+), 20 deletions(-) diff --git a/scripts/bootstrap.mjs b/scripts/bootstrap.mjs index a01f031d9ad..1ce0bd7dc4b 100644 --- a/scripts/bootstrap.mjs +++ b/scripts/bootstrap.mjs @@ -1,9 +1,3 @@ -import { buildCli, buildIcons, buildShared, buildUI, buildVitePlugins, runTask } from './build.mjs' +import { runTaskQueue } from './build.mjs' -await runTask('shared', buildShared) -await Promise.all([ - runTask('cli', buildCli), - runTask('vite plugins', buildVitePlugins), - runTask('icons', buildIcons) -]) -await runTask('ui', buildUI) +await runTaskQueue() diff --git a/scripts/build.mjs b/scripts/build.mjs index 7bd3e90fcde..da8c30fb4f7 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -29,3 +29,15 @@ export async function runTask(taskName, task) { console.error(e.toString()) } } + +export async function runTaskQueue() { + await runTask('shared', buildShared) + + await Promise.all([ + runTask('cli', buildCli), + runTask('vite plugins', buildVitePlugins), + runTask('icons', buildIcons) + ]) + + await runTask('ui', buildUI) +} diff --git a/scripts/release.mjs b/scripts/release.mjs index c53838c1da6..1a557754fd0 100644 --- a/scripts/release.mjs +++ b/scripts/release.mjs @@ -1,14 +1,4 @@ -import { buildCli, buildIcons, buildShared, buildUI, buildVitePlugins, runTask } from './build.mjs' +import { runTaskQueue } from './build.mjs' import { release } from '@varlet/cli' -async function task() { - await runTask('shared', buildShared) - await Promise.all([ - runTask('cli', buildCli), - runTask('vite plugins', buildVitePlugins), - runTask('icons', buildIcons) - ]) - await runTask('ui', buildUI) -} - -await release({ task }) +await release({ task: runTaskQueue }) From 5fe07ce168639b84b6898182f1d4aa26c2168102 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Sat, 14 Jan 2023 00:07:15 +0800 Subject: [PATCH 08/21] refactor: wip --- .../template/generators/config/default/base/package.json | 4 ++-- .../template/generators/config/i18n/base/package.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/varlet-cli/template/generators/config/default/base/package.json b/packages/varlet-cli/template/generators/config/default/base/package.json index b8a55c7e298..5aac3f495fa 100644 --- a/packages/varlet-cli/template/generators/config/default/base/package.json +++ b/packages/varlet-cli/template/generators/config/default/base/package.json @@ -2,8 +2,8 @@ "name": "@varlet/ui", "version": "0.0.0", "description": "A components library example", - "main": "lib/index.js", - "module": "es/index.js", + "main": "lib/varlet.cjs.js", + "module": "es/index.mjs", "typings": "types/index.d.ts", "vetur": { "tags": "highlight/tags.json", diff --git a/packages/varlet-cli/template/generators/config/i18n/base/package.json b/packages/varlet-cli/template/generators/config/i18n/base/package.json index b8a55c7e298..5aac3f495fa 100644 --- a/packages/varlet-cli/template/generators/config/i18n/base/package.json +++ b/packages/varlet-cli/template/generators/config/i18n/base/package.json @@ -2,8 +2,8 @@ "name": "@varlet/ui", "version": "0.0.0", "description": "A components library example", - "main": "lib/index.js", - "module": "es/index.js", + "main": "lib/varlet.cjs.js", + "module": "es/index.mjs", "typings": "types/index.d.ts", "vetur": { "tags": "highlight/tags.json", From f9bc29845a79e3bc84129718d73e109f7cbd3f38 Mon Sep 17 00:00:00 2001 From: haoziqaq <357229046@qq.com> Date: Sat, 14 Jan 2023 00:26:01 +0800 Subject: [PATCH 09/21] refactor: wip --- packages/varlet-ui/docs/importOnDemand.en-US.md | 8 ++++---- packages/varlet-ui/docs/importOnDemand.zh-CN.md | 8 ++++---- packages/varlet-ui/docs/quickstart.en-US.md | 2 +- packages/varlet-ui/docs/quickstart.zh-CN.md | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/varlet-ui/docs/importOnDemand.en-US.md b/packages/varlet-ui/docs/importOnDemand.en-US.md index eeaef5e68c3..c0e699554bf 100644 --- a/packages/varlet-ui/docs/importOnDemand.en-US.md +++ b/packages/varlet-ui/docs/importOnDemand.en-US.md @@ -12,7 +12,7 @@ Each component is a `Vue plugin` and consists of `component logic` and `style fi // playground-ignore import { createApp } from 'vue' import { Button } from '@varlet/ui' -import '@varlet/ui/es/button/style/index.js' +import '@varlet/ui/es/button/style/index' createApp().use(Button) ```` @@ -23,7 +23,7 @@ OR // playground-ignore