From 4b879422a92c1301abd41d36d300d558d16c3aed Mon Sep 17 00:00:00 2001 From: liihuu Date: Mon, 11 Dec 2023 05:02:05 +0800 Subject: [PATCH] chore: opt ci --- .eslintignore | 7 +-- index.js | 6 +-- package.json | 23 +++++---- scripts/build-cjs.js | 10 ++++ scripts/build-esm.js | 11 +++++ scripts/build-umd.js | 15 ++++++ scripts/build.cjs | 34 -------------- scripts/build.js | 28 +++++++++++ scripts/{clean.cjs => clean.js} | 39 ++++++++-------- scripts/config.cjs | 69 --------------------------- scripts/config.js | 82 +++++++++++++++++++++++++++++++++ scripts/paths.cjs | 14 ------ scripts/utils.js | 13 ++++++ src/common/utils/logger.ts | 9 ++-- src/index.ts | 2 +- 15 files changed, 201 insertions(+), 161 deletions(-) create mode 100644 scripts/build-cjs.js create mode 100644 scripts/build-esm.js create mode 100644 scripts/build-umd.js delete mode 100644 scripts/build.cjs create mode 100644 scripts/build.js rename scripts/{clean.cjs => clean.js} (50%) delete mode 100644 scripts/config.cjs create mode 100644 scripts/config.js delete mode 100644 scripts/paths.cjs create mode 100644 scripts/utils.js diff --git a/.eslintignore b/.eslintignore index d687733c..9a432946 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,8 +1,5 @@ -config/ -dist/ -types/ -docs/ -types/ scripts/ +dist/ +docs/ .eslintrc.cjs index.js \ No newline at end of file diff --git a/index.js b/index.js index 6b194e3b..0d11903a 100644 --- a/index.js +++ b/index.js @@ -12,10 +12,8 @@ * limitations under the License. */ -'use strict' - if (process.env.NODE_ENV === 'production') { - module.exports = require('./dist/klinecharts.min.js') + module.exports = require('./umd/klinecharts.min.js') } else { - module.exports = require('./dist/klinecharts.js') + module.exports = require('./umd/klinecharts.js') } diff --git a/package.json b/package.json index 5d20b27d..8a502bde 100644 --- a/package.json +++ b/package.json @@ -2,14 +2,14 @@ "name": "klinecharts", "version": "9.6.0", "description": "Lightweight k-line chart built with html5 canvas", - "main": "./dist/klinecharts.min.js", - "module": "index.js", - "types": "./types/index.d.ts", + "main": "./dist/main.js", + "module": "./dist/index.js", + "unpkg": "./dist/umd/klinecharts.min.js", + "types": "./dist/index.d.ts", + "type": "module", "files": [ "LICENSE", "README.md", - "index.js", - "types/", "dist/", "licenses/", "NOTICE" @@ -35,11 +35,14 @@ "private": false, "scripts": { "lint": "eslint src", - "clean": "node scripts/clean.cjs", - "build-core:dev": "cross-env NODE_ENV=development node scripts/build.cjs", - "build-core:prod": "cross-env NODE_ENV=production node scripts/build.cjs", - "build-core": "npm run build-core:dev && npm run build-core:prod", - "build-dts": "dts-bundle-generator --no-banner true --fail-on-class true --umd-module-name klinecharts -o types/index.d.ts src/index.ts", + "clean": "node scripts/clean.js", + "build-esm": "node scripts/build-esm.js", + "build-cjs": "cross-env NODE_ENV=production node scripts/build-cjs.js", + "build-umd:dev": "cross-env NODE_ENV=development node scripts/build-umd.js", + "build-umd:prod": "cross-env NODE_ENV=production node scripts/build-umd.js", + "build-umd": "npm run build-umd:dev && npm run build-umd:prod", + "build-core": "npm run build-esm && npm run build-cjs && npm run build-umd", + "build-dts": "dts-bundle-generator --no-banner true --fail-on-class true --umd-module-name klinecharts -o dist/index.d.ts src/index.ts", "build": "npm run clean && npm run build-core && npm run build-dts", "prepare": "husky install", "docs:pre-work": "npm run pre-work --prefix docs", diff --git a/scripts/build-cjs.js b/scripts/build-cjs.js new file mode 100644 index 00000000..9b71fe71 --- /dev/null +++ b/scripts/build-cjs.js @@ -0,0 +1,10 @@ +import build from './build.js' +import { resolvePath } from './utils.js' + +const fileName = 'main.cjs' +const index = resolvePath('index.js') +build({ + index, + fileName, + format: 'cjs' +}) diff --git a/scripts/build-esm.js b/scripts/build-esm.js new file mode 100644 index 00000000..27bf7cae --- /dev/null +++ b/scripts/build-esm.js @@ -0,0 +1,11 @@ +import build from './build.js' +import { resolvePath } from './utils.js' + +const fileName = 'index.js' +const index = resolvePath('index.ts', resolvePath('src')) + +build({ + index, + fileName, + format: 'esm' +}) \ No newline at end of file diff --git a/scripts/build-umd.js b/scripts/build-umd.js new file mode 100644 index 00000000..537daacf --- /dev/null +++ b/scripts/build-umd.js @@ -0,0 +1,15 @@ +import build from './build.js' +import { isDev, env } from './config.js' +import { resolvePath } from './utils.js' + +const fileName = isDev ? 'klinecharts.js' : 'klinecharts.min.js' +const index = resolvePath('index.ts', resolvePath('src')) + +build({ + index, + replaceValues: { "process.env.NODE_ENV": JSON.stringify(env) }, + fileName, + format: 'umd', + parentDir: 'umd', + name: 'klinecharts' +}) diff --git a/scripts/build.cjs b/scripts/build.cjs deleted file mode 100644 index 3fa16a1a..00000000 --- a/scripts/build.cjs +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const rollup = require('rollup'); - -const chalk = require('chalk'); - -const { inputConfig, outputConfig, version } = require('./config.cjs'); - -const env = process.env.NODE_ENV; - -async function build() { - const fileName = env === 'development' ? 'klinecharts.js' : 'klinecharts.min.js' - - const fileNameVersion = `v${version} ${fileName}` - console.log(`Creating an optimized version ${chalk.blue(fileNameVersion)} build...\n`); - const input = inputConfig(env); - - try { - const startTime = new Date().getTime() - const bundle = await rollup.rollup(input); - - const output = outputConfig(env, fileName); - await bundle.write(output); - - console.log(chalk.green(`\n✔️ Compiled ${fileNameVersion} successfully.\n`)); - console.log(`Done in ${((new Date().getTime() - startTime) / 1000 / 60).toFixed(2)}s.\n`) - } catch (err) { - console.log(`\n\n${chalk.red(err)}\n`); - console.log(chalk.red(`✖️ Failed to compile ${fileNameVersion}.\n`)); - process.exit(1); - } -} - -build(); diff --git a/scripts/build.js b/scripts/build.js new file mode 100644 index 00000000..3274ed16 --- /dev/null +++ b/scripts/build.js @@ -0,0 +1,28 @@ +import { rollup } from 'rollup' +import chalk from 'chalk' + +import { createInputConfig, createOutputConfig, version, env } from './config.js' + +async function build({ index, replaceValues, fileName, format, parentDir, name }) { + const text = `version ${version}${env ? ` ${env} `: ' '}${format} file` + + console.log(`Start building ${text}...\n`) + + try { + const startTime = new Date().getTime() + const bundle = await rollup(createInputConfig({ input: index, replaceValues })) + + await bundle.write(createOutputConfig({ + fileName, format, name, parentDir + })); + + console.log(chalk.green(`\n✔️ Compiled ${text} successfully.\n`)); + console.log(`Done in ${((new Date().getTime() - startTime) / 1000 / 60).toFixed(2)}s.\n`) + } catch (err) { + console.log(`\n\n${chalk.red(err)}\n`); + console.log(chalk.red(`✖️ Failed to compile ${text}.\n`)); + process.exit(1); + } +} + +export default build diff --git a/scripts/clean.cjs b/scripts/clean.js similarity index 50% rename from scripts/clean.cjs rename to scripts/clean.js index ad8b7cdf..d1f7dcae 100644 --- a/scripts/clean.cjs +++ b/scripts/clean.js @@ -1,19 +1,20 @@ -'use strict'; -const fs = require('fs'); -const chalk = require('chalk'); +import fs from 'fs' +import chalk from 'chalk' -const { resolvePath, buildDir } = require('./paths.cjs'); +import { resolvePath } from './utils.js' + +const buildDir = resolvePath('dist') let totalFileCount = 0 let deletedFileCount = 0 function eachFiles (dir) { if (fs.existsSync(dir)) { - const files = fs.readdirSync(dir); + const files = fs.readdirSync(dir) files.forEach(file => { - const path = resolvePath(file, dir); + const path = resolvePath(file, dir) if (fs.statSync(path).isDirectory()) { - eachFiles(path); + eachFiles(path) } else { totalFileCount++ } @@ -23,29 +24,29 @@ function eachFiles (dir) { function deleteFiles (dir) { if (fs.existsSync(dir)) { - const files = fs.readdirSync(dir); + const files = fs.readdirSync(dir) files.forEach(file => { - const path = resolvePath(file, dir); + const path = resolvePath(file, dir) if (fs.statSync(path).isDirectory()) { - deleteDir(path); + deleteFiles(path) } else { - fs.unlinkSync(path); + fs.unlinkSync(path) deletedFileCount++ process.stdout.clearLine(process.stdout); - process.stdout.cursorTo(0); - const percent = `${Math.round(deletedFileCount / totalFileCount * 100)}%`; - process.stdout.write(`${chalk.blue(`${percent}(${deletedFileCount}/${totalFileCount}): ${file}`)}`, 'utf-8'); + process.stdout.cursorTo(0) + const percent = `${Math.round(deletedFileCount / totalFileCount * 100)}%` + process.stdout.write(`${chalk.blue(`${percent}(${deletedFileCount}/${totalFileCount}): ${file}`)}`, 'utf-8') } }) - fs.rmdirSync(dir); + fs.rmdirSync(dir) } } function clean () { - eachFiles(buildDir); - deleteFiles(buildDir); + eachFiles(buildDir) + deleteFiles(buildDir) - console.log(chalk.green('\n\n✔️ Clean successfully.\n')); + console.log(chalk.green('\n\n✔️ Clean successfully.\n')) } -clean(); +clean() diff --git a/scripts/config.cjs b/scripts/config.cjs deleted file mode 100644 index 859149e0..00000000 --- a/scripts/config.cjs +++ /dev/null @@ -1,69 +0,0 @@ -'use strict'; - -const { nodeResolve } = require('@rollup/plugin-node-resolve'); -const eslint = require('@rollup/plugin-eslint'); -const replace = require('@rollup/plugin-replace'); -const commonjs = require('@rollup/plugin-commonjs'); -const typescript = require('@rollup/plugin-typescript'); -const terser = require('@rollup/plugin-terser'); -const fileSize = require('rollup-plugin-filesize'); -const progress = require('rollup-plugin-progress'); - -const paths = require('./paths.cjs'); - -const packageJson = require(paths.packageJson); - -const version = packageJson.version; - -const plugins = (env) => [ - typescript(), - eslint({ - throwOnError: true - }), - nodeResolve(), - commonjs(), - progress(), - replace({ - preventAssignment: true, - values: { - '__BUILD_ENV__': env, - '__BUILD_VERSION__': version - } - }), - fileSize(), - env === 'production' && terser({ - compress: { - pure_getters: true, - unsafe: true, - unsafe_comps: true - } - }) -]; - -function inputConfig (env) { - return { input: paths.index, plugins: plugins(env) }; -} - -function outputConfig (env, fileName) { - const isDevelopment = env === 'development'; - return { - file: paths.resolvePath(fileName, paths.buildDir), - format: 'umd', - name: 'klinecharts', - sourcemap: isDevelopment, - indent: false, - banner: ` -/** - * @license - * KLineChart v${version} - * Copyright (c) 2019 lihu. - * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 - */`.trim(), - }; -} - -module.exports = { - inputConfig, - outputConfig, - version -}; diff --git a/scripts/config.js b/scripts/config.js new file mode 100644 index 00000000..685b9e9c --- /dev/null +++ b/scripts/config.js @@ -0,0 +1,82 @@ +import { nodeResolve } from '@rollup/plugin-node-resolve' +import eslint from '@rollup/plugin-eslint' +import replace from '@rollup/plugin-replace' +// import commonjs from '@rollup/plugin-commonjs' +import typescript from '@rollup/plugin-typescript' +import terser from '@rollup/plugin-terser' +import fileSize from 'rollup-plugin-filesize' +import progress from 'rollup-plugin-progress' + +import { resolvePath, getVersion } from './utils.js' + +const version = getVersion() + +const env = process.env.NODE_ENV + +const isDev = env === 'development' + +const isProd = env === 'production' + +const buildDir = resolvePath('dist') + +function createInputConfig ({ input, replaceValues }) { + return { + input, + plugins: [ + typescript(), + eslint({ + throwOnError: true + }), + nodeResolve(), + // commonjs(), + progress(), + replace({ + preventAssignment: true, + values: { + '__VERSION__': version, + ...replaceValues + } + }), + fileSize(), + isProd && terser() + ].filter(p => !!p) + } +} + +function createOutputConfig ({ + fileName, format, name, parentDir +}) { + let file + if (parentDir) { + file = resolvePath(fileName, resolvePath(parentDir, buildDir)) + } else { + file = resolvePath(fileName, buildDir) + } + const config = { + file, + format, + sourcemap: isDev, + indent: false, + banner: ` + /** + * @license + * KLineChart v${version} + * Copyright (c) 2019 lihu. + * Licensed under Apache License 2.0 https://www.apache.org/licenses/LICENSE-2.0 + */`.trim(), + } + + if (!!name) { + config.name = name + } + return config +} + +export { + createInputConfig, + createOutputConfig, + version, + env, + isDev, + isProd +} diff --git a/scripts/paths.cjs b/scripts/paths.cjs deleted file mode 100644 index d5b84711..00000000 --- a/scripts/paths.cjs +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -const path = require('path'); -const fs = require('fs'); - -const root = fs.realpathSync(process.cwd()); -const resolvePath = (relativePath, rootDirectory = root) => path.resolve(rootDirectory, relativePath); - -module.exports = { - resolvePath, - buildDir: resolvePath('dist'), - index: resolvePath('src/index.ts'), - packageJson: resolvePath('package.json') -}; diff --git a/scripts/utils.js b/scripts/utils.js new file mode 100644 index 00000000..a301a5f7 --- /dev/null +++ b/scripts/utils.js @@ -0,0 +1,13 @@ + +import path from 'path' +import fs from 'fs' + +const root = fs.realpathSync(process.cwd()) +const resolvePath = (relativePath, rootDirectory = root) => path.resolve(rootDirectory, relativePath) + +function getVersion () { + const result = fs.readFileSync(resolvePath('package.json'), 'utf-8') + return JSON.parse(result).version +} + +export { resolvePath, getVersion } diff --git a/src/common/utils/logger.ts b/src/common/utils/logger.ts index 9fc99e65..04447ebf 100644 --- a/src/common/utils/logger.ts +++ b/src/common/utils/logger.ts @@ -12,8 +12,7 @@ * limitations under the License. */ -// @ts-expect-error -const DEV = '__BUILD_ENV__' === 'development' +const DEV = process.env.NODE_ENV === 'development' function log (templateText: string, tagStyle: string, messageStyle: string, api: string, invalidParam: string, append: string): void { if (DEV) { @@ -36,15 +35,15 @@ export function logWarn (api: string, invalidParam: string, append?: string): vo export function logError (api: string, invalidParam: string, append?: string): void { log( '%c😟 klinecharts error%c %s%s%s', - 'padding:3px 4px;border-radius:2px;color:#ffffff;background-color:#EF5350;', - 'color:#EF5350;', + 'padding:3px 4px;border-radius:2px;color:#ffffff;background-color:#F92855;', + 'color:#F92855;', api, invalidParam, append ?? '' ) } export function logTag (): void { log( - '%c❤️ Welcome to klinecharts. Version is __BUILD_VERSION__', + '%c❤️ Welcome to klinecharts. Version is __VERSION__', 'border-radius:4px;border:dashed 1px #1677FF;line-height:70px;padding:0 20px;margin:16px 0;font-size:14px;color:#1677FF;', '', '', diff --git a/src/index.ts b/src/index.ts index a228e8a7..b6614786 100644 --- a/src/index.ts +++ b/src/index.ts @@ -69,7 +69,7 @@ let chartBaseId = 1 * @return {string} */ function version (): string { - return '__BUILD_VERSION__' + return '__VERSION__' } /**