Skip to content

Commit

Permalink
fix: remove the default value of outDir and fix source code types
Browse files Browse the repository at this point in the history
  • Loading branch information
chengpeiquan committed Sep 3, 2024
1 parent 312dec8 commit 002bfe1
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 79 deletions.
54 changes: 27 additions & 27 deletions src/main.ts → src/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import fs from 'fs'
import { resolve } from 'path'
import formatConfig from './libs/formatConfig'
import type { ResolvedConfig } from 'vite'
import type { NormalizedOutputOptions, OutputBundle } from 'rollup'
import fs from 'node:fs'
import { resolve } from 'node:path'
import { getPluginConfig } from './utils'
import type {
BannerPluginOptions,
PluginConfig,
ContentCallback,
} from './types'
PluginOption as VitePluginOption,
ResolvedConfig as ViteResolvedConfig,
} from 'vite'
import type { PluginConfig, UnionPluginOptions } from './types'

export type {
BannerPluginOptions,
Expand All @@ -16,40 +14,41 @@ export type {
} from './types'

// Extends the config from `vite.config.ts`
let viteConfig: ResolvedConfig
let viteConfig: ViteResolvedConfig

// File suffix that needs to be matched
const includeRegexp: RegExp = new RegExp(/\.(css|[mc]?js)$/i)
const includeRegexp = new RegExp(/\.(css|[mc]?js)$/i)

// Filename to exclude
const excludeRegexp: RegExp = new RegExp(/vendor/)
const excludeRegexp = new RegExp(/vendor/)

/**
* Add banner comments to files
*
* @param pluginOptions - A comment content or An option
*/
export default function (
pluginOptions: string | BannerPluginOptions | ContentCallback
): any {
export default function (pluginOptions: UnionPluginOptions) {
// Get the plugin config
const pluginConfig: PluginConfig = formatConfig(pluginOptions)
const pluginConfig: PluginConfig = getPluginConfig(pluginOptions)

// Handle files
return {
name: 'banner',
configResolved(resolvedConfig: ResolvedConfig) {
apply: 'build',
configResolved(resolvedConfig) {
viteConfig = resolvedConfig
},
async writeBundle(options: NormalizedOutputOptions, bundle: OutputBundle) {
async writeBundle(_, bundle) {
for (const file of Object.entries(bundle)) {
// Get the full path of file
const root: string = viteConfig.root
const outDir: string =
pluginConfig.outDir || viteConfig.build.outDir || 'dist'
const fileName: string = file[0].endsWith('.js-lean')
const root = viteConfig.root
const outDir = pluginConfig.outDir || viteConfig.build.outDir

const fileName = file[0].endsWith('.js-lean')
? file[0].replace(/\.js-lean/, '.lean.js')
: file[0]
const filePath: string = resolve(root, outDir, fileName)

const filePath = resolve(root, outDir, fileName)

const { content: setContent } = pluginConfig

Expand All @@ -61,11 +60,12 @@ export default function (
encoding: 'utf8',
})

let myContent: string =
typeof setContent === 'string' ? setContent : ''
let myContent = typeof setContent === 'string' ? setContent : ''

if (typeof setContent === 'function') {
myContent = setContent(fileName)
myContent = setContent(fileName) ?? ''
}

if (myContent) {
// If the banner content has comment symbol, use it directly
if (
Expand All @@ -91,5 +91,5 @@ export default function (
}
}
},
}
} satisfies VitePluginOption
}
27 changes: 0 additions & 27 deletions src/libs/verifyBanner.ts

This file was deleted.

39 changes: 26 additions & 13 deletions src/types/index.ts → src/types.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
/* eslint-disable no-unused-vars */

/**
* Some options from `vite.config.[ts|js]`
*
* @since 0.2.0
*/
export interface BannerPluginOptions {
/**
* The comment content of the banner
*
* @since ^0.6.0 support for `ContentCallback` types
*/
content: string | ContentCallback

/**
* The output directory from the configuration of Vite.js
* @default 'dist'
*
* @see https://vitejs.dev/config/build-options.html#build-outdir
*
* @default viteConfig.build.outDir
*/
outDir?: string

/**
* Whether to print error messages to the console
*
* @since 0.4.0
*
* @default false
*/
debug?: boolean
Expand All @@ -28,33 +33,29 @@ export interface BannerPluginOptions {
* By default, the validity of the content will be verified.
*
* If set to `false`, no verification will be performed.
*
* @see https://github.com/chengpeiquan/vite-plugin-banner/issues/13
*
* @since 0.5.0
*
* @default true
*/
verify?: boolean
}

/**
* Configuration of the plugin's internal runtime
*/
export interface PluginConfig {
content: string | ContentCallback
outDir: string
debug: boolean
verify: boolean
}

/**
* Callback function to get the contents to be injected.(or not inject)
*
* @since 0.6.0
*
* @param fileName - The name of the file currently being processed
*
* @returns
* 1. When a valid string is returned, it will become the banner content
* 2. Returning a Falsy value will skip processing(e.g. `''`, `null`, `undefined`)
*
* @example
*
* ```ts
* content: (fileName: string) => {
* // Or use switch statement
Expand All @@ -65,3 +66,15 @@ export interface PluginConfig {
* ```
*/
export type ContentCallback = (fileName: string) => string | null | undefined

export type UnionPluginOptions = string | BannerPluginOptions | ContentCallback

/**
* Configuration of the plugin's internal runtime
*/
export interface PluginConfig {
content: string | ContentCallback
outDir: string
debug: boolean
verify: boolean
}
53 changes: 41 additions & 12 deletions src/libs/formatConfig.ts → src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,47 @@
import verifyBanner from './verifyBanner'
import type {
BannerPluginOptions,
ContentCallback,
PluginConfig,
} from '../types'
import type { PluginConfig, UnionPluginOptions } from './types'

/**
* Verify the banner content
*
* @param content - The content of banner
*
* @return The error message, when success, if will be a empty string
*/
export const verifyBanner = (content: string): string => {
// illegal type
if (typeof content !== 'string') {
return 'The banner content must be a string.'
}

// No content
if (!content) {
return 'The banner content can not be empty.'
}

// The comment symbols not in pairs
if (
(content.includes('/*') && !content.includes('*/')) ||
(!content.includes('/*') && content.includes('*/'))
) {
return 'If you want to pass in comment symbols, you must pass them in pairs.'
}

// Ok
return ''
}

/**
* Process options of different formats into a unified format
*
* @param options - Some options from `vite.config.[ts|js]`
*
* @returns A unified plugin option
*/
export default function formatConfig(
options: string | BannerPluginOptions | ContentCallback
): PluginConfig {
export const getPluginConfig = (options: UnionPluginOptions): PluginConfig => {
// Set a default config
const config: PluginConfig = {
content: '',
outDir: 'dist',
outDir: '',
debug: false,
verify: true,
}
Expand All @@ -29,7 +54,7 @@ export default function formatConfig(
!['[object String]', '[object Object]', '[object Function]'].includes(type)
) {
throw new Error(
'[vite-plugin-banner] The options must be a string, an object or a function.'
'[vite-plugin-banner] The options must be a string, an object or a function.',
)
}

Expand All @@ -50,6 +75,7 @@ export default function formatConfig(
if (!Object.prototype.hasOwnProperty.call(options, 'content')) {
throw new Error(`[vite-plugin-banner] Missing "content" option.`)
}

config.content = options.content

// Update the `outDir` option
Expand All @@ -68,14 +94,17 @@ export default function formatConfig(
config.verify = options.verify
}
}

// No verification required
if (!config.verify) return config

if (typeof config.content === 'function') return config

// Verify the validity of the incoming comment content
const errMsg: string = verifyBanner(config.content)
const errMsg = verifyBanner(config.content)
if (errMsg) {
throw new Error(`[vite-plugin-banner] ${errMsg}`)
}

return config
}

0 comments on commit 002bfe1

Please sign in to comment.