gatsby-node.js 19 KB

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