gatsby-node.js 15 KB

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