Skip to content

Commit

Permalink
feat: rollup-chain环境变量
Browse files Browse the repository at this point in the history
  • Loading branch information
xuasir committed Mar 19, 2021
1 parent fb837ed commit 518bbef
Show file tree
Hide file tree
Showing 15 changed files with 116 additions and 50 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"scripts": {
"test": "jest",
"build": "npx xus lib-build",
"copy:preset": "xus copy --src packages/preset-built-in/src/plugin/template --dest packages/preset-built-in/dist/plugin/template",
"copy:preset": "xus copy --src packages/preset-built-in/src/plugin/template --dest packages/preset-built-in/dist/template",
"copy:create": "xus copy --src packages/create-lib/src/template --dest packages/create-lib/dist/template"
},
"devDependencies": {
Expand Down
16 changes: 11 additions & 5 deletions packages/cli-types/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,15 @@ export interface IPluginAPI extends IPluginAPIBase {
skipPlugin: IPluginManager['skipPlugin']

// rollup
modifyRollupConfig: IFastHookRegister<(rc: IRollupChain) => IRollupChain>
getRollupConfig: () => Promise<IRollupChainConfig>
modifyRollupConfig: IFastHookRegister<
(rc: IRollupChain, arg?: any) => IRollupChain
>
getRollupConfig: (arg?: any) => Promise<IRollupChainConfig>
// webpack
modifyWebpackConfig: IFastHookRegister<(wc: webpackChain) => webpackChain>
getWebpackConfig: () => Promise<any>
modifyWebpackConfig: IFastHookRegister<
(wc: webpackChain, arg?: any) => webpackChain
>
getWebpackConfig: (arg?: any) => Promise<any>
}

// IConfig
Expand All @@ -78,6 +82,7 @@ export interface IConfig extends IProjectConfig {
libName: string
target: 'esnext' | TransformOptions['target']
formats: ('esm' | 'cjs' | 'iife' | 'umd')[]
disableFormatPostfix: boolean
rollTypes: boolean
sourcemap: boolean
minify: false | 'esbuild' | 'terser'
Expand Down Expand Up @@ -120,6 +125,7 @@ export interface IConfig extends IProjectConfig {
alias: Record<string, string>
replace: Record<string, string>
excludeExternal: string[]
external: string[]

// lerna mode
lerna:
Expand All @@ -131,7 +137,7 @@ export interface IConfig extends IProjectConfig {
}

// insider
rollupChain: (rc: IRollupChain) => IRollupChain
rollupChain: (rc: IRollupChain, pkgDir: string) => IRollupChain

afterBuild: ICmd[]
}
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-cmd-roll-lib/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@xus/plugin-cmd-roll-lib",
"version": "0.2.1",
"description": "a bundle for js ts react",
"main": "dist/index.cjs.js",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"keywords": [
"cli",
Expand Down
10 changes: 6 additions & 4 deletions packages/plugin-cmd-roll-lib/src/bundler/bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ async function doBuild(ops: IRollupBuildOps) {
inputConfig,
outputConfigs,
alwaysEmptyDistDir,
skipEmptyDistDir = false
skipEmptyDistDir = false,
disableConsoleInfo = false
} = ops
if (isWatch) {
logger.debug(`do watch: `)
Expand Down Expand Up @@ -63,9 +64,10 @@ async function doBuild(ops: IRollupBuildOps) {
logger.debug(`start ${isWrite ? 'write' : 'generate'}`)
for (const output of outputConfigs) {
logger.debug(output)
logger.info(
chalk.green(`[${isWrite ? 'Write' : 'Generate'}] ${output.format}`)
)
!disableConsoleInfo &&
logger.info(
chalk.green(`[${isWrite ? 'Write' : 'Generate'}] ${output.format}`)
)
await bundler[isWrite ? 'write' : 'generate'](output)
}
await bundler.close()
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-cmd-roll-lib/src/bundler/rollTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export async function rollTypes(
}
)
if (!res) return
const ops = generateTypeOps(pkgRoot, buildOps, api)
const ops = generateTypeOps(pkgRoot, buildOps)
if (ops) {
api.logger.debug(`[rollup types] with `, ops)
await rollupBundler(ops)
Expand Down
1 change: 1 addition & 0 deletions packages/plugin-cmd-roll-lib/src/bundler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export interface IRollupBuildOps {
pkgRoot: string
alwaysEmptyDistDir: boolean
skipEmptyDistDir?: boolean
disableConsoleInfo?: boolean
}

export type IRollupBuildFn = (ops: IRollupBuildOps) => Promise<void>
4 changes: 4 additions & 0 deletions packages/plugin-cmd-roll-lib/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const libBuildSchema = createSchema<IRollLibConfig>((joi) =>
minify: [joi.string(), joi.boolean()],
target: [joi.string(), joi.array().items(joi.string())],
formats: joi.array().items(joi.string()),
disableFormatPostfix: joi.boolean(),
rollTypes: joi.boolean(),
sourcemap: joi.boolean(),
alwaysEmptyDistDir: joi.boolean(),
Expand All @@ -27,6 +28,7 @@ export const libBuildSchema = createSchema<IRollLibConfig>((joi) =>
alias: joi.object(),
replace: joi.object(),
excludeExternal: joi.array().items(joi.string()),
external: joi.array().items(joi.string()),

// lerna mode
lerna: [
Expand All @@ -48,6 +50,7 @@ export const defaultLibBuildConfig: () => IRollLibConfig = () => {
libName: 'index',
target: 'esnext',
formats: [],
disableFormatPostfix: false,
rollTypes: true,
sourcemap: false,
minify: false,
Expand All @@ -69,6 +72,7 @@ export const defaultLibBuildConfig: () => IRollLibConfig = () => {
alias: {},
replace: {},
excludeExternal: [],
external: [],

// lerna mode
lerna: {
Expand Down
6 changes: 3 additions & 3 deletions packages/plugin-cmd-roll-lib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ export default createPlugin({
// default config should run before user modify
api.logger.debug(`modify rollup config `)
api.modifyRollupConfig({
fn(rc) {
fn(rc, pkgDir) {
modifyConfig(rc, resolvedConfig, api)
if (resolvedConfig?.rollupChain) {
resolvedConfig.rollupChain(rc)
resolvedConfig.rollupChain(rc, pkgDir)
}
return rc
},
Expand All @@ -60,7 +60,7 @@ export default createPlugin({
await rollupBundler(buildOps)
if (resolvedConfig.rollTypes) {
api.logger.debug(`rollup types `)
rollTypes(pkg, buildOps, api)
await rollTypes(pkg, buildOps, api)
}
process.chdir(saveCwd)
}
Expand Down
14 changes: 11 additions & 3 deletions packages/plugin-cmd-roll-lib/src/modify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,10 @@ export function modifyConfig(

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

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

function getPkgDeps(root: string, exclude: string[]): string[] {
function getPkgDeps(
root: string,
include: string[],
exclude: string[]
): string[] {
let pkg = null
try {
pkg = require(join(root, 'package.json'))
Expand All @@ -130,7 +137,8 @@ function getPkgDeps(root: string, exclude: string[]): string[] {
if (pkg) {
deps = [
...Object.keys(pkg?.dependencies || {}),
...Object.keys(pkg?.peerDependencies || {})
...Object.keys(pkg?.peerDependencies || {}),
...include
].filter((dep) => !exclude.includes(dep))
}
return deps
Expand Down
53 changes: 33 additions & 20 deletions packages/plugin-cmd-roll-lib/src/resolveConfig/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IArgs, IPluginAPI } from '@xus/cli-types'
import { IRollupBuildOps } from '../bundler'
import { IRollLibConfig, IResolvedConfig } from '../types'
import { isLernaPkg, orderBy, getFileMeta } from '@xus/cli-shared'
import { isLernaPkg, orderBy, getFileMeta, Logger } from '@xus/cli-shared'
import { relative, join, isAbsolute, extname, basename } from 'path'
import { TypesDir } from '../bundler'
import dts from 'rollup-plugin-dts'
Expand Down Expand Up @@ -52,8 +52,8 @@ export function resolveConfig(
pkgs = api.getLernaPkgs().map((p) => relative(lernaRoot, p))
}
pkgs = orderBy(pkgs, pkgsOrder)
.map((p) => join(lernaRoot, p))
.filter((pkg) => !excludePkgs.includes(pkg))
.map((p) => join(lernaRoot, p))
}
} else {
// simple pack
Expand Down Expand Up @@ -90,16 +90,25 @@ export function resolveConfig(
return resolvedConfig
}

const buildLogger = new Logger(`xus:generate:build`)
export async function generateBuildOps(
pkgRoot: string,
resolvedConfig: IResolvedConfig,
api: IPluginAPI
): Promise<IRollupBuildOps> {
const rollupConfig = await api.getRollupConfig()
const rollupConfig = await api.getRollupConfig(basename(pkgRoot))
const isProd = api.mode === 'production'
const { libName, outDir, formats, alwaysEmptyDistDir } = resolvedConfig
const {
libName,
outDir,
formats,
alwaysEmptyDistDir,
disableFormatPostfix
} = resolvedConfig
if (rollupConfig) {
api.logger.debug(`[generate buildOps] in ${pkgRoot}`)
buildLogger.debug(`[generate buildOps] in ${pkgRoot}`)
buildLogger.debug(`rollup config input `, rollupConfig.input)
buildLogger.debug(`resolved config input `, resolvedConfig.entry)
const { output, ...inputOps } = rollupConfig
// TODO: support from rollup-chain
inputOps.preserveEntrySignatures = 'strict'
Expand All @@ -114,8 +123,9 @@ export async function generateBuildOps(
if (!entry) {
throw new Error(`[generate buildOps] lib-build should have a entry`)
} else {
resolvedConfig.entry = entry
inputOps.input = entry
}
buildLogger.debug(`auto find entry `, entry)
}
const entry = (inputOps.input = inputOps.input || resolvedConfig.entry)
const isSingleEntry = typeof entry === 'string'
Expand All @@ -126,9 +136,8 @@ export async function generateBuildOps(
!isAbsolute(entry[key]) && (entry[key] = join(pkgRoot, entry[key]))
})
}
api.logger.debug(`[generate buildOps] final inputConfig: `)
api.logger.debug(inputOps)

buildLogger.debug(`[generate buildOps] final inputConfig: `)
buildLogger.debug(inputOps)
// output generate
const outputOps = formats.map((format) => {
const outputConfig = {
Expand All @@ -137,9 +146,9 @@ export async function generateBuildOps(
format,
exports: format === 'cjs' ? 'named' : 'auto',
namespaceToStringTag: true,
entryFileNames: isProd
? `${isSingleEntry ? libName : '[name]'}.${format}.prod.js`
: `${isSingleEntry ? libName : '[name]'}.${format}.js`,
entryFileNames: `${isSingleEntry ? libName : '[name]'}${
disableFormatPostfix ? '' : '.' + format
}${isProd ? '.prod' : ''}.js`,
chunkFileNames: `[name].js`,
sourcemap: !!resolvedConfig?.sourcemap,
...output
Expand All @@ -148,8 +157,8 @@ export async function generateBuildOps(

return outputConfig
})
api.logger.debug(`[generate buildOps] final outputConfig: `)
api.logger.debug(outputOps)
buildLogger.debug(`[generate buildOps] final outputConfig: `)
buildLogger.debug(outputOps)

return {
inputConfig: inputOps,
Expand All @@ -160,16 +169,19 @@ export async function generateBuildOps(
alwaysEmptyDistDir
} as IRollupBuildOps
} else {
throw new Error(`roll-lib need a rollup config`)
throw new Error(`lib-build need a rollup config`)
}
}

const typeLogger = new Logger(`xus:generate:types`)
const tsRE = /\.tsx?$/
export function generateTypeOps(
pkgRoot: string,
buildOps: IRollupBuildOps,
api: IPluginAPI
buildOps: IRollupBuildOps
): IRollupBuildOps | null {
typeLogger.debug(`rollup types in `, pkgRoot)
typeLogger.debug(`with `, buildOps.inputConfig.input)
typeLogger.debug(`cwd `, process.cwd())
const entry = buildOps.inputConfig.input
let inputs: Record<string, string> = {}
if (entry) {
Expand Down Expand Up @@ -198,8 +210,8 @@ export function generateTypeOps(
delete inputs[key]
}
})
api.logger.debug(`[generate types options] types entry: `)
api.logger.debug(inputs)
typeLogger.debug(`[generate types options] types entry: `)
typeLogger.debug(inputs)
return {
inputConfig: {
input: inputs,
Expand All @@ -216,7 +228,8 @@ export function generateTypeOps(
isWrite: true,
pkgRoot,
alwaysEmptyDistDir: false,
skipEmptyDistDir: true
skipEmptyDistDir: true,
disableConsoleInfo: true
}
}
return null
Expand Down
4 changes: 3 additions & 1 deletion packages/plugin-cmd-roll-lib/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export interface IRollLibConfig {
libName: string
target: 'esnext' | TransformOptions['target']
formats: ('esm' | 'cjs' | 'iife' | 'umd')[]
disableFormatPostfix: boolean
rollTypes: boolean
sourcemap: boolean
minify: false | 'esbuild' | 'terser'
Expand All @@ -35,6 +36,7 @@ export interface IRollLibConfig {
alias: Record<string, string>
replace: Record<string, string>
excludeExternal: string[]
external: string[]

// lerna mode
lerna:
Expand All @@ -47,7 +49,7 @@ export interface IRollLibConfig {
}

// insider
rollupChain?: (rc: IRollupChain) => IRollupChain
rollupChain?: (rc: IRollupChain, pkgDir: string) => IRollupChain
afterBuild: ICmd[]
}

Expand Down
1 change: 0 additions & 1 deletion packages/plugin-lib-legacy/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
"@xus/cli-shared": "^0.2.1",
"@xus/cli-types": "^0.2.1",
"@xus/core": "^0.2.1",
"core-js": "^3.9.1",
"rollup": "^2.40.0"
},
"devDependencies": {
Expand Down
10 changes: 6 additions & 4 deletions packages/preset-built-in/src/plugin/bundler/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ export default createPlugin({
api.registerMethod({
methodName: BundlerMethods.getRollupConfig,
throwOnExist: false,
fn: async () => {
fn: async (arg?: any) => {
const rc = new rollupChain()
await api.applyHook({
name: BundlerMethods.modifyRollupConfig,
type: HookTypes.serial,
initialValue: rc
initialValue: rc,
args: arg
})
return rc.toConfig()
}
Expand All @@ -35,12 +36,13 @@ export default createPlugin({
api.registerMethod({
methodName: BundlerMethods.getWebpackConfig,
throwOnExist: false,
fn: async () => {
fn: async (arg?: any) => {
const wr = new webpackChain()
await api.applyHook({
name: BundlerMethods.modifyWebpackConfig,
type: HookTypes.serial,
initialValue: wr
initialValue: wr,
args: arg
})
return wr.toConfig()
}
Expand Down

0 comments on commit 518bbef

Please sign in to comment.