Skip to content

Commit

Permalink
fix(cli/compile): add commonjs bundle
Browse files Browse the repository at this point in the history
affects: @varlet/cli, @varlet/ui
  • Loading branch information
haoziqaq committed Nov 20, 2021
1 parent 9c3f547 commit 4a424d4
Show file tree
Hide file tree
Showing 13 changed files with 134 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ packages/varlet-cli/site/site.config.json
packages/varlet-cli/site/*.site.config.json

packages/varlet-ui/site
packages/varlet-ui/lib
packages/varlet-ui/es
packages/varlet-ui/cjs
packages/varlet-ui/umd
packages/varlet-ui/coverage
packages/varlet-ui/highlight
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"packages/varlet-cli/site/**",
"packages/varlet-cli/generators/**",
"packages/varlet-vscode-extension/dist/**",
"packages/varlet-ui/lib/**",
"packages/varlet-ui/es/**",
"packages/varlet-ui/umd/**",
"packages/varlet-ui/site/**",
Expand All @@ -55,6 +56,7 @@
"packages/varlet-cli/site/**",
"packages/varlet-cli/generators/**",
"packages/varlet-icons/dist/**",
"packages/varlet-ui/lib/**",
"packages/varlet-ui/es/**",
"packages/varlet-ui/umd/**",
"packages/varlet-ui/site/**",
Expand Down
1 change: 1 addition & 0 deletions packages/varlet-cli/generators/sfc/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ node_modules
.DS_Store

site
lib
es
umd
coverage
Expand Down
3 changes: 3 additions & 0 deletions packages/varlet-cli/generators/sfc/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "basic-ui",
"version": "0.0.0",
"description": "A basic components library",
"main": "lib/index.js",
"module": "es/index.js",
"typings": "types/index.d.ts",
"vetur": {
Expand Down Expand Up @@ -64,6 +65,7 @@
"eslintConfig": {
"root": true,
"ignorePatterns": [
"lib/**",
"es/**",
"umd/**",
"site/**",
Expand All @@ -80,6 +82,7 @@
"@varlet/stylelint-config"
],
"ignoreFiles": [
"lib/**",
"es/**",
"umd/**",
"site/**",
Expand Down
1 change: 1 addition & 0 deletions packages/varlet-cli/generators/tsx/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ node_modules
.DS_Store

site
lib
es
umd
coverage
Expand Down
3 changes: 3 additions & 0 deletions packages/varlet-cli/generators/tsx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"name": "basic-ui",
"version": "0.0.0",
"description": "A basic components library",
"main": "lib/index.js",
"module": "es/index.js",
"typings": "types/index.d.ts",
"vetur": {
Expand Down Expand Up @@ -64,6 +65,7 @@
"eslintConfig": {
"root": true,
"ignorePatterns": [
"lib/**",
"es/**",
"umd/**",
"site/**",
Expand All @@ -80,6 +82,7 @@
"@varlet/stylelint-config"
],
"ignoreFiles": [
"lib/**",
"es/**",
"umd/**",
"site/**",
Expand Down
13 changes: 6 additions & 7 deletions packages/varlet-cli/src/commands/compile.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import ora from 'ora'
import logger from '../shared/logger'
import { remove } from 'fs-extra'
import { ES_DIR, HL_DIR, UMD_DIR } from '../shared/constant'
import { ES_DIR, HL_DIR, LIB_DIR, UMD_DIR } from '../shared/constant'
import { compileModule } from '../compiler/compileModule'
import { compileTemplateHighlight } from '../compiler/compileTemplateHighlight'
import { compileTypes } from '../compiler/compileTypes'

export function removeDir() {
return Promise.all([remove(ES_DIR), remove(HL_DIR), remove(UMD_DIR)])
return Promise.all([remove(ES_DIR), remove(LIB_DIR), remove(HL_DIR), remove(UMD_DIR)])
}

export async function runTask(taskName: string, task: () => any) {
Expand All @@ -25,10 +25,9 @@ export async function compile(cmd: { noUmd: boolean }) {
process.env.NODE_ENV = 'compile'

await removeDir()
await Promise.all([
runTask('types', compileTypes),
runTask('template highlight', compileTemplateHighlight),
runTask('module', compileModule),
])
await Promise.all([runTask('types', compileTypes), runTask('template highlight', compileTemplateHighlight)])

await runTask('module', compileModule)
await runTask('commonjs', () => compileModule('commonjs'))
!cmd.noUmd && (await runTask('umd', () => compileModule('umd')))
}
25 changes: 19 additions & 6 deletions packages/varlet-cli/src/compiler/compileModule.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import { build } from 'vite'
import { resolve } from 'path'
import { copy, ensureFileSync, readdir, removeSync } from 'fs-extra'
import { EXAMPLE_DIR_NAME, TESTS_DIR_NAME, DOCS_DIR_NAME, SRC_DIR, ES_DIR, STYLE_DIR_NAME } from '../shared/constant'
import {
EXAMPLE_DIR_NAME,
TESTS_DIR_NAME,
DOCS_DIR_NAME,
SRC_DIR,
ES_DIR,
STYLE_DIR_NAME,
LIB_DIR,
} from '../shared/constant'
import { getPublicDirs, isDir, isLess, isScript, isSFC } from '../shared/fsUtils'
import { compileSFC } from './compileSFC'
import { compileLibraryEntry, compileScriptFile } from './compileScript'
import { compileESEntry, compileCommonJSEntry, compileScriptFile } from './compileScript'
import { compileLess } from './compileStyle'
import { getUMDConfig } from '../config/vite.config'
import { getVarletConfig } from '../config/varlet.config'
Expand Down Expand Up @@ -44,18 +52,21 @@ export async function compileFile(file: string) {
isDir(file) && (await compileDir(file))
}

export async function compileModule(modules: string | boolean = false) {
export async function compileModule(modules: 'umd' | 'commonjs' | boolean = false) {
if (modules === 'umd') {
await compileUMD()
return
}

await copy(SRC_DIR, ES_DIR)
process.env.BABEL_MODULE = modules === 'commonjs' ? 'commonjs' : 'module'

const dest = modules === 'commonjs' ? LIB_DIR : ES_DIR
await copy(SRC_DIR, dest)
const moduleDir: string[] = await readdir(ES_DIR)

await Promise.all(
moduleDir.map((filename: string) => {
const file: string = resolve(ES_DIR, filename)
const file: string = resolve(dest, filename)

if (isDir(file)) {
ensureFileSync(resolve(file, './style/index.js'))
Expand All @@ -66,5 +77,7 @@ export async function compileModule(modules: string | boolean = false) {
})
)

await compileLibraryEntry(ES_DIR, await getPublicDirs())
const publicDirs = await getPublicDirs()

await (modules === 'commonjs' ? compileCommonJSEntry(dest, publicDirs) : compileESEntry(dest, publicDirs))
}
75 changes: 71 additions & 4 deletions packages/varlet-cli/src/compiler/compileScript.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { transformAsync } from '@babel/core'
import { bigCamelize, replaceExt } from '../shared/fsUtils'
import { writeFileSync, readFileSync, removeSync, writeFile } from 'fs-extra'
import { extractStyleDependencies, IMPORT_CSS_RE, IMPORT_LESS_RE } from './compileStyle'
import {
extractStyleDependencies,
IMPORT_CSS_RE,
IMPORT_LESS_RE,
REQUIRE_CSS_RE,
REQUIRE_LESS_RE,
} from './compileStyle'
import { resolve } from 'path'
import type { BabelFileResult } from '@babel/core'

Expand All @@ -24,8 +30,22 @@ export async function compileScript(script: string, file: string) {
let { code } = (await transformAsync(script, {
filename: file,
})) as BabelFileResult
code = extractStyleDependencies(file, code as string, IMPORT_CSS_RE, 'css', false)
code = extractStyleDependencies(file, code as string, IMPORT_LESS_RE, 'less', false)
const modules = process.env.BABEL_MODULE

code = extractStyleDependencies(
file,
code as string,
modules === 'commonjs' ? REQUIRE_CSS_RE : IMPORT_CSS_RE,
'css',
false
)
code = extractStyleDependencies(
file,
code as string,
modules === 'commonjs' ? REQUIRE_LESS_RE : IMPORT_LESS_RE,
'less',
false
)
code = replaceVueExt(code as string)
code = replaceTSXExt(code as string)
code = replaceJSXExt(code as string)
Expand All @@ -41,7 +61,7 @@ export async function compileScriptFile(file: string) {
await compileScript(sources, file)
}

export async function compileLibraryEntry(dir: string, publicDirs: string[]) {
export async function compileESEntry(dir: string, publicDirs: string[]) {
const imports: string[] = []
const plugins: string[] = []
const constInternalComponents: string[] = []
Expand Down Expand Up @@ -112,3 +132,50 @@ ${lessImports.join('\n')}
writeFile(resolve(dir, 'less.js'), lessTemplate, 'utf-8'),
])
}

export async function compileCommonJSEntry(dir: string, publicDirs: string[]) {
const requires: string[] = []
const plugins: string[] = []
const cssRequires: string[] = []
const lessRequires: string[] = []
const publicComponents: string[] = []

publicDirs.forEach((dirname: string) => {
const publicComponent = bigCamelize(dirname)

publicComponents.push(publicComponent)
requires.push(`const ${publicComponent} = require('./${dirname}')`)
plugins.push(`${publicComponent}.install && app.use(${publicComponent})`)
cssRequires.push(`require('./${dirname}/style')`)
lessRequires.push(`require('./${dirname}/style/less')`)
})

const install = `
function install(app) {
${plugins.join('\n ')}
}
`

const indexTemplate = `\
${requires.join('\n')}\n
${install}
module.exports = {
install,
${publicComponents.join(',\n ')}
}
`

const styleTemplate = `\
${cssRequires.join('\n')}
`

const lessTemplate = `\
${lessRequires.join('\n')}
`
await Promise.all([
writeFile(resolve(dir, 'index.js'), indexTemplate, 'utf-8'),
writeFile(resolve(dir, 'style.js'), styleTemplate, 'utf-8'),
writeFile(resolve(dir, 'less.js'), lessTemplate, 'utf-8'),
])
}
27 changes: 23 additions & 4 deletions packages/varlet-cli/src/compiler/compileStyle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export const EMPTY_SPACE_RE = /[\s]+/g
export const EMPTY_LINE_RE = /[\n\r]*/g
export const IMPORT_CSS_RE = /(?<!['"`])import\s+['"](\.{1,2}\/.+\.css)['"]\s*;?(?!\s*['"`])/g
export const IMPORT_LESS_RE = /(?<!['"`])import\s+['"](\.{1,2}\/.+\.less)['"]\s*;?(?!\s*['"`])/g
export const REQUIRE_CSS_RE = /(?<!['"`])require\(\s*['"](\.{1,2}\/.+\.css)['"]\s*\);?(?!\s*['"`])/g
export const REQUIRE_LESS_RE = /(?<!['"`])require\(\s*['"](\.{1,2}\/.+\.less)['"]\s*\);?(?!\s*['"`])/g
export const STYLE_IMPORT_RE = /@import\s+['"](.+)['"]\s*;/g

export const clearEmptyLine = (s: string) => s.replace(EMPTY_LINE_RE, '').replace(EMPTY_SPACE_RE, ' ')
Expand All @@ -33,16 +35,33 @@ export function extractStyleDependencies(
const styleImports = code.match(reg) ?? []
const cssFile = resolve(dir, './style/index.js')
const lessFile = resolve(dir, './style/less.js')
const modules = process.env.BABEL_MODULE

styleImports.forEach((styleImport: string) => {
const normalizedPath = normalizeStyleDependency(styleImport, reg)
smartAppendFileSync(cssFile, `import '${normalizedPath}.css'\n`)
smartAppendFileSync(lessFile, `import '${normalizedPath}.${expect}'\n`)
smartAppendFileSync(
cssFile,
modules === 'commonjs' ? `require('${normalizedPath}.css')\n` : `import '${normalizedPath}.css'\n`
)
smartAppendFileSync(
lessFile,
modules === 'commonjs' ? `require('${normalizedPath}.${expect}')\n` : `import '${normalizedPath}.${expect}'\n`
)
})

if (self) {
smartAppendFileSync(cssFile, `import '${normalizeStyleDependency(base, reg)}.css'\n`)
smartAppendFileSync(lessFile, `import '${normalizeStyleDependency(base, reg)}.${expect}'\n`)
smartAppendFileSync(
cssFile,
modules === 'commonjs'
? `require('${normalizeStyleDependency(base, reg)}.css')\n`
: `import '${normalizeStyleDependency(base, reg)}.css'\n`
)
smartAppendFileSync(
lessFile,
modules === 'commonjs'
? `require('${normalizeStyleDependency(base, reg)}.${expect}')\n`
: `import '${normalizeStyleDependency(base, reg)}.${expect}'\n`
)
}

return code.replace(reg, '')
Expand Down
4 changes: 2 additions & 2 deletions packages/varlet-cli/src/config/babel.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ module.exports = (api?: ConfigAPI, options: PresetOption = {}) => {
api.cache.never()
}

const isTest = process.env.NODE_ENV === 'test'
const isCommonJS = process.env.NODE_ENV === 'test' || process.env.BABEL_MODULE === 'commonjs'

return {
presets: [
[
require.resolve('@babel/preset-env'),
{
modules: isTest ? 'commonjs' : false,
modules: isCommonJS ? 'commonjs' : false,
loose: options.loose,
},
],
Expand Down
1 change: 1 addition & 0 deletions packages/varlet-cli/src/shared/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const CWD = process.cwd()
export const VARLET_CONFIG = resolve(CWD, 'varlet.config.js')
export const SRC_DIR = resolve(CWD, 'src')
export const ES_DIR = resolve(CWD, 'es')
export const LIB_DIR = resolve(CWD, 'lib')
export const UMD_DIR = resolve(CWD, 'umd')
export const TYPES_DIR = resolve(CWD, 'types')
export const ROOT_DOCS_DIR = resolve(CWD, 'docs')
Expand Down
1 change: 1 addition & 0 deletions packages/varlet-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.23.3",
"description": "A material like components library",
"module": "es/index.js",
"main": "lib/index.js",
"typings": "types/index.d.ts",
"vetur": {
"tags": "highlight/tags.json",
Expand Down

0 comments on commit 4a424d4

Please sign in to comment.