gatsby-node.js 18 KB

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