gatsby-node.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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-ui': resolve('packages/semi-ui'),
  109. '@douyinfe/semi-foundation': resolve('packages/semi-foundation'),
  110. '@douyinfe/semi-icons': resolve('packages/semi-icons/src/'),
  111. '@douyinfe/semi-icons-lab': resolve('packages/semi-icons-lab/src/'),
  112. '@douyinfe/semi-theme-default': resolve('packages/semi-theme-default'),
  113. '@douyinfe/semi-illustrations': resolve('packages/semi-illustrations/src/'),
  114. '@douyinfe/semi-animation-react': resolve('packages/semi-animation-react/'),
  115. '@douyinfe/semi-animation-styled': resolve('packages/semi-animation-styled/'),
  116. 'services': resolve('src/services'),
  117. 'utils': resolve('src/utils'),
  118. 'context': resolve('src/context'),
  119. 'components': resolve('src/components'),
  120. 'locale': resolve('src/locale'),
  121. 'src': resolve('src')
  122. },
  123. extensions: ["*", ".mjs", ".js", ".json"]
  124. },
  125. module: {
  126. rules: [
  127. {
  128. include: [path.resolve(__dirname, 'src')],
  129. oneOf: [
  130. {
  131. test: /\.module\.s(a|c)ss$/,
  132. use: [...srcScssModuleUse],
  133. },
  134. {
  135. test: /\.s(a|c)ss$/,
  136. use: [...srcScssUse],
  137. },
  138. {
  139. test: /\.css$/,
  140. use: [...srcCssUse],
  141. },
  142. ],
  143. },
  144. {
  145. test: /\.s(a|c)ss$/,
  146. include: [resolve('packages/semi-ui'), resolve('packages/semi-foundation'), resolve('packages/semi-icons')],
  147. use: [...srcScssUse, resolve('packages/semi-webpack/lib/semi-theme-loader.js')],
  148. },
  149. {
  150. test: /\.m?js/,
  151. include: [/micromark-util-sanitize-uri/, /mdast-util-from-markdown/, /micromark/, /mdast-util-to-markdown/, /semi-foundation\/node_modules\/@mdx-js/],
  152. use: ["esbuild-loader"]
  153. },
  154. {
  155. test: [/\.jsx?$/, /\.mjs/],
  156. include: [path.resolve(__dirname, 'src')],
  157. use: {
  158. loader: 'esbuild-loader',
  159. options: {
  160. loader: 'jsx', // Remove this if you're not using JSX
  161. target: 'esnext' // Syntax to compile to (see options below for possible values)
  162. },
  163. },
  164. },
  165. {
  166. test: [/\.tsx?$/],
  167. include: [path.resolve(__dirname, 'src')],
  168. use: {
  169. loader: 'esbuild-loader',
  170. options: {
  171. loader: 'tsx', // Remove this if you're not using JSX
  172. target: 'esnext' // Syntax to compile to (see options below for possible values)
  173. },
  174. },
  175. },
  176. {
  177. test: /\.mjs$/,
  178. include: /node_modules/,
  179. type: "javascript/auto"
  180. }
  181. ],
  182. },
  183. plugins: [plugins.extractText(), plugins.define({
  184. "THEME_SWITCHER_URL": JSON.stringify(process.env['THEME_SWITCHER_URL']),
  185. "MATERIAL_LIST_URL": JSON.stringify(process.env['MATERIAL_LIST_URL']),
  186. "SEMI_SEARCH_URL": JSON.stringify(process.env['SEMI_SEARCH_URL']),
  187. "DSM_URL": JSON.stringify(process.env['DSM_URL']),
  188. 'process.env.SEMI_SITE_HEADER': JSON.stringify(process.env.SEMI_SITE_HEADER),
  189. 'process.env.SEMI_SITE_BANNER': JSON.stringify(process.env.SEMI_SITE_BANNER),
  190. "process.env.SEMI_SITE_UNIVERS_WEBVIEW": JSON.stringify(process.env.SEMI_SITE_UNIVERS_WEBVIEW),
  191. 'process.env.D2C_URL': JSON.stringify(process.env.D2C_URL),
  192. "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']}` : ""),
  193. })],
  194. });
  195. };
  196. exports.onCreateNode = ({ node, getNode, actions }) => {
  197. const { createNodeField } = actions;
  198. if (node.internal.type === 'Mdx') {
  199. const mdxNode = getNode(node.parent);
  200. const levels = mdxNode.relativePath.split(path.sep);
  201. const locale = getLocale(mdxNode.name);
  202. createNodeField({
  203. node,
  204. name: 'slug',
  205. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  206. });
  207. createNodeField({
  208. node,
  209. name: 'type',
  210. value: `${levels[0]}`,
  211. });
  212. createNodeField({
  213. node,
  214. name: 'typeOrder',
  215. value: items.indexOf(levels[0]),
  216. });
  217. createNodeField({
  218. node,
  219. name: 'locale',
  220. value: locale,
  221. });
  222. }
  223. };
  224. exports.onPreBootstrap = ({ Joi }) => {
  225. let orderFunc = require('./content/order');
  226. console.log('starting order mdx');
  227. orderFunc();
  228. };
  229. exports.createPages = async ({ actions, graphql, reporter }) => {
  230. const { createPage } = actions;
  231. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  232. const result = await graphql(`
  233. query {
  234. allMdx(
  235. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  236. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  237. ) {
  238. edges {
  239. previous {
  240. fields {
  241. slug
  242. }
  243. id
  244. frontmatter {
  245. title
  246. localeCode
  247. icon
  248. showNew
  249. }
  250. }
  251. node {
  252. fields {
  253. slug
  254. }
  255. id
  256. frontmatter {
  257. localeCode
  258. order
  259. icon
  260. showNew
  261. }
  262. }
  263. next {
  264. fields {
  265. slug
  266. }
  267. id
  268. frontmatter {
  269. title
  270. localeCode
  271. icon
  272. showNew
  273. }
  274. }
  275. }
  276. }
  277. }
  278. `);
  279. // Handle errors
  280. if (result.errors) {
  281. reporter.panicOnBuild('Error while running GraphQL query.');
  282. return;
  283. }
  284. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  285. createPage({
  286. path: node.fields.slug,
  287. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  288. component: blogPostTemplate,
  289. context: {
  290. slug: node.fields.slug,
  291. next,
  292. previous,
  293. // id: node.id,
  294. },
  295. });
  296. });
  297. };
  298. exports.onPostBuild = async () => {
  299. const publicPath = path.join(__dirname, 'public');
  300. const replacedNameSet = new Set();
  301. const pageDataFiles = glob.sync(`${publicPath}/page-data/**/*.json`);
  302. for (let file of pageDataFiles) {
  303. const newFilename = file.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=> {
  304. replacedNameSet.add(p1);
  305. return `${p1}${/^\d+$/.test(p1) ? numHash : `.${hash}`}.json`;
  306. });
  307. fs.renameSync(file, newFilename);
  308. }
  309. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  310. for (let file of htmlAndJSFiles) {
  311. const stats = fs.statSync(file);
  312. if (stats.isFile()) {
  313. if (file.includes("public/editor")) {
  314. continue;
  315. }
  316. let content = fs.readFileSync(file, 'utf8');
  317. let result = content.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=>{
  318. if (replacedNameSet.has(p1) && !/^\d+$/.test(p1)) {
  319. const newFileName = `${p1}.${hash}.json`;
  320. console.log(`Add hash to json in ${file} from ${p1}.json to ${newFileName} ..`);
  321. return newFileName;
  322. } else {
  323. return `${p1}.json`;
  324. }
  325. });
  326. result = result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  327. `designToken.json?v=${hash}`);
  328. fs.writeFileSync(file, result, 'utf8');
  329. }
  330. }
  331. console.log("Num json set ", Array.from(replacedNameSet));
  332. //only match nav json (only number)
  333. const jsonFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  334. for (let file of jsonFiles) {
  335. if (file.includes("public/editor")) {
  336. continue;
  337. }
  338. const stats = fs.statSync(file);
  339. if (stats.isFile()) {
  340. console.log("Notice: Add Hash to JSON File " + file);
  341. if (file.includes("public/editor")) {
  342. continue;
  343. }
  344. let result = fs.readFileSync(file, 'utf8');
  345. for (let name of replacedNameSet) {
  346. if (/^\d+$/.test(name)) {
  347. result = result.replaceAll(name, `${name}${numHash}`);
  348. }
  349. }
  350. result = result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  351. `designToken.json?v=${hash}`);
  352. fs.writeFileSync(file, result, 'utf8');
  353. }
  354. }
  355. (()=>{
  356. const jsFiles = glob.sync(`${publicPath}/*.js`);
  357. const mapFiles = glob.sync(`${publicPath}/*.map`);
  358. const replaceNames = {};
  359. for (let file of jsFiles) {
  360. const filename = path.basename(file);
  361. const fileNameWithoutExt = filename.split('.')[0];
  362. const originHash = fileNameWithoutExt.split('-').at(-1);
  363. if (originHash && originHash !== fileNameWithoutExt) {
  364. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  365. replaceNames[originHash] = `${originHash}${numHash}`;
  366. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js`));
  367. } else {
  368. let finalFileName = `${fileNameWithoutExt}${numHash}.js`;
  369. replaceNames[filename] = finalFileName;
  370. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  371. }
  372. }
  373. for (let file of mapFiles) {
  374. const filename = path.basename(file);
  375. const fileNameWithoutExt = filename.split('.')[0];
  376. const originHash = fileNameWithoutExt.split('-').at(-1);
  377. if (originHash && originHash !== fileNameWithoutExt) {
  378. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  379. replaceNames[originHash] = `${originHash}${numHash}`;
  380. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js.map`));
  381. } else {
  382. let finalFileName = `${fileNameWithoutExt}${numHash}.js.map`;
  383. replaceNames[filename] = finalFileName;
  384. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  385. }
  386. }
  387. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  388. for (let file of allFiles) {
  389. const stats = fs.statSync(file);
  390. if (stats.isFile()) {
  391. let result = fs.readFileSync(file, 'utf8');
  392. for (let [oldName, newName] of Object.entries(replaceNames)) {
  393. result = result.replaceAll(oldName, newName);
  394. }
  395. fs.writeFileSync(file, result, 'utf8');
  396. }
  397. }
  398. })();
  399. (()=>{
  400. const cssFiles = glob.sync(`${publicPath}/*.css`);
  401. const replaceNames = {};
  402. for (let file of cssFiles) {
  403. const { base: filename, name: fileNameWithoutExt } = path.parse(file);
  404. const originHash = fileNameWithoutExt.split('.').at(-1);
  405. if (originHash && originHash !== fileNameWithoutExt) {
  406. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  407. replaceNames[originHash] = `${originHash}${numHash}`;
  408. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.css`));
  409. } else {
  410. let finalFileName = `${fileNameWithoutExt}${numHash}.css`;
  411. replaceNames[filename] = finalFileName;
  412. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  413. }
  414. }
  415. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  416. for (let file of allFiles) {
  417. const stats = fs.statSync(file);
  418. if (stats.isFile()) {
  419. let result = fs.readFileSync(file, 'utf8');
  420. for (let [oldName, newName] of Object.entries(replaceNames)) {
  421. result = result.replaceAll(oldName, newName);
  422. }
  423. fs.writeFileSync(file, result, 'utf8');
  424. }
  425. }
  426. })();
  427. };