gatsby-node.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /* eslint-disable max-lines-per-function */
  2. /**
  3. * Implement Gatsby's Node APIs in this file.
  4. *
  5. * See: https://www.gatsbyjs.org/docs/node-apis/
  6. */
  7. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  8. const path = require('path');
  9. const fs = require('fs');
  10. const JSZip = require('jszip');
  11. const items = ['basic', 'chart'];
  12. const sha1 = require('sha1');
  13. const hash = sha1(`${new Date().getTime()}${Math.random()}`);
  14. const numHash = Math.round(Math.random() * 1000000);
  15. const glob = require('glob');
  16. function resolve(...dirs) {
  17. return path.resolve(__dirname, ...dirs);
  18. }
  19. // 打包 skills 目录到 static 文件夹
  20. async function packageSkills() {
  21. const skillsDir = resolve('ecosystem/semi-ui-skills');
  22. const outputPath = resolve('static/skills.zip');
  23. // 检查 skills 目录是否存在
  24. if (!fs.existsSync(skillsDir)) {
  25. console.log('Skills directory not found, skipping packaging');
  26. return;
  27. }
  28. console.log('Packaging skills directory...');
  29. const zip = new JSZip();
  30. const skillsFolderName = path.basename(skillsDir);
  31. const rootFolder = zip.folder(skillsFolderName);
  32. // 递归读取目录并添加到 zip,确保 semi-ui-skills 文件夹本身在 zip 中
  33. function addFolderToZip(dir, zipFolder) {
  34. const files = fs.readdirSync(dir);
  35. files.forEach(file => {
  36. const filePath = path.join(dir, file);
  37. if (fs.statSync(filePath).isDirectory()) {
  38. const folder = zipFolder.folder(file);
  39. addFolderToZip(filePath, folder);
  40. } else {
  41. zipFolder.file(path.basename(filePath), fs.readFileSync(filePath));
  42. }
  43. });
  44. }
  45. addFolderToZip(skillsDir, rootFolder);
  46. // 生成 zip 文件
  47. const content = await zip.generateAsync({ type: 'nodebuffer' });
  48. fs.writeFileSync(outputPath, content);
  49. console.log(`Skills packaged successfully to: ${outputPath}`);
  50. }
  51. const getLocale = path => {
  52. let pathname = path || window.location.pathname;
  53. let locale = 'zh-CN';
  54. if (/en-US/.test(pathname)) {
  55. locale = 'en-US';
  56. }
  57. return locale;
  58. };
  59. exports.onCreateWebpackConfig = ({ stage, rules, loaders, plugins, actions }) => {
  60. const isSSR = stage.includes('html');
  61. const sassLoader = () => 'sass-loader';
  62. const miniCssExtract = (...args) => loaders.miniCssExtract(...args);
  63. const cssLoader = (options = {}) => ({
  64. loader: 'css-loader',
  65. options: {
  66. ...options,
  67. },
  68. });
  69. const semiOptions = { esbuild: true };
  70. const srcScssModuleUse = [];
  71. const srcScssUse = [];
  72. const srcCssUse = [];
  73. // for semi
  74. semiOptions.scssUse = [
  75. loaders.css({
  76. importLoaders: 3,
  77. }),
  78. loaders.postcss(),
  79. sassLoader(),
  80. ];
  81. semiOptions.cssUse = [loaders.css({ importLoaders: 1 }), loaders.postcss()];
  82. semiOptions.scssPaths = [resolve('packages/semi-foundation'), resolve('packages/semi-ui'), resolve('packages/semi-icons')],
  83. semiOptions.paths = [
  84. function check(path) {
  85. return (
  86. (/packages\/semi-foundation/i.test(path) ||
  87. /packages\/semi-ui/i.test(path) ||
  88. /packages\/semi-icons/i.test(path)) &&
  89. !(/packages\/semi-foundation\/node_modules/i.test(path) || /packages\/semi-ui\/node_modules/i.test(path))
  90. );
  91. },
  92. ];
  93. semiOptions.extract = isSSR
  94. ? {
  95. loader: { loader: MiniCssExtractPlugin.loader, options: {} },
  96. }
  97. : false;
  98. // for src
  99. srcScssModuleUse.push(
  100. cssLoader({
  101. importLoaders: 2,
  102. modules: {
  103. localIdentName: '[local]--[hash:base64:5]',
  104. },
  105. onlyLocals: isSSR,
  106. localsConvention: 'camelCase',
  107. }),
  108. loaders.postcss(),
  109. sassLoader()
  110. );
  111. srcScssUse.push(cssLoader({ importLoaders: 2 }), loaders.postcss(), sassLoader());
  112. srcCssUse.push(cssLoader({ importLoaders: 1 }), loaders.postcss());
  113. if (!isSSR) {
  114. [semiOptions.scssUse, semiOptions.cssUse, srcScssModuleUse, srcScssUse, srcCssUse].forEach(
  115. arr => {
  116. arr.unshift(miniCssExtract());
  117. }
  118. );
  119. }
  120. console.log(["node_modules", resolve("node_modules")]);
  121. actions.setWebpackConfig({
  122. externals: {
  123. "node:url": "url",
  124. "node:path": "path",
  125. "node:process": "process",
  126. },
  127. resolve: {
  128. alias: {
  129. "vfile/do-not-use-conditional-minurl": isSSR ? "vfile/lib/minurl.js" : "vfile/lib/minurl.browser.js",
  130. "vfile/do-not-use-conditional-minproc": isSSR ? "vfile/lib/minproc.js" : "vfile/lib/minproc.browser.js",
  131. "vfile/do-not-use-conditional-minpath": isSSR ? "vfile/lib/minpath.js" : "vfile/lib/minpath.browser.js",
  132. "#minpath": isSSR ? "vfile/lib/minpath.js" : "vfile/lib/minpath.browser.js",
  133. "#minproc": isSSR ? "vfile/lib/minproc.js" : "vfile/lib/minproc.browser.js",
  134. "#minurl": isSSR ? "vfile/lib/minurl.js" : "vfile/lib/minurl.browser.js",
  135. "estree-util-visit/do-not-use-color": isSSR ? "estree-util-visit/lib/color.node.js" : "estree-util-visit/lib/color.default.js",
  136. "devlop": "devlop/lib/default.js",
  137. "unist-util-visit-parents/do-not-use-color": isSSR ? "unist-util-visit-parents/lib/color.node.js" : "unist-util-visit-parents/lib/color.js",
  138. 'semi-site-header': process.env.SEMI_SITE_HEADER || '@douyinfe/semi-site-header',
  139. 'semi-site-banner': process.env.SEMI_SITE_BANNER || '@douyinfe/semi-site-banner',
  140. 'univers-webview': process.env.SEMI_SITE_UNIVERS_WEBVIEW || resolve('packages/semi-ui'),
  141. '@douyinfe/semi-json-viewer-core': resolve('packages/semi-json-viewer-core/src'),
  142. '@douyinfe/semi-ui': resolve('packages/semi-ui'),
  143. '@douyinfe/semi-foundation': resolve('packages/semi-foundation'),
  144. '@douyinfe/semi-icons': resolve('packages/semi-icons/src/'),
  145. '@douyinfe/semi-icons-lab': resolve('packages/semi-icons-lab/src/'),
  146. '@douyinfe/semi-theme-default': resolve('packages/semi-theme-default'),
  147. '@douyinfe/semi-illustrations': resolve('packages/semi-illustrations/src/'),
  148. '@douyinfe/semi-animation-react': resolve('packages/semi-animation-react/'),
  149. '@douyinfe/semi-animation-styled': resolve('packages/semi-animation-styled/'),
  150. 'services': resolve('src/services'),
  151. 'utils': resolve('src/utils'),
  152. 'context': resolve('src/context'),
  153. 'components': resolve('src/components'),
  154. 'locale': resolve('src/locale'),
  155. 'src': resolve('src')
  156. },
  157. extensions: ["*", ".mjs", ".js", ".json"]
  158. },
  159. module: {
  160. rules: [
  161. {
  162. include: [path.resolve(__dirname, 'src')],
  163. oneOf: [
  164. {
  165. test: /\.module\.s(a|c)ss$/,
  166. use: [...srcScssModuleUse],
  167. },
  168. {
  169. test: /\.s(a|c)ss$/,
  170. use: [...srcScssUse],
  171. },
  172. {
  173. test: /\.css$/,
  174. use: [...srcCssUse],
  175. },
  176. ],
  177. },
  178. {
  179. test: /\.s(a|c)ss$/,
  180. include: [resolve('packages/semi-ui'), resolve('packages/semi-foundation'), resolve('packages/semi-icons')],
  181. use: [...srcScssUse, resolve('packages/semi-webpack/lib/semi-theme-loader.js')],
  182. },
  183. {
  184. test: /\.m?js/,
  185. include: [/micromark-util-sanitize-uri/, /mdast-util-from-markdown/, /micromark/, /mdast-util-to-markdown/, /semi-foundation\/node_modules\/@mdx-js/, /jsonc-parser/],
  186. use: ["esbuild-loader"]
  187. },
  188. {
  189. test: [/\.jsx?$/, /\.mjs/],
  190. include: [path.resolve(__dirname, 'src')],
  191. use: {
  192. loader: 'esbuild-loader',
  193. options: {
  194. loader: 'jsx', // Remove this if you're not using JSX
  195. target: 'esnext' // Syntax to compile to (see options below for possible values)
  196. },
  197. },
  198. },
  199. {
  200. test: /jsonWorkerManager\.ts$/,
  201. use: [{
  202. loader: 'webpack-replace-loader',
  203. options: {
  204. search: '%WORKER_RAW%',
  205. replace: () => {
  206. const workFilePath = resolve('packages/semi-json-viewer-core/workerLib/worker.js');
  207. const result = fs.readFileSync(workFilePath, 'utf-8');
  208. const encodedResult = encodeURIComponent(result);
  209. return encodedResult;
  210. }
  211. }
  212. }],
  213. },
  214. {
  215. test: [/\.tsx?$/],
  216. include: [path.resolve(__dirname, 'src')],
  217. use: [{
  218. loader: 'esbuild-loader',
  219. options: {
  220. loader: 'tsx', // Remove this if you're not using JSX
  221. target: 'esnext' // Syntax to compile to (see options below for possible values)
  222. },
  223. }],
  224. },
  225. {
  226. test: /\.mjs$/,
  227. include: /node_modules/,
  228. type: "javascript/auto"
  229. },
  230. { test: /\.worker\.ts$/, use: ['worker-loader', 'ts-loader'] }
  231. ],
  232. },
  233. plugins: [plugins.extractText(), plugins.define({
  234. "SEMI_AI_HELP": JSON.stringify(process.env['SEMI_AI_HELP']),
  235. "THEME_SWITCHER_URL": JSON.stringify(process.env['THEME_SWITCHER_URL']),
  236. "MATERIAL_LIST_URL": JSON.stringify(process.env['MATERIAL_LIST_URL']),
  237. "SEMI_SEARCH_URL": JSON.stringify(process.env['SEMI_SEARCH_URL']),
  238. "DSM_URL": JSON.stringify(process.env['DSM_URL']),
  239. 'process.env.SEMI_SITE_HEADER': JSON.stringify(process.env.SEMI_SITE_HEADER),
  240. 'process.env.SEMI_SITE_BANNER': JSON.stringify(process.env.SEMI_SITE_BANNER),
  241. "process.env.SEMI_SITE_UNIVERS_WEBVIEW": JSON.stringify(process.env.SEMI_SITE_UNIVERS_WEBVIEW),
  242. 'process.env.D2C_URL': JSON.stringify(process.env.D2C_URL),
  243. "ASSET_PREFIX": JSON.stringify((process.env['CDN_OUTER_CN'] || process.env['CDN_INNER_CN']) ? `https://${(process.env['CDN_OUTER_CN'] || process.env['CDN_INNER_CN'])}/${process.env['CDN_PATH_PREFIX']}` : ""),
  244. })],
  245. });
  246. };
  247. exports.onCreateNode = ({ node, getNode, actions }) => {
  248. const { createNodeField } = actions;
  249. if (node.internal.type === 'Mdx') {
  250. const mdxNode = getNode(node.parent);
  251. const levels = mdxNode.relativePath.split(path.sep);
  252. const locale = getLocale(mdxNode.name);
  253. createNodeField({
  254. node,
  255. name: 'slug',
  256. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  257. });
  258. createNodeField({
  259. node,
  260. name: 'type',
  261. value: `${levels[0]}`,
  262. });
  263. createNodeField({
  264. node,
  265. name: 'typeOrder',
  266. value: items.indexOf(levels[0]),
  267. });
  268. createNodeField({
  269. node,
  270. name: 'locale',
  271. value: locale,
  272. });
  273. }
  274. };
  275. exports.onPreBootstrap = async ({ Joi }) => {
  276. // 首先打包 skills 目录
  277. await packageSkills();
  278. let orderFunc = require('./content/order');
  279. console.log('starting order mdx');
  280. orderFunc();
  281. };
  282. exports.createPages = async ({ actions, graphql, reporter }) => {
  283. const { createPage } = actions;
  284. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  285. const result = await graphql(`
  286. query {
  287. allMdx(
  288. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  289. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  290. ) {
  291. edges {
  292. previous {
  293. fields {
  294. slug
  295. }
  296. id
  297. frontmatter {
  298. title
  299. localeCode
  300. icon
  301. showNew
  302. }
  303. }
  304. node {
  305. fields {
  306. slug
  307. }
  308. id
  309. frontmatter {
  310. localeCode
  311. order
  312. icon
  313. showNew
  314. }
  315. }
  316. next {
  317. fields {
  318. slug
  319. }
  320. id
  321. frontmatter {
  322. title
  323. localeCode
  324. icon
  325. showNew
  326. }
  327. }
  328. }
  329. }
  330. }
  331. `);
  332. // Handle errors
  333. if (result.errors) {
  334. reporter.panicOnBuild('Error while running GraphQL query.');
  335. return;
  336. }
  337. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  338. createPage({
  339. path: node.fields.slug,
  340. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  341. component: blogPostTemplate,
  342. context: {
  343. slug: node.fields.slug,
  344. next,
  345. previous,
  346. // id: node.id,
  347. },
  348. });
  349. });
  350. };
  351. exports.onPostBuild = async () => {
  352. const publicPath = path.join(__dirname, 'public');
  353. const replacedNameSet = new Set();
  354. const pageDataFiles = glob.sync(`${publicPath}/page-data/**/*.json`);
  355. for (let file of pageDataFiles) {
  356. const newFilename = file.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=> {
  357. replacedNameSet.add(p1);
  358. return `${p1}${/^\d+$/.test(p1) ? numHash : `.${hash}`}.json`;
  359. });
  360. fs.renameSync(file, newFilename);
  361. }
  362. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  363. for (let file of htmlAndJSFiles) {
  364. const stats = fs.statSync(file);
  365. if (stats.isFile()) {
  366. if (file.includes("public/editor")) {
  367. continue;
  368. }
  369. let content = fs.readFileSync(file, 'utf8');
  370. let result = content.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=>{
  371. if (replacedNameSet.has(p1) && !/^\d+$/.test(p1)) {
  372. const newFileName = `${p1}.${hash}.json`;
  373. console.log(`Add hash to json in ${file} from ${p1}.json to ${newFileName} ..`);
  374. return newFileName;
  375. } else {
  376. return `${p1}.json`;
  377. }
  378. });
  379. result = result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  380. `designToken.json?v=${hash}`);
  381. fs.writeFileSync(file, result, 'utf8');
  382. }
  383. }
  384. console.log("Num json set ", Array.from(replacedNameSet));
  385. //only match nav json (only number)
  386. const jsonFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  387. for (let file of jsonFiles) {
  388. if (file.includes("public/editor")) {
  389. continue;
  390. }
  391. const stats = fs.statSync(file);
  392. if (stats.isFile()) {
  393. console.log("Notice: Add Hash to JSON File " + file);
  394. if (file.includes("public/editor")) {
  395. continue;
  396. }
  397. let result = fs.readFileSync(file, 'utf8');
  398. for (let name of replacedNameSet) {
  399. if (/^\d+$/.test(name)) {
  400. result = result.replaceAll(name, `${name}${numHash}`);
  401. }
  402. }
  403. result = result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  404. `designToken.json?v=${hash}`);
  405. fs.writeFileSync(file, result, 'utf8');
  406. }
  407. }
  408. (()=>{
  409. const jsFiles = glob.sync(`${publicPath}/*.js`);
  410. const mapFiles = glob.sync(`${publicPath}/*.map`);
  411. const replaceNames = {};
  412. for (let file of jsFiles) {
  413. const filename = path.basename(file);
  414. const fileNameWithoutExt = filename.split('.')[0];
  415. const originHash = fileNameWithoutExt.split('-').at(-1);
  416. if (originHash && originHash !== fileNameWithoutExt) {
  417. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  418. replaceNames[originHash] = `${originHash}${numHash}`;
  419. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js`));
  420. } else {
  421. let finalFileName = `${fileNameWithoutExt}${numHash}.js`;
  422. replaceNames[filename] = finalFileName;
  423. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  424. }
  425. }
  426. for (let file of mapFiles) {
  427. const filename = path.basename(file);
  428. const fileNameWithoutExt = filename.split('.')[0];
  429. const originHash = fileNameWithoutExt.split('-').at(-1);
  430. if (originHash && originHash !== fileNameWithoutExt) {
  431. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  432. replaceNames[originHash] = `${originHash}${numHash}`;
  433. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js.map`));
  434. } else {
  435. let finalFileName = `${fileNameWithoutExt}${numHash}.js.map`;
  436. replaceNames[filename] = finalFileName;
  437. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  438. }
  439. }
  440. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  441. for (let file of allFiles) {
  442. const stats = fs.statSync(file);
  443. if (stats.isFile()) {
  444. let result = fs.readFileSync(file, 'utf8');
  445. for (let [oldName, newName] of Object.entries(replaceNames)) {
  446. result = result.replaceAll(oldName, newName);
  447. }
  448. fs.writeFileSync(file, result, 'utf8');
  449. }
  450. }
  451. })();
  452. (()=>{
  453. const cssFiles = glob.sync(`${publicPath}/*.css`);
  454. const replaceNames = {};
  455. for (let file of cssFiles) {
  456. const { base: filename, name: fileNameWithoutExt } = path.parse(file);
  457. const originHash = fileNameWithoutExt.split('.').at(-1);
  458. if (originHash && originHash !== fileNameWithoutExt) {
  459. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  460. replaceNames[originHash] = `${originHash}${numHash}`;
  461. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.css`));
  462. } else {
  463. let finalFileName = `${fileNameWithoutExt}${numHash}.css`;
  464. replaceNames[filename] = finalFileName;
  465. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  466. }
  467. }
  468. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  469. for (let file of allFiles) {
  470. const stats = fs.statSync(file);
  471. if (stats.isFile()) {
  472. let result = fs.readFileSync(file, 'utf8');
  473. for (let [oldName, newName] of Object.entries(replaceNames)) {
  474. result = result.replaceAll(oldName, newName);
  475. }
  476. fs.writeFileSync(file, result, 'utf8');
  477. }
  478. }
  479. })();
  480. };