gatsby-node.js 15 KB

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