Skip to content

Commit

Permalink
refactor: 重构配置文件
Browse files Browse the repository at this point in the history
  • Loading branch information
xuasir committed Mar 18, 2021
1 parent 044c305 commit d3dda92
Show file tree
Hide file tree
Showing 10 changed files with 201 additions and 61 deletions.
5 changes: 1 addition & 4 deletions packages/cli-shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/xus-code/cli.git"
Expand Down Expand Up @@ -55,4 +52,4 @@
"@types/rimraf": "^3.0.0",
"@types/yargs-parser": "^20.2.0"
}
}
}
5 changes: 1 addition & 4 deletions packages/cli-types/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
"files": [
"dist"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/xus-code/cli.git"
Expand All @@ -36,4 +33,4 @@
"devDependencies": {
"postcss": "^8.2.8"
}
}
}
34 changes: 27 additions & 7 deletions packages/cli-types/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ export interface IPluginAPI extends IPluginAPIBase {
}

// IConfig

type ICmd = {
bin: string
args: string[]
message: IRunCmdMessage
}
export interface IConfig extends IProjectConfig {
libBuild: {
libName: string
Expand All @@ -77,7 +83,7 @@ export interface IConfig extends IProjectConfig {
minify: false | 'esbuild' | 'terser'
alwaysEmptyDistDir: boolean
css: {
injectScript: boolean
injectMode: false | 'script' | 'url'
cssCodeSplit: boolean
modules: {
getJSON?: (
Expand All @@ -104,12 +110,30 @@ export interface IConfig extends IProjectConfig {
postcss: Postcss.ProcessOptions & { plugins: Postcss.Plugin[] }
preprocessor: Partial<Record<'sass' | 'less' | 'stylus', any>>
}
assets: {
dirname: string
inlineLimit: number
}
json: {
exportMode: 'named' | 'stringify'
}
alias: Record<string, string>
replace: Record<string, string>
excludeExternal: string[]

// lerna mode
pkgsOrder: string[]
lerna:
| false
| {
// independentConfig: boolean
pkgsOrder: string[]
excludePkgs: string[]
}

// insider
rollupChain: (rc: IRollupChain) => IRollupChain

afterBuild: ICmd[]
}
lint: {
eslint:
Expand All @@ -132,11 +156,7 @@ export interface IConfig extends IProjectConfig {
}
release: {
// before hooks for run lint test build...
beforeRelease: {
bin: string
args: string[]
message: IRunCmdMessage
}[]
beforeRelease: ICmd[]
// in lenra mode to ensure pkg publish order
order: string[]
branch: string
Expand Down
45 changes: 39 additions & 6 deletions packages/plugin-cmd-roll-lib/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,35 @@ export const libBuildSchema = createSchema<IRollLibConfig>((joi) =>
sourcemap: joi.boolean(),
alwaysEmptyDistDir: joi.boolean(),
css: joi.object({
injectScript: joi.boolean(),
injectMode: joi.boolean(),
cssCodeSplit: joi.boolean(),
modules: joi.object(),
preprocessor: joi.object(),
postcss: joi.object()
}),
assets: {
dirname: joi.string(),
inlineLimit: joi.number()
},
json: {
exportMode: joi.string()
},
alias: joi.object(),
replace: joi.object(),
excludeExternal: joi.array().items(joi.string()),

// lerna mode
pkgsOrder: joi.array().items(joi.string()),
pointPkgs: joi.array().items(joi.string()),
lerna: [
joi.boolean(),
joi.object({
independentConfig: joi.boolean(),
pkgsOrder: joi.array().items(joi.string()),
excludePkgs: joi.array().items(joi.string())
})
],

rollupChain: joi.function()
rollupChain: joi.function(),
afterBuild: joi.array()
})
)

Expand All @@ -36,14 +53,30 @@ export const defaultLibBuildConfig: () => IRollLibConfig = () => {
minify: false,
alwaysEmptyDistDir: false,
css: {
injectScript: false,
injectMode: false,
cssCodeSplit: false,
modules: {},
preprocessor: {},
postcss: {}
},
assets: {
dirname: 'assets',
inlineLimit: 0
},
json: {
exportMode: 'named'
},
alias: {},
replace: {},
excludeExternal: [],

// lerna mode
pkgsOrder: []
lerna: {
independentConfig: false,
pkgsOrder: [],
excludePkgs: []
},

afterBuild: []
}
}
23 changes: 22 additions & 1 deletion packages/plugin-cmd-roll-lib/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createPlugin } from '@xus/cli-types'
import { chalk } from '@xus/cli-shared'
import { chalk, runCmd } from '@xus/cli-shared'
import { basename } from 'path'
import { rollupBundler } from './bundler'
import { resolveConfig, generateBuildOps } from './resolveConfig'
Expand Down Expand Up @@ -34,6 +34,7 @@ export default createPlugin({
// resolveConfig
api.logger.debug(`resolve config `)
const resolvedConfig = resolveConfig(args, config, api)

// default config should run before user modify
api.logger.debug(`modify rollup config `)
api.modifyRollupConfig({
Expand All @@ -57,8 +58,28 @@ export default createPlugin({
// to rollup
api.logger.info(chalk.yellow(`running for ${basename(pkg)}`))
await rollupBundler(buildOps)
// if (resolvedConfig.rollTypes) {
// api.logger.debug(`roll types `)
// await runCmd(
// 'npx',
// ['tsc', '--emitDeclarationOnly', '--outDir', 'xus_type'],
// {
// start: 'generate types start',
// succeed: 'generate types succeed',
// failed: 'generate types failed'
// }
// )
// }
process.chdir(saveCwd)
}

const afterBuild = resolvedConfig.afterBuild
if (afterBuild && afterBuild.length > 0) {
api.logger.info(`after build command running `)
await afterBuild.reduce((p, cmd) => {
return p.then(() => runCmd(cmd.bin, cmd.args, cmd.message))
}, Promise.resolve(true))
}
}
)
},
Expand Down
38 changes: 26 additions & 12 deletions packages/plugin-cmd-roll-lib/src/modify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ export function modifyConfig(
extensions
}
])
rc.plugin('commonjs').use(commonjs).after('commonjs')
rc.plugin('commonjs')
.use(commonjs, [{ sourceMap: false }])
.after('nodeResolve')

// esbuild
rc.plugin('$$esbuild').use(esbuildPlugin, [
Expand All @@ -52,7 +54,7 @@ export function modifyConfig(
const css = resolvedConfig.css
rc.plugin('$$css').use(cssPlugin, [
{
injectScript: css.injectScript,
injectMode: css.injectMode,
cssCodeSplit: css.cssCodeSplit,
minify: !!resolvedConfig.minify,
modules: css.modules || {},
Expand All @@ -62,36 +64,48 @@ export function modifyConfig(
])

// asset
rc.plugin('asset').use(assetPlugin, [
const assets = resolvedConfig.assets
rc.plugin('$$assets').use(assetPlugin, [
{
assetDir: 'assets',
assetDir: assets.dirname,
assetRoot: join(api.cwd, 'assets'),
inlineLimit: 0
inlineLimit: assets.inlineLimit
}
])

// json
const json = resolvedConfig.json
rc.plugin('$$json').use(jsonPlugin, [
{
exportMode: 'stringify'
exportMode: json.exportMode
}
])

//alias
const configAlias = resolvedConfig.alias
const aliasEntries = Object.keys(configAlias).map((find) => ({
find,
replacement: configAlias[find]
}))
rc.plugin('alias').use(alias, [
{
entries: [{ find: '@', replacement: join(api.cwd, 'src') }]
entries: [
{ find: '@', replacement: join(api.cwd, 'src') },
...aliasEntries
]
}
])
const configReplace = resolvedConfig.replace
rc.plugin('replace').use(replace, [
{
preventAssignment: true
preventAssignment: true,
...configReplace
}
])

// external
// TODO: excludeExternal config
getPkgDeps(api.cwd).forEach((dep) => rc.external.set(dep))
const excludeExternal = resolvedConfig.excludeExternal
getPkgDeps(api.cwd, excludeExternal).forEach((dep) => rc.external.set(dep))

// onwarn
rc.onwarn((warning, onwarn) => {
Expand All @@ -105,7 +119,7 @@ function onRollupWarning(warning: RollupWarning, onwarn: WarningHandler) {
onwarn(warning)
}

function getPkgDeps(root: string): string[] {
function getPkgDeps(root: string, exclude: string[]): string[] {
let pkg = null
try {
pkg = require(join(root, 'package.json'))
Expand All @@ -117,7 +131,7 @@ function getPkgDeps(root: string): string[] {
deps = [
...Object.keys(pkg?.dependencies || {}),
...Object.keys(pkg?.peerDependencies || {})
]
].filter((dep) => !exclude.includes(dep))
}
return deps
}
15 changes: 8 additions & 7 deletions packages/plugin-cmd-roll-lib/src/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export type IPostcssOps = Postcss.ProcessOptions & {
}
export type IPreprocessorOps = Partial<Record<string, any>>
interface ICssOps {
injectScript?: boolean
injectMode?: false | 'script' | 'url'
cssCodeSplit?: boolean
minify?: boolean
// ops
Expand All @@ -56,8 +56,7 @@ const commonjsProxyRE = /\?commonjs-proxy/
const cssCache = new Map<string, string>()
const opsToFullCssChunk = new WeakMap<NormalizedOutputOptions, string>()
export function cssPlugin(ops?: ICssOps): Plugin {
const { cssCodeSplit = false, injectScript = false, minify = false } =
ops || {}
const { cssCodeSplit = false, injectMode = false, minify = false } = ops || {}
let hasGenFullStyle = false
return {
name: 'xus:rollup:css',
Expand Down Expand Up @@ -103,18 +102,20 @@ export function cssPlugin(ops?: ICssOps): Plugin {
// bundle a css for every chunk
// 1. minify replace
cssChunk = await processCssChunk(cssChunk, {
inject: injectScript,
inject: !!injectMode,
minify
})
// 2. inject code
const filename = `${chunk.name}.css`
let injectCode = `import './css/${filename}';\n`
if (injectScript) {
let injectCode = ''
if (injectMode === 'script') {
const style = `__xus__style__`
injectCode =
`var ${style} = document.createElement('style');\n` +
`${style}.innerHTML = ${JSON.stringify(cssChunk)};\n` +
`document.head.appendChild(${style});`
} else if (injectMode === 'url') {
injectCode = `import './css/${filename}';\n`
}
const s = new MagicString(code)
s.prepend(injectCode)
Expand Down Expand Up @@ -297,7 +298,7 @@ async function compileCss(

async function processCssChunk(
css: string,
{ inject, minify }: { inject: boolean; minify: boolean }
{ minify }: { inject: boolean; minify: boolean }
) {
let res = css
// replace assets mark
Expand Down
Loading

0 comments on commit d3dda92

Please sign in to comment.