gatsby-node.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. }
  249. }
  250. node {
  251. fields {
  252. slug
  253. }
  254. id
  255. frontmatter {
  256. localeCode
  257. order
  258. icon
  259. }
  260. }
  261. next {
  262. fields {
  263. slug
  264. }
  265. id
  266. frontmatter {
  267. title
  268. localeCode
  269. icon
  270. }
  271. }
  272. }
  273. }
  274. }
  275. `);
  276. // Handle errors
  277. if (result.errors) {
  278. reporter.panicOnBuild('Error while running GraphQL query.');
  279. return;
  280. }
  281. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  282. createPage({
  283. path: node.fields.slug,
  284. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  285. component: blogPostTemplate,
  286. context: {
  287. slug: node.fields.slug,
  288. next,
  289. previous,
  290. // id: node.id,
  291. },
  292. });
  293. });
  294. };
  295. exports.onPostBuild = async () => {
  296. const publicPath = path.join(__dirname, 'public');
  297. const replacedNameSet = new Set();
  298. const pageDataFiles = glob.sync(`${publicPath}/page-data/**/*.json`);
  299. for (let file of pageDataFiles) {
  300. const newFilename = file.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=> {
  301. replacedNameSet.add(p1);
  302. return `${p1}${/^\d+$/.test(p1)?numHash:`.${hash}`}.json`;
  303. });
  304. fs.renameSync(file, newFilename);
  305. }
  306. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  307. for (let file of htmlAndJSFiles) {
  308. const stats = fs.statSync(file);
  309. if (stats.isFile()) {
  310. if (file.includes("public/editor")) {
  311. continue;
  312. }
  313. let content = fs.readFileSync(file, 'utf8');
  314. let result = content.replace(/([a-zA-Z0-9\-]+)\.json/g, (_, p1)=>{
  315. if (replacedNameSet.has(p1) && !/^\d+$/.test(p1)) {
  316. const newFileName = `${p1}.${hash}.json`;
  317. console.log(`Add hash to json in ${file} from ${p1}.json to ${newFileName} ..`);
  318. return newFileName;
  319. } else {
  320. return `${p1}.json`;
  321. }
  322. });
  323. result=result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  324. `designToken.json?v=${hash}`);
  325. fs.writeFileSync(file, result, 'utf8');
  326. }
  327. }
  328. console.log("Num json set ", Array.from(replacedNameSet));
  329. //only match nav json (only number)
  330. const jsonFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  331. for (let file of jsonFiles) {
  332. if (file.includes("public/editor")) {
  333. continue;
  334. }
  335. const stats = fs.statSync(file);
  336. if (stats.isFile()) {
  337. console.log("Notice: Add Hash to JSON File "+ file);
  338. if (file.includes("public/editor")) {
  339. continue;
  340. }
  341. let result = fs.readFileSync(file, 'utf8');
  342. for (let name of replacedNameSet) {
  343. if (/^\d+$/.test(name)) {
  344. result = result.replaceAll(name, `${name}${numHash}`);
  345. }
  346. }
  347. result=result.replace(/designToken.json(\?v=[a-f0-9]*)?/g,
  348. `designToken.json?v=${hash}`);
  349. fs.writeFileSync(file, result, 'utf8');
  350. }
  351. }
  352. (()=>{
  353. const jsFiles = glob.sync(`${publicPath}/*.js`);
  354. const mapFiles = glob.sync(`${publicPath}/*.map`);
  355. const replaceNames = {};
  356. for (let file of jsFiles) {
  357. const filename = path.basename(file);
  358. const fileNameWithoutExt = filename.split('.')[0];
  359. const originHash = fileNameWithoutExt.split('-').at(-1);
  360. if (originHash && originHash!==fileNameWithoutExt) {
  361. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  362. replaceNames[originHash] = `${originHash}${numHash}`;
  363. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js`));
  364. } else {
  365. let finalFileName = `${fileNameWithoutExt}${numHash}.js`;
  366. replaceNames[filename] = finalFileName;
  367. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  368. }
  369. }
  370. for (let file of mapFiles) {
  371. const filename = path.basename(file);
  372. const fileNameWithoutExt = filename.split('.')[0];
  373. const originHash = fileNameWithoutExt.split('-').at(-1);
  374. if (originHash && originHash!==fileNameWithoutExt) {
  375. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  376. replaceNames[originHash] = `${originHash}${numHash}`;
  377. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.js.map`));
  378. } else {
  379. let finalFileName = `${fileNameWithoutExt}${numHash}.js.map`;
  380. replaceNames[filename] = finalFileName;
  381. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  382. }
  383. }
  384. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  385. for (let file of allFiles) {
  386. const stats = fs.statSync(file);
  387. if (stats.isFile()) {
  388. let result = fs.readFileSync(file, 'utf8');
  389. for (let [oldName, newName] of Object.entries(replaceNames)) {
  390. result = result.replaceAll(oldName, newName);
  391. }
  392. fs.writeFileSync(file, result, 'utf8');
  393. }
  394. }
  395. })();
  396. (()=>{
  397. const cssFiles = glob.sync(`${publicPath}/*.css`);
  398. const replaceNames = {};
  399. for (let file of cssFiles) {
  400. const { base: filename, name: fileNameWithoutExt } = path.parse(file);
  401. const originHash = fileNameWithoutExt.split('.').at(-1);
  402. if (originHash && originHash!==fileNameWithoutExt) {
  403. let fileNameWithoutExtWithHash = fileNameWithoutExt.replace(originHash, `${originHash}${numHash}`);
  404. replaceNames[originHash] = `${originHash}${numHash}`;
  405. fs.renameSync(file, path.join(path.dirname(file), `${fileNameWithoutExtWithHash}.css`));
  406. } else {
  407. let finalFileName = `${fileNameWithoutExt}${numHash}.css`;
  408. replaceNames[filename] = finalFileName;
  409. fs.renameSync(file, path.join(path.dirname(file), finalFileName));
  410. }
  411. }
  412. const allFiles = glob.sync(`${publicPath}/**/*.{js,html,json}`);
  413. for (let file of allFiles) {
  414. const stats = fs.statSync(file);
  415. if (stats.isFile()) {
  416. let result = fs.readFileSync(file, 'utf8');
  417. for (let [oldName, newName] of Object.entries(replaceNames)) {
  418. result = result.replaceAll(oldName, newName);
  419. }
  420. fs.writeFileSync(file, result, 'utf8');
  421. }
  422. }
  423. })();
  424. };