gatsby-node.js 18 KB

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