chore: update build script

pull/6316/head
tangjinzhou 2023-02-23 17:20:38 +08:00
parent 53b146ab88
commit 33a47bc27a
18 changed files with 254 additions and 409 deletions

View File

@ -1,195 +1,36 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); 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) { const restCssPath = path.join(process.cwd(), 'components', 'style', 'reset.css');
return `const { ${theme}ThemeSingle } = require('./theme');\nconst defaultTheme = require('./default-theme');\n const tokenStatisticPath = path.join(process.cwd(), 'components', 'version', 'token.json');
module.exports = { const tokenMetaPath = path.join(process.cwd(), 'components', 'version', 'token-meta.json');
...defaultTheme,
...${theme}ThemeSingle
}`;
}
// We need compile additional content for antd user
function finalizeCompile() { 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'))) { if (fs.existsSync(path.join(__dirname, './lib'))) {
// Build a entry less file to dist/antd.less fs.copyFileSync(restCssPath, path.join(process.cwd(), 'lib', 'style', 'reset.css'));
const componentsPath = path.join(process.cwd(), 'components'); fs.copyFileSync(tokenStatisticPath, path.join(process.cwd(), 'lib', 'version', 'token.json'));
let componentsLessContent = ''; fs.copyFileSync(tokenMetaPath, path.join(process.cwd(), 'lib', 'version', 'token-meta.json'));
// 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,
);
});
} }
} }
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() { function finalizeDist() {
if (fs.existsSync(path.join(__dirname, './dist'))) { if (fs.existsSync(path.join(__dirname, './dist'))) {
// Build less entry file: dist/antd.less fs.copyFileSync(restCssPath, path.join(process.cwd(), 'dist', 'reset.css'));
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
}
} }
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 = { module.exports = {
compile: { 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, finalize: finalizeCompile,
}, },
dist: { dist: {
finalize: finalizeDist, finalize: finalizeDist,
}, },
generateThemeFileContent,
bail: true, bail: true,
}; };

View File

@ -37,16 +37,12 @@ module.exports = {
collectCoverage: process.env.COVERAGE === 'true', collectCoverage: process.env.COVERAGE === 'true',
collectCoverageFrom: [ collectCoverageFrom: [
'components/**/*.{js,jsx,vue}', 'components/**/*.{js,jsx,vue}',
'!components/*/style/index.{js,jsx}',
'!components/style/*.{js,jsx}',
'!components/*/locale/*.{js,jsx}',
'!components/*/__tests__/**/type.{js,jsx}', '!components/*/__tests__/**/type.{js,jsx}',
'!components/vc-*/**/*', '!components/vc-*/**/*',
'!components/*/demo/**/*', '!components/*/demo/**/*',
'!components/_util/**/*', '!components/_util/**/*',
'!components/align/**/*', '!components/align/**/*',
'!components/trigger/**/*', '!components/trigger/**/*',
'!components/style.js',
'!**/node_modules/**', '!**/node_modules/**',
], ],
testEnvironment: 'jsdom', testEnvironment: 'jsdom',

View File

@ -18,7 +18,6 @@ yarn-error.log
.editorconfig .editorconfig
.eslintignore .eslintignore
**/*.yml **/*.yml
components/style/color/*.less
**/assets **/assets
.gitattributes .gitattributes
.stylelintrc .stylelintrc

View File

@ -3,10 +3,9 @@ function useProdHMR() {
} }
let webpackHMR = false; let webpackHMR = false;
let viteHMR = false;
function useDevHMR() { function useDevHMR() {
return webpackHMR || viteHMR; return webpackHMR;
} }
export default process.env.NODE_ENV === 'production' ? useProdHMR : useDevHMR; 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 // We have to hack handler to force mark as HRM
if ( if (
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'production' &&
((typeof module !== 'undefined' && typeof module !== 'undefined' &&
module && module &&
// @ts-ignore (module as any).hot
module.hot) ||
// @ts-ignore
import.meta.hot)
) { ) {
const win = window as any; const win = window as any;
if (typeof win.webpackHotUpdate === 'function') { if (typeof win.webpackHotUpdate === 'function') {
const originWebpackHotUpdate = win.webpackHotUpdate; const originWebpackHotUpdate = win.webpackHotUpdate;
@ -34,8 +29,5 @@ if (
}, 0); }, 0);
return originWebpackHotUpdate(...args); return originWebpackHotUpdate(...args);
}; };
// @ts-ignore
} else if (import.meta.hot) {
viteHMR = true;
} }
} }

View File

@ -19,8 +19,10 @@ import type { FullToken } from './util/genComponentStyleHook';
import genComponentStyleHook from './util/genComponentStyleHook'; import genComponentStyleHook from './util/genComponentStyleHook';
import statisticToken, { merge as mergeToken, statistic } from './util/statistic'; import statisticToken, { merge as mergeToken, statistic } from './util/statistic';
import type { VueNode } from '../_util/type'; import type { VueNode } from '../_util/type';
import { objectType } from '../_util/type';
import type { ComputedRef, InjectionKey, Ref } from 'vue'; 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); const defaultTheme = createTheme(defaultDerivative);
@ -60,6 +62,25 @@ export interface DesignTokenContext {
} }
//defaultConfig //defaultConfig
const DesignTokenContextKey: InjectionKey<DesignTokenContext> = Symbol('DesignTokenContext'); const DesignTokenContextKey: InjectionKey<DesignTokenContext> = Symbol('DesignTokenContext');
export const useDesignTokenProvider = (value: DesignTokenContext) => {
provide(DesignTokenContextKey, value);
};
export const useDesignTokenInject = () => {
return inject(DesignTokenContextKey, defaultConfig);
};
export const DesignTokenProvider = defineComponent({
props: {
value: objectType<DesignTokenContext>(),
},
setup(props, { slots }) {
useDesignTokenProvider(toReactive(computed(() => props.value)));
return () => {
return slots.default?.();
};
},
});
// ================================== Hook ================================== // ================================== Hook ==================================
export function useToken(): [ export function useToken(): [
ComputedRef<Theme<SeedToken, MapToken>>, ComputedRef<Theme<SeedToken, MapToken>>,

View File

@ -6,9 +6,9 @@ import { genCommonStyle, genLinkStyle } from '../../_style';
import type { UseComponentStyleResult } from '../internal'; import type { UseComponentStyleResult } from '../internal';
import { mergeToken, statisticToken, useToken } from '../internal'; import { mergeToken, statisticToken, useToken } from '../internal';
import type { ComponentTokenMap, GlobalToken } from '../interface'; import type { ComponentTokenMap, GlobalToken } from '../interface';
import useConfigInject from '../../config-provider/hooks/useConfigInject';
import type { Ref } from 'vue'; import type { Ref } from 'vue';
import { computed } from 'vue'; import { computed } from 'vue';
import { useConfigContextInject } from '../../config-provider/context';
export type OverrideTokenWithoutDerivative = ComponentTokenMap; export type OverrideTokenWithoutDerivative = ComponentTokenMap;
export type OverrideComponent = keyof OverrideTokenWithoutDerivative; export type OverrideComponent = keyof OverrideTokenWithoutDerivative;
@ -44,9 +44,11 @@ export default function genComponentStyleHook<ComponentName extends OverrideComp
| OverrideTokenWithoutDerivative[ComponentName] | OverrideTokenWithoutDerivative[ComponentName]
| ((token: GlobalToken) => OverrideTokenWithoutDerivative[ComponentName]), | ((token: GlobalToken) => OverrideTokenWithoutDerivative[ComponentName]),
) { ) {
return (prefixCls: Ref<string>): UseComponentStyleResult => { return (_prefixCls?: Ref<string>): UseComponentStyleResult => {
const prefixCls = computed(() => _prefixCls?.value);
const [theme, token, hashId] = useToken(); const [theme, token, hashId] = useToken();
const { rootPrefixCls, iconPrefixCls } = useConfigInject('', {}); const { getPrefixCls, iconPrefixCls } = useConfigContextInject();
const rootPrefixCls = computed(() => getPrefixCls());
const sharedInfo = computed(() => { const sharedInfo = computed(() => {
return { return {
theme: theme.value, theme: theme.value,

View File

@ -130,7 +130,7 @@ export default (prefixCls: Ref<string>, injectStyle: Ref<boolean>): UseComponent
'Tooltip', 'Tooltip',
token => { token => {
// Popover use Tooltip as internal component. We do not need to handle this. // Popover use Tooltip as internal component. We do not need to handle this.
if (injectStyle.value === false) { if (injectStyle?.value === false) {
return []; return [];
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "ant-design-vue", "name": "ant-design-vue",
"version": "3.3.0-beta.4", "version": "4.0.0-beta.1",
"title": "Ant Design Vue", "title": "Ant Design Vue",
"description": "An enterprise-class UI design language and Vue-based implementation", "description": "An enterprise-class UI design language and Vue-based implementation",
"keywords": [ "keywords": [
@ -30,17 +30,19 @@
"locale" "locale"
], ],
"scripts": { "scripts": {
"predev": "npm run version && node node_modules/esbuild/install.js", "collect-token-statistic": "ts-node --project tsconfig.node.json scripts/collect-token-statistic.js",
"precompile": "npm run version", "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", "pretest": "npm run version",
"predist": "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", "dev": "npm run predev && npm run routes && vite serve site",
"test": "cross-env NODE_ENV=test jest --config .jest.js", "test": "cross-env NODE_ENV=test jest --config .jest.js",
"compile": "node antd-tools/cli/run.js compile", "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", "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": "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 && node antd-tools/cli/run.js pub-with-ci", "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", "prepublishOnly": "node antd-tools/cli/run.js guard",
"pre-publish": "npm run generator-webtypes", "pre-publish": "npm run generator-webtypes",
"prettier": "prettier -c --write **/*", "prettier": "prettier -c --write **/*",
@ -220,6 +222,7 @@
"prettier": "^2.2.0", "prettier": "^2.2.0",
"pretty-quick": "^3.0.0", "pretty-quick": "^3.0.0",
"prismjs": "^1.23.0", "prismjs": "^1.23.0",
"progress": "^2.0.3",
"qs": "^6.10.3", "qs": "^6.10.3",
"raw-loader": "^4.0.2", "raw-loader": "^4.0.2",
"remark-frontmatter": "^2.0.0", "remark-frontmatter": "^2.0.0",
@ -245,6 +248,7 @@
"through2": "^3.0.0", "through2": "^3.0.0",
"ts-jest": "^28.0.5", "ts-jest": "^28.0.5",
"ts-loader": "^9.1.0", "ts-loader": "^9.1.0",
"ts-node": "^10.8.2",
"typescript": "~4.9.3", "typescript": "~4.9.3",
"umi-request": "^1.3.5", "umi-request": "^1.3.5",
"unified": "9.2.2", "unified": "9.2.2",
@ -298,8 +302,6 @@
}, },
"sideEffects": [ "sideEffects": [
"site/*", "site/*",
"components/style.ts",
"components/**/style/*",
"*.vue", "*.vue",
"*.md", "*.md",
"dist/*", "dist/*",

View File

@ -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);
})();

View File

@ -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;

View File

@ -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;

View File

@ -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();

View File

@ -4,7 +4,7 @@ const path = require('path');
const { version } = require('../package.json'); const { version } = require('../package.json');
fs.writeFileSync( fs.writeFileSync(
path.join(__dirname, '..', 'components', 'version', 'version.tsx'), path.join(__dirname, '..', 'components', 'version', 'version.ts'),
`export default '${version}'`, `export default '${version}';`,
'utf8', 'utf8',
); );

View File

@ -25,7 +25,6 @@ const ignoreFiles = [
'dist/**', 'dist/**',
'**/**.snap', '**/**.snap',
'**/**.map', '**/**.map',
'**/components/style/color/**',
'**/dist/**', '**/dist/**',
'_site/**', '_site/**',
]; ];

View File

@ -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();

View File

@ -7,7 +7,7 @@
"ant-design-vue/lib/*": ["components/*"], "ant-design-vue/lib/*": ["components/*"],
"ant-design-vue/locale/*": ["components/locale/*"] "ant-design-vue/locale/*": ["components/locale/*"]
}, },
"lib": ["ESNext", "DOM", "DOM.Iterable"], "lib": ["dom", "es2017"],
"strictNullChecks": false, "strictNullChecks": false,
"moduleResolution": "node", "moduleResolution": "node",
"esModuleInterop": true, "esModuleInterop": true,
@ -16,12 +16,12 @@
"noUnusedParameters": true, "noUnusedParameters": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noImplicitAny": false, "noImplicitAny": false,
"target": "esnext", "target": "es6",
"module": "esnext", "module": "esnext",
"skipLibCheck": true, "skipLibCheck": true,
"allowJs": true, "allowJs": true,
"importsNotUsedAsValues": "preserve", "importsNotUsedAsValues": "preserve",
"stripInternal": true "stripInternal": true
}, },
"exclude": ["node_modules", "lib", "es", "dist", "v2-doc", "scripts", "**/__tests__/**/*"] "exclude": ["node_modules", "lib", "es", "dist", "scripts", "**/__tests__/**/*"]
} }

7
tsconfig.node.json Normal file
View File

@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"types": ["node"]
}
}

View File

@ -1,35 +1,8 @@
// This config is for building dist files // 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 { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const { ESBuildMinifyPlugin } = require('esbuild-loader'); const { ESBuildMinifyPlugin } = require('esbuild-loader');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin'); const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const getWebpackConfig = require('./antd-tools/getWebpackConfig'); 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) { function addLocales(webpackConfig) {
let packageName = 'antd-with-locales'; let packageName = 'antd-with-locales';
@ -41,15 +14,14 @@ function addLocales(webpackConfig) {
} }
function externalDayjs(config) { function externalDayjs(config) {
config.externals.push({ config.externals.dayjs = {
dayjs: { dayjs: {
root: 'dayjs', root: 'dayjs',
commonjs2: 'dayjs', commonjs2: 'dayjs',
commonjs: 'dayjs', commonjs: 'dayjs',
amd: 'dayjs', amd: 'dayjs',
module: 'dayjs',
}, },
}); };
config.externals.push(function ({ _context, request }, callback) { config.externals.push(function ({ _context, request }, callback) {
if (/^dayjs\/plugin\//.test(request)) { if (/^dayjs\/plugin\//.test(request)) {
const name = request.replace(/\//g, '_'); const name = request.replace(/\//g, '_');
@ -58,7 +30,6 @@ function externalDayjs(config) {
commonjs2: name, commonjs2: name,
commonjs: name, commonjs: name,
amd: name, amd: name,
module: name,
}); });
} }
callback(); callback();
@ -83,58 +54,8 @@ function injectWarningCondition(config) {
}); });
} }
function processWebpackThemeConfig(themeConfig, theme, vars) { const webpackConfig = getWebpackConfig(false);
themeConfig.forEach(config => { const webpackESMConfig = getWebpackConfig(false, true);
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',
});
webpackConfig.forEach(config => { webpackConfig.forEach(config => {
injectWarningCondition(config); injectWarningCondition(config);
@ -142,8 +63,8 @@ webpackConfig.forEach(config => {
if (process.env.RUN_ENV === 'PRODUCTION') { if (process.env.RUN_ENV === 'PRODUCTION') {
webpackConfig.forEach(config => { webpackConfig.forEach(config => {
externalDayjs(config);
addLocales(config); addLocales(config);
externalDayjs(config);
// Reduce non-minified dist files size // Reduce non-minified dist files size
config.optimization.usedExports = true; config.optimization.usedExports = true;
// use esbuild // 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 = [ module.exports = [...webpackConfig, ...webpackESMConfig];
...webpackConfig,
...webpackESMConfig,
...webpackDarkConfig,
...webpackCompactConfig,
...webpackVariableConfig,
];