From 33a47bc27adbe7337462a7efc55e1e14510ac43d Mon Sep 17 00:00:00 2001 From: tangjinzhou <415800467@qq.com> Date: Thu, 23 Feb 2023 17:20:38 +0800 Subject: [PATCH] chore: update build script --- .antd-tools.config.js | 185 ++---------------- .jest.js | 4 - .prettierignore | 1 - components/_util/cssinjs/hooks/useHMR.ts | 16 +- components/theme/internal.ts | 23 ++- .../theme/util/genComponentStyleHook.ts | 8 +- components/tooltip/style/index.ts | 2 +- package.json | 18 +- scripts/collect-token-statistic.js | 80 ++++++++ scripts/dark-vars.js | 18 -- scripts/default-vars.js | 19 -- scripts/generate-token-meta.js | 101 ++++++++++ scripts/generate-version.js | 4 +- scripts/prettier.js | 1 - scripts/syncStyleFromAntd.js | 69 ------- tsconfig.json | 6 +- tsconfig.node.json | 7 + webpack.build.conf.js | 101 +--------- 18 files changed, 254 insertions(+), 409 deletions(-) create mode 100644 scripts/collect-token-statistic.js delete mode 100644 scripts/dark-vars.js delete mode 100644 scripts/default-vars.js create mode 100644 scripts/generate-token-meta.js delete mode 100644 scripts/syncStyleFromAntd.js create mode 100644 tsconfig.node.json diff --git a/.antd-tools.config.js b/.antd-tools.config.js index 7118b5000..36b9b7598 100644 --- a/.antd-tools.config.js +++ b/.antd-tools.config.js @@ -1,195 +1,36 @@ const fs = require('fs'); const path = require('path'); -const defaultVars = require('./scripts/default-vars'); -const darkVars = require('./scripts/dark-vars'); -const compactVars = require('./scripts/compact-vars'); -function generateThemeFileContent(theme) { - return `const { ${theme}ThemeSingle } = require('./theme');\nconst defaultTheme = require('./default-theme');\n -module.exports = { - ...defaultTheme, - ...${theme}ThemeSingle -}`; -} +const restCssPath = path.join(process.cwd(), 'components', 'style', 'reset.css'); +const tokenStatisticPath = path.join(process.cwd(), 'components', 'version', 'token.json'); +const tokenMetaPath = path.join(process.cwd(), 'components', 'version', 'token-meta.json'); -// We need compile additional content for antd user function finalizeCompile() { + if (fs.existsSync(path.join(__dirname, './es'))) { + fs.copyFileSync(restCssPath, path.join(process.cwd(), 'es', 'style', 'reset.css')); + fs.copyFileSync(tokenStatisticPath, path.join(process.cwd(), 'es', 'version', 'token.json')); + fs.copyFileSync(tokenMetaPath, path.join(process.cwd(), 'es', 'version', 'token-meta.json')); + } + if (fs.existsSync(path.join(__dirname, './lib'))) { - // Build a entry less file to dist/antd.less - const componentsPath = path.join(process.cwd(), 'components'); - let componentsLessContent = ''; - // Build components in one file: lib/style/components.less - fs.readdir(componentsPath, (err, files) => { - files.forEach(file => { - if (fs.existsSync(path.join(componentsPath, file, 'style', 'index.less'))) { - componentsLessContent += `@import "../${path.posix.join( - file, - 'style', - 'index-pure.less', - )}";\n`; - } - }); - fs.writeFileSync( - path.join(process.cwd(), 'lib', 'style', 'components.less'), - componentsLessContent, - ); - }); + fs.copyFileSync(restCssPath, path.join(process.cwd(), 'lib', 'style', 'reset.css')); + fs.copyFileSync(tokenStatisticPath, path.join(process.cwd(), 'lib', 'version', 'token.json')); + fs.copyFileSync(tokenMetaPath, path.join(process.cwd(), 'lib', 'version', 'token-meta.json')); } } -function buildThemeFile(theme, vars) { - // Build less entry file: dist/antd.${theme}.less - if (theme !== 'default') { - fs.writeFileSync( - path.join(process.cwd(), 'dist', `antd.${theme}.less`), - `@import "../lib/style/${theme}.less";\n@import "../lib/style/components.less";`, - ); - // eslint-disable-next-line no-console - console.log(`Built a entry less file to dist/antd.${theme}.less`); - } else { - fs.writeFileSync( - path.join(process.cwd(), 'dist', `default-theme.js`), - `module.exports = ${JSON.stringify(vars, null, 2)};\n`, - ); - return; - } - - // Build ${theme}.js: dist/${theme}-theme.js, for less-loader - - fs.writeFileSync( - path.join(process.cwd(), 'dist', `theme.js`), - `const ${theme}ThemeSingle = ${JSON.stringify(vars, null, 2)};\n`, - { - flag: 'a', - }, - ); - - fs.writeFileSync( - path.join(process.cwd(), 'dist', `${theme}-theme.js`), - generateThemeFileContent(theme), - ); - - // eslint-disable-next-line no-console - console.log(`Built a ${theme} theme js file to dist/${theme}-theme.js`); -} - function finalizeDist() { if (fs.existsSync(path.join(__dirname, './dist'))) { - // Build less entry file: dist/antd.less - fs.writeFileSync( - path.join(process.cwd(), 'dist', 'antd.less'), - '@import "../lib/style/default.less";\n@import "../lib/style/components.less";', - ); - // eslint-disable-next-line no-console - fs.writeFileSync( - path.join(process.cwd(), 'dist', 'theme.js'), - `const defaultTheme = require('./default-theme.js');\n`, - ); - // eslint-disable-next-line no-console - console.log('Built a entry less file to dist/antd.less'); - buildThemeFile('default', defaultVars); - buildThemeFile('dark', darkVars); - buildThemeFile('compact', compactVars); - buildThemeFile('variable', {}); - fs.writeFileSync( - path.join(process.cwd(), 'dist', `theme.js`), - ` -function getThemeVariables(options = {}) { - let themeVar = { - 'hack': \`true;@import "\${require.resolve('ant-design-vue/lib/style/color/colorPalette.less')}";\`, - ...defaultTheme - }; - if(options.dark) { - themeVar = { - ...themeVar, - ...darkThemeSingle - } + fs.copyFileSync(restCssPath, path.join(process.cwd(), 'dist', 'reset.css')); } - if(options.compact){ - themeVar = { - ...themeVar, - ...compactThemeSingle - } - } - return themeVar; -} - -module.exports = { - darkThemeSingle, - compactThemeSingle, - getThemeVariables -}`, - { - flag: 'a', - }, - ); - } -} - -function isComponentStyleEntry(file) { - return file.path.match(/style(\/|\\)index\.tsx/); -} - -function needTransformStyle(content) { - return content.includes('../../style/index.less') || content.includes('./index.less'); } module.exports = { compile: { - includeLessFile: [/(\/|\\)components(\/|\\)style(\/|\\)default.less$/], - transformTSFile(file) { - if (isComponentStyleEntry(file)) { - let content = file.contents.toString(); - - if (needTransformStyle(content)) { - const cloneFile = file.clone(); - - // Origin - content = content.replace('../../style/index.less', '../../style/default.less'); - cloneFile.contents = Buffer.from(content); - - return cloneFile; - } - } - }, - transformFile(file) { - if (isComponentStyleEntry(file)) { - const indexLessFilePath = file.path.replace('index.tsx', 'index.less'); - - if (fs.existsSync(indexLessFilePath)) { - // We put origin `index.less` file to `index-pure.less` - const pureFile = file.clone(); - pureFile.contents = Buffer.from(fs.readFileSync(indexLessFilePath, 'utf8')); - pureFile.path = pureFile.path.replace('index.tsx', 'index-pure.less'); - - // Rewrite `index.less` file with `root-entry-name` - const indexLessFile = file.clone(); - indexLessFile.contents = Buffer.from( - [ - // Inject variable - '@root-entry-name: default;', - // Point to origin file - "@import './index-pure.less';", - ].join('\n\n'), - ); - indexLessFile.path = indexLessFile.path.replace('index.tsx', 'index.less'); - - return [indexLessFile, pureFile]; - } - } - - return []; - }, - lessConfig: { - modifyVars: { - 'root-entry-name': 'default', - }, - }, finalize: finalizeCompile, }, dist: { finalize: finalizeDist, }, - generateThemeFileContent, bail: true, }; diff --git a/.jest.js b/.jest.js index 3086ad2d2..b2988233f 100644 --- a/.jest.js +++ b/.jest.js @@ -37,16 +37,12 @@ module.exports = { collectCoverage: process.env.COVERAGE === 'true', collectCoverageFrom: [ 'components/**/*.{js,jsx,vue}', - '!components/*/style/index.{js,jsx}', - '!components/style/*.{js,jsx}', - '!components/*/locale/*.{js,jsx}', '!components/*/__tests__/**/type.{js,jsx}', '!components/vc-*/**/*', '!components/*/demo/**/*', '!components/_util/**/*', '!components/align/**/*', '!components/trigger/**/*', - '!components/style.js', '!**/node_modules/**', ], testEnvironment: 'jsdom', diff --git a/.prettierignore b/.prettierignore index fc219ac37..b3b276aff 100644 --- a/.prettierignore +++ b/.prettierignore @@ -18,7 +18,6 @@ yarn-error.log .editorconfig .eslintignore **/*.yml -components/style/color/*.less **/assets .gitattributes .stylelintrc diff --git a/components/_util/cssinjs/hooks/useHMR.ts b/components/_util/cssinjs/hooks/useHMR.ts index 481d63038..4fc7ab7ed 100644 --- a/components/_util/cssinjs/hooks/useHMR.ts +++ b/components/_util/cssinjs/hooks/useHMR.ts @@ -3,10 +3,9 @@ function useProdHMR() { } let webpackHMR = false; -let viteHMR = false; function useDevHMR() { - return webpackHMR || viteHMR; + return webpackHMR; } export default process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR; @@ -15,15 +14,11 @@ export default process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR; // We have to hack handler to force mark as HRM if ( process.env.NODE_ENV !== 'production' && - ((typeof module !== 'undefined' && - module && - // @ts-ignore - module.hot) || - // @ts-ignore - import.meta.hot) + typeof module !== 'undefined' && + module && + (module as any).hot ) { const win = window as any; - if (typeof win.webpackHotUpdate === 'function') { const originWebpackHotUpdate = win.webpackHotUpdate; @@ -34,8 +29,5 @@ if ( }, 0); return originWebpackHotUpdate(...args); }; - // @ts-ignore - } else if (import.meta.hot) { - viteHMR = true; } } diff --git a/components/theme/internal.ts b/components/theme/internal.ts index 78a19468b..aee0e5ba8 100644 --- a/components/theme/internal.ts +++ b/components/theme/internal.ts @@ -19,8 +19,10 @@ import type { FullToken } from './util/genComponentStyleHook'; import genComponentStyleHook from './util/genComponentStyleHook'; import statisticToken, { merge as mergeToken, statistic } from './util/statistic'; import type { VueNode } from '../_util/type'; +import { objectType } from '../_util/type'; import type { ComputedRef, InjectionKey, Ref } from 'vue'; -import { computed, inject } from 'vue'; +import { defineComponent, provide, computed, inject } from 'vue'; +import { toReactive } from '../_util/toReactive'; const defaultTheme = createTheme(defaultDerivative); @@ -60,6 +62,25 @@ export interface DesignTokenContext { } //defaultConfig const DesignTokenContextKey: InjectionKey = Symbol('DesignTokenContext'); + +export const useDesignTokenProvider = (value: DesignTokenContext) => { + provide(DesignTokenContextKey, value); +}; + +export const useDesignTokenInject = () => { + return inject(DesignTokenContextKey, defaultConfig); +}; +export const DesignTokenProvider = defineComponent({ + props: { + value: objectType(), + }, + setup(props, { slots }) { + useDesignTokenProvider(toReactive(computed(() => props.value))); + return () => { + return slots.default?.(); + }; + }, +}); // ================================== Hook ================================== export function useToken(): [ ComputedRef>, diff --git a/components/theme/util/genComponentStyleHook.ts b/components/theme/util/genComponentStyleHook.ts index 7705829b6..9b6cba739 100644 --- a/components/theme/util/genComponentStyleHook.ts +++ b/components/theme/util/genComponentStyleHook.ts @@ -6,9 +6,9 @@ import { genCommonStyle, genLinkStyle } from '../../_style'; import type { UseComponentStyleResult } from '../internal'; import { mergeToken, statisticToken, useToken } from '../internal'; import type { ComponentTokenMap, GlobalToken } from '../interface'; -import useConfigInject from '../../config-provider/hooks/useConfigInject'; import type { Ref } from 'vue'; import { computed } from 'vue'; +import { useConfigContextInject } from '../../config-provider/context'; export type OverrideTokenWithoutDerivative = ComponentTokenMap; export type OverrideComponent = keyof OverrideTokenWithoutDerivative; @@ -44,9 +44,11 @@ export default function genComponentStyleHook OverrideTokenWithoutDerivative[ComponentName]), ) { - return (prefixCls: Ref): UseComponentStyleResult => { + return (_prefixCls?: Ref): UseComponentStyleResult => { + const prefixCls = computed(() => _prefixCls?.value); const [theme, token, hashId] = useToken(); - const { rootPrefixCls, iconPrefixCls } = useConfigInject('', {}); + const { getPrefixCls, iconPrefixCls } = useConfigContextInject(); + const rootPrefixCls = computed(() => getPrefixCls()); const sharedInfo = computed(() => { return { theme: theme.value, diff --git a/components/tooltip/style/index.ts b/components/tooltip/style/index.ts index b668db728..88223298f 100644 --- a/components/tooltip/style/index.ts +++ b/components/tooltip/style/index.ts @@ -130,7 +130,7 @@ export default (prefixCls: Ref, injectStyle: Ref): UseComponent 'Tooltip', token => { // Popover use Tooltip as internal component. We do not need to handle this. - if (injectStyle.value === false) { + if (injectStyle?.value === false) { return []; } diff --git a/package.json b/package.json index f7ef3e06c..9da99cd75 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ant-design-vue", - "version": "3.3.0-beta.4", + "version": "4.0.0-beta.1", "title": "Ant Design Vue", "description": "An enterprise-class UI design language and Vue-based implementation", "keywords": [ @@ -30,17 +30,19 @@ "locale" ], "scripts": { - "predev": "npm run version && node node_modules/esbuild/install.js", - "precompile": "npm run version", + "collect-token-statistic": "ts-node --project tsconfig.node.json scripts/collect-token-statistic.js", + "token-meta": "node scripts/generate-token-meta.js", + "predev": "npm run version & npm run collect-token-statistic & npm run token-meta && node node_modules/esbuild/install.js", + "precompile": "npm run version & npm run collect-token-statistic & npm run token-meta", "pretest": "npm run version", "predist": "npm run version", - "presite": "npm run version", + "presite": "npm run version & npm run collect-token-statistic & npm run token-meta", "dev": "npm run predev && npm run routes && vite serve site", "test": "cross-env NODE_ENV=test jest --config .jest.js", "compile": "node antd-tools/cli/run.js compile", "generator-webtypes": "tsc -p antd-tools/generator-types/tsconfig.json && node antd-tools/generator-types/index.js", - "pub": "npm run version && node --max_old_space_size=8192 antd-tools/cli/run.js pub", - "pub-with-ci": "npm run version && node antd-tools/cli/run.js pub-with-ci", + "pub": "npm run version & npm run collect-token-statistic & npm run token-meta && node --max_old_space_size=8192 antd-tools/cli/run.js pub", + "pub-with-ci": "npm run version & npm run collect-token-statistic & npm run token-meta && node antd-tools/cli/run.js pub-with-ci", "prepublishOnly": "node antd-tools/cli/run.js guard", "pre-publish": "npm run generator-webtypes", "prettier": "prettier -c --write **/*", @@ -220,6 +222,7 @@ "prettier": "^2.2.0", "pretty-quick": "^3.0.0", "prismjs": "^1.23.0", + "progress": "^2.0.3", "qs": "^6.10.3", "raw-loader": "^4.0.2", "remark-frontmatter": "^2.0.0", @@ -245,6 +248,7 @@ "through2": "^3.0.0", "ts-jest": "^28.0.5", "ts-loader": "^9.1.0", + "ts-node": "^10.8.2", "typescript": "~4.9.3", "umi-request": "^1.3.5", "unified": "9.2.2", @@ -298,8 +302,6 @@ }, "sideEffects": [ "site/*", - "components/style.ts", - "components/**/style/*", "*.vue", "*.md", "dist/*", diff --git a/scripts/collect-token-statistic.js b/scripts/collect-token-statistic.js new file mode 100644 index 000000000..aef9c43cf --- /dev/null +++ b/scripts/collect-token-statistic.js @@ -0,0 +1,80 @@ +/* eslint-disable import/no-unresolved,no-console,global-require,import/no-dynamic-require */ + +const chalk = require('chalk'); +const VueServerRenderer = require('vue/server-renderer'); + +const fs = require('fs-extra'); +const glob = require('glob'); +const path = require('path'); +const ProgressBar = require('progress'); +const { statistic } = require('../components/theme/util/statistic'); +const { DesignTokenProvider } = require('../components/theme/internal'); +const seedToken = require('../components/theme/themes/seed'); +const { defineComponent, ref, createVNode, createSSRApp } = require('vue'); + +console.log(chalk.green(`🔥 Collecting token statistics...`)); + +const EmptyElement = createVNode('div'); + +const styleFiles = glob.sync( + path.join( + process.cwd(), + 'components/!(version|config-provider|icon|locale-provider|auto-complete|col|row|time-picker|)/style/index.?(ts|tsx)', + ), +); + +const bar = new ProgressBar('🚀 Collecting by component: [:bar] :component (:current/:total)', { + complete: '=', + incomplete: ' ', + total: styleFiles.length, +}); + +styleFiles.forEach(file => { + const pathArr = file.split('/'); + const styleIndex = pathArr.lastIndexOf('style'); + const componentName = pathArr[styleIndex - 1]; + bar.tick(1, { component: componentName }); + let useStyle = () => {}; + if (file.includes('grid')) { + const { useColStyle, useRowStyle } = require(file); + useStyle = () => { + useRowStyle(); + useColStyle(); + }; + } else { + useStyle = require(file).default; + } + const Component = defineComponent({ + setup() { + useStyle(ref('file'), ref()); + return () => EmptyElement; + }, + }); + VueServerRenderer.renderToString( + createSSRApp({ + setup() { + return () => createVNode(Component); + }, + }), + ); + // Render wireframe + VueServerRenderer.renderToString( + createSSRApp({ + setup() { + return () => + createVNode( + DesignTokenProvider, + { value: { token: { ...seedToken, wireframe: true } } }, + () => createVNode(Component), + ); + }, + }), + ); +}); + +(() => { + const tokenPath = `${process.cwd()}/components/version/token.json`; + fs.writeJsonSync(tokenPath, statistic, 'utf8'); + + console.log(chalk.green(`✅ Collected token statistics successfully, check it in`), tokenPath); +})(); diff --git a/scripts/dark-vars.js b/scripts/dark-vars.js deleted file mode 100644 index 04ca9e47d..000000000 --- a/scripts/dark-vars.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * convert dark.less into js vars - * - * const darkVars = require('./dark-vars'); - */ -const fs = require('fs'); -const path = require('path'); -const lessToJs = require('less-vars-to-js'); - -const stylePath = path.join(__dirname, '..', 'components', 'style'); -const darkLess = fs.readFileSync(path.join(stylePath, 'themes', 'dark.less'), 'utf8'); - -const darkPaletteLess = lessToJs(darkLess, { - stripPrefix: true, - resolveVariables: false, -}); - -module.exports = darkPaletteLess; diff --git a/scripts/default-vars.js b/scripts/default-vars.js deleted file mode 100644 index 31f290190..000000000 --- a/scripts/default-vars.js +++ /dev/null @@ -1,19 +0,0 @@ -/** - * convert default.less into js vars - * - * const darkVars = require('./default-vars'); - */ -const fs = require('fs'); -const path = require('path'); -const lessToJs = require('less-vars-to-js'); - -const stylePath = path.join(__dirname, '..', 'components', 'style'); -const colorLess = fs.readFileSync(path.join(stylePath, 'color', 'colors.less'), 'utf8'); -const defaultLess = fs.readFileSync(path.join(stylePath, 'themes', 'default.less'), 'utf8'); - -const defaultPaletteLess = lessToJs(`${colorLess}${defaultLess}`, { - stripPrefix: true, - resolveVariables: false, -}); - -module.exports = defaultPaletteLess; diff --git a/scripts/generate-token-meta.js b/scripts/generate-token-meta.js new file mode 100644 index 000000000..48b60f7e9 --- /dev/null +++ b/scripts/generate-token-meta.js @@ -0,0 +1,101 @@ +const TypeDoc = require('typedoc'); +const fs = require('fs-extra'); + +const getTokenList = (list, source) => + list + .filter( + item => + !item.comment?.blockTags.some(tag => tag.tag === '@internal' || tag.tag === '@private'), + ) + .map(item => ({ + source, + token: item.name, + type: item.type.toString(), + desc: + item.comment?.blockTags + ?.find(tag => tag.tag === '@desc') + ?.content.reduce((result, str) => result.concat(str.text), '') || '', + descEn: + item.comment?.blockTags + ?.find(tag => tag.tag === '@descEN') + ?.content.reduce((result, str) => result.concat(str.text), '') || '', + name: + item.comment?.blockTags + ?.find(tag => tag.tag === '@nameZH') + ?.content.reduce((result, str) => result.concat(str.text), '') || '', + nameEn: + item.comment?.blockTags + ?.find(tag => tag.tag === '@nameEN') + ?.content.reduce((result, str) => result.concat(str.text), '') || '', + })); + +function main() { + const app = new TypeDoc.Application(); + + // If you want TypeDoc to load tsconfig.json / typedoc.json files + app.options.addReader(new TypeDoc.TSConfigReader()); + app.options.addReader(new TypeDoc.TypeDocReader()); + + app.bootstrap({ + // typedoc options here + entryPoints: ['components/theme/interface/index.ts'], + }); + + const project = app.convert(); + + if (project) { + // Project may not have converted correctly + const output = 'components/version/token-meta.json'; + const tokenMeta = {}; + let presetColors = []; + project.children.forEach(type => { + if (type.name === 'SeedToken') { + tokenMeta.seed = getTokenList(type.children, 'seed'); + } else if (type.name === 'MapToken') { + tokenMeta.map = getTokenList(type.children, 'map'); + } else if (type.name === 'AliasToken') { + tokenMeta.alias = getTokenList(type.children, 'alias'); + } else if (type.name === 'PresetColors') { + presetColors = type.type.target.elements.map(item => item.value); + } + }); + + // Exclude preset colors + tokenMeta.seed = tokenMeta.seed.filter( + item => !presetColors.some(color => item.token.startsWith(color)), + ); + tokenMeta.map = tokenMeta.map.filter( + item => !presetColors.some(color => item.token.startsWith(color)), + ); + tokenMeta.alias = tokenMeta.alias.filter( + item => !presetColors.some(color => item.token.startsWith(color)), + ); + + tokenMeta.alias = tokenMeta.alias.filter( + item => !tokenMeta.map.some(mapItem => mapItem.token === item.token), + ); + tokenMeta.map = tokenMeta.map.filter( + item => !tokenMeta.seed.some(seedItem => seedItem.token === item.token), + ); + + const finalMeta = Object.entries(tokenMeta).reduce((acc, [key, value]) => { + value.forEach(item => { + acc[item.token] = { + name: item.name, + nameEn: item.nameEn, + desc: item.desc, + descEn: item.descEn, + type: item.type, + source: key, + }; + }); + return acc; + }, {}); + + fs.writeJsonSync(output, finalMeta, 'utf8'); + // eslint-disable-next-line no-console + console.log(`✅ Token Meta has been written to ${output}`); + } +} + +main(); diff --git a/scripts/generate-version.js b/scripts/generate-version.js index 0370a17df..42e79cb3f 100644 --- a/scripts/generate-version.js +++ b/scripts/generate-version.js @@ -4,7 +4,7 @@ const path = require('path'); const { version } = require('../package.json'); fs.writeFileSync( - path.join(__dirname, '..', 'components', 'version', 'version.tsx'), - `export default '${version}'`, + path.join(__dirname, '..', 'components', 'version', 'version.ts'), + `export default '${version}';`, 'utf8', ); diff --git a/scripts/prettier.js b/scripts/prettier.js index 27d5c28f4..3ef0ab53a 100644 --- a/scripts/prettier.js +++ b/scripts/prettier.js @@ -25,7 +25,6 @@ const ignoreFiles = [ 'dist/**', '**/**.snap', '**/**.map', - '**/components/style/color/**', '**/dist/**', '_site/**', ]; diff --git a/scripts/syncStyleFromAntd.js b/scripts/syncStyleFromAntd.js deleted file mode 100644 index b79d17e9f..000000000 --- a/scripts/syncStyleFromAntd.js +++ /dev/null @@ -1,69 +0,0 @@ -const { Octokit } = require('@octokit/rest'); -const Base64 = require('js-base64').Base64; -const fs = require('fs'); -const fse = require('fs-extra'); -const path = require('path'); - -const owner = 'ant-design'; -const repo = 'ant-design'; -const tag = '3.26.13'; -const clientId = '5f6ccfdc4cdc69f8ba12'; -const clientSecret = process.env.CLIENT_SECRET; - -const github = new Octokit(); - -async function syncFiles(data = []) { - for (const item of data) { - try { - const { data: itemData } = await github.repos.getContents({ - owner, - repo, - path: `${item.path}`, - ref: tag, - client_id: clientId, - client_secret: clientSecret, - }); - if (Array.isArray(itemData)) { - syncFiles(itemData); - } else { - const toPath = path.join(__dirname, '..', itemData.path.replace(`/${itemData.name}`, '')); - if (!fs.existsSync(toPath)) { - fse.ensureDirSync(toPath); - } - // eslint-disable-next-line no-console - console.log('update style: ', path.join(toPath, itemData.name.replace('.tsx', '.js'))); - const content = Base64.decode(itemData.content); - fs.writeFileSync(path.join(toPath, itemData.name.replace('.tsx', '.js')), content); - } - } catch (e) {} - } -} -async function syncStyle() { - const { data = [] } = await github.repos.getContents({ - owner, - repo, - path: 'components', - ref: tag, - client_id: clientId, - client_secret: clientSecret, - }); - - for (const item of data) { - try { - if (item.name === 'style') { - syncFiles([item]); - } else { - const { data: itemData } = await github.repos.getContents({ - owner, - repo, - path: `${item.path}/style`, - ref: tag, - client_id: clientId, - client_secret: clientSecret, - }); - syncFiles(itemData); - } - } catch (e) {} - } -} -syncStyle(); diff --git a/tsconfig.json b/tsconfig.json index 4fe495a19..80ed81973 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,7 @@ "ant-design-vue/lib/*": ["components/*"], "ant-design-vue/locale/*": ["components/locale/*"] }, - "lib": ["ESNext", "DOM", "DOM.Iterable"], + "lib": ["dom", "es2017"], "strictNullChecks": false, "moduleResolution": "node", "esModuleInterop": true, @@ -16,12 +16,12 @@ "noUnusedParameters": true, "noUnusedLocals": true, "noImplicitAny": false, - "target": "esnext", + "target": "es6", "module": "esnext", "skipLibCheck": true, "allowJs": true, "importsNotUsedAsValues": "preserve", "stripInternal": true }, - "exclude": ["node_modules", "lib", "es", "dist", "v2-doc", "scripts", "**/__tests__/**/*"] + "exclude": ["node_modules", "lib", "es", "dist", "scripts", "**/__tests__/**/*"] } diff --git a/tsconfig.node.json b/tsconfig.node.json new file mode 100644 index 000000000..d58b1bdd7 --- /dev/null +++ b/tsconfig.node.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "CommonJS", + "types": ["node"] + } +} diff --git a/webpack.build.conf.js b/webpack.build.conf.js index ca58c2425..b4ccb6723 100644 --- a/webpack.build.conf.js +++ b/webpack.build.conf.js @@ -1,35 +1,8 @@ // This config is for building dist files -const chalk = require('chalk'); -const RemovePlugin = require('remove-files-webpack-plugin'); const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer'); const { ESBuildMinifyPlugin } = require('esbuild-loader'); const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin'); const getWebpackConfig = require('./antd-tools/getWebpackConfig'); -const darkVars = require('./scripts/dark-vars'); -const compactVars = require('./scripts/compact-vars'); -function injectLessVariables(config, variables) { - (Array.isArray(config) ? config : [config]).forEach(conf => { - conf.module.rules.forEach(rule => { - // filter less rule - if (rule.test instanceof RegExp && rule.test.test('.less')) { - const lessRule = rule.use[rule.use.length - 1]; - if (lessRule.options.lessOptions) { - lessRule.options.lessOptions.modifyVars = { - ...lessRule.options.lessOptions.modifyVars, - ...variables, - }; - } else { - lessRule.options.modifyVars = { - ...lessRule.options.modifyVars, - ...variables, - }; - } - } - }); - }); - - return config; -} function addLocales(webpackConfig) { let packageName = 'antd-with-locales'; @@ -41,15 +14,14 @@ function addLocales(webpackConfig) { } function externalDayjs(config) { - config.externals.push({ + config.externals.dayjs = { dayjs: { root: 'dayjs', commonjs2: 'dayjs', commonjs: 'dayjs', amd: 'dayjs', - module: 'dayjs', }, - }); + }; config.externals.push(function ({ _context, request }, callback) { if (/^dayjs\/plugin\//.test(request)) { const name = request.replace(/\//g, '_'); @@ -58,7 +30,6 @@ function externalDayjs(config) { commonjs2: name, commonjs: name, amd: name, - module: name, }); } callback(); @@ -83,58 +54,8 @@ function injectWarningCondition(config) { }); } -function processWebpackThemeConfig(themeConfig, theme, vars) { - themeConfig.forEach(config => { - externalDayjs(config); - - // rename default entry to ${theme} entry - Object.keys(config.entry).forEach(entryName => { - const originPath = config.entry[entryName]; - let replacedPath = [...originPath]; - - // We will replace `./index` to `./index-style-only` since theme dist only use style file - if (originPath.length === 1 && originPath[0] === './index') { - replacedPath = ['./index-style-only']; - } else { - // eslint-disable-next-line no-console - console.log(chalk.red('🆘 Seems entry has changed! It should be `./index`')); - } - - config.entry[entryName.replace('antd', `antd.${theme}`)] = replacedPath; - delete config.entry[entryName]; - }); - - // apply ${theme} less variables - injectLessVariables(config, vars); - // ignore emit ${theme} entry js & js.map file - config.plugins.push( - new RemovePlugin({ - after: { - root: './dist', - include: [ - `antd.${theme}.js`, - `antd.${theme}.js.map`, - `antd.${theme}.min.js`, - `antd.${theme}.min.js.map`, - ], - log: false, - logWarning: false, - }, - }), - ); - }); -} - -const legacyEntryVars = { - 'root-entry-name': 'default', -}; -const webpackConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars); -const webpackESMConfig = injectLessVariables(getWebpackConfig(false, true), legacyEntryVars); -const webpackDarkConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars); -const webpackCompactConfig = injectLessVariables(getWebpackConfig(false), legacyEntryVars); -const webpackVariableConfig = injectLessVariables(getWebpackConfig(false), { - 'root-entry-name': 'variable', -}); +const webpackConfig = getWebpackConfig(false); +const webpackESMConfig = getWebpackConfig(false, true); webpackConfig.forEach(config => { injectWarningCondition(config); @@ -142,8 +63,8 @@ webpackConfig.forEach(config => { if (process.env.RUN_ENV === 'PRODUCTION') { webpackConfig.forEach(config => { - externalDayjs(config); addLocales(config); + externalDayjs(config); // Reduce non-minified dist files size config.optimization.usedExports = true; // use esbuild @@ -170,16 +91,6 @@ if (process.env.RUN_ENV === 'PRODUCTION') { ); } }); - - processWebpackThemeConfig(webpackDarkConfig, 'dark', darkVars); - processWebpackThemeConfig(webpackCompactConfig, 'compact', compactVars); - processWebpackThemeConfig(webpackVariableConfig, 'variable', {}); } -module.exports = [ - ...webpackConfig, - ...webpackESMConfig, - ...webpackDarkConfig, - ...webpackCompactConfig, - ...webpackVariableConfig, -]; +module.exports = [...webpackConfig, ...webpackESMConfig];