gatsby-node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 processGraphQLData = require('./search/generator');
  11. const items = ['basic', 'chart'];
  12. const sha1 = require('sha1');
  13. const hash = sha1(`${new Date().getTime()}${Math.random()}`);
  14. const glob = require('glob');
  15. const addPageDataVersion = async file => {
  16. const stats = fs.statSync(file);
  17. if (stats.isFile()) {
  18. console.log(`Adding version to page-data.json app-data.json designToken.json in ${file}..`);
  19. let content = fs.readFileSync(file, 'utf8');
  20. const result = content.replace(
  21. /page-data.json(\?v=[a-f0-9]{32})?/g,
  22. `page-data.json?v=${hash}`
  23. ).replace(/app-data.json(\?v=[a-f0-9]{32})?/g,
  24. `app-data.json?v=${hash}`
  25. ).replace(/designToken.json(\?v=[a-f0-9]{32})?/g,
  26. `designToken.json?v=${hash}`);
  27. fs.writeFileSync(file, result, 'utf8');
  28. }
  29. };
  30. function resolve(dir) {
  31. return path.resolve(__dirname, dir);
  32. }
  33. const getLocale = path => {
  34. let pathname = path || window.location.pathname;
  35. let locale = 'zh-CN';
  36. if (/en-US/.test(pathname)) {
  37. locale = 'en-US';
  38. }
  39. return locale;
  40. };
  41. exports.onCreateWebpackConfig = ({ stage, rules, loaders, plugins, actions }) => {
  42. const isSSR = stage.includes('html');
  43. const sassLoader = () => 'sass-loader';
  44. const miniCssExtract = (...args) => loaders.miniCssExtract(...args);
  45. const cssLoader = (options = {}) => ({
  46. loader: 'css-loader',
  47. options: {
  48. ...options,
  49. },
  50. });
  51. const semiOptions = { esbuild: true };
  52. const srcScssModuleUse = [];
  53. const srcScssUse = [];
  54. const srcCssUse = [];
  55. const semiDvScssUse = [];
  56. const semiDvJsxRule = [];
  57. // for semi
  58. semiOptions.scssUse = [
  59. loaders.css({
  60. importLoaders: 3,
  61. }),
  62. loaders.postcss(),
  63. sassLoader(),
  64. ];
  65. semiOptions.cssUse = [loaders.css({ importLoaders: 1 }), loaders.postcss()];
  66. semiOptions.scssPaths = [resolve('packages/semi-foundation'), resolve('packages/semi-ui'), resolve('packages/semi-icons')],
  67. semiOptions.paths = [
  68. function check(path) {
  69. return (
  70. (/packages\/semi-foundation/i.test(path) ||
  71. /packages\/semi-ui/i.test(path) ||
  72. /packages\/semi-icons/i.test(path)) &&
  73. !(/packages\/semi-foundation\/node_modules/i.test(path) || /packages\/semi-ui\/node_modules/i.test(path))
  74. );
  75. },
  76. ];
  77. semiOptions.extract = isSSR
  78. ? {
  79. loader: { loader: MiniCssExtractPlugin.loader, options: {} },
  80. }
  81. : false;
  82. // for src
  83. srcScssModuleUse.push(
  84. cssLoader({
  85. importLoaders: 2,
  86. modules: {
  87. localIdentName: '[local]--[hash:base64:5]',
  88. },
  89. onlyLocals: isSSR,
  90. localsConvention: 'camelCase',
  91. }),
  92. loaders.postcss(),
  93. sassLoader()
  94. );
  95. srcScssUse.push(cssLoader({ importLoaders: 2 }), loaders.postcss(), sassLoader());
  96. srcCssUse.push(cssLoader({ importLoaders: 1 }), loaders.postcss());
  97. if (!isSSR) {
  98. [semiOptions.scssUse, semiOptions.cssUse, srcScssModuleUse, srcScssUse, srcCssUse, semiDvScssUse].forEach(
  99. arr => {
  100. arr.unshift(miniCssExtract());
  101. }
  102. );
  103. }
  104. actions.setWebpackConfig({
  105. resolve: {
  106. alias: {
  107. '@douyinfe/semi-ui': resolve('packages/semi-ui'),
  108. '@douyinfe/semi-foundation': resolve('packages/semi-foundation'),
  109. '@douyinfe/semi-icons': resolve('packages/semi-icons/src/'),
  110. '@douyinfe/semi-theme-default': resolve('packages/semi-theme-default'),
  111. '@douyinfe/semi-illustrations': resolve('packages/semi-illustrations/src/'),
  112. '@douyinfe/semi-animation-react': resolve('packages/semi-animation-react/'),
  113. '@douyinfe/semi-animation-styled': resolve('packages/semi-animation-styled/'),
  114. 'services': resolve('src/services'),
  115. 'utils': resolve('src/utils'),
  116. 'context': resolve('src/context'),
  117. 'components': resolve('src/components'),
  118. 'locale': resolve('src/locale'),
  119. 'src':resolve('src')
  120. },
  121. },
  122. module: {
  123. rules: [
  124. ...semiDvJsxRule,
  125. {
  126. include: [path.resolve(__dirname, 'src')],
  127. oneOf: [
  128. {
  129. test: /\.module\.s(a|c)ss$/,
  130. use: [...srcScssModuleUse],
  131. },
  132. {
  133. test: /\.s(a|c)ss$/,
  134. use: [...srcScssUse],
  135. },
  136. {
  137. test: /\.css$/,
  138. use: [...srcCssUse],
  139. },
  140. ],
  141. },
  142. {
  143. test: /\.s(a|c)ss$/,
  144. include: [resolve('packages/semi-ui'), resolve('packages/semi-foundation'), resolve('packages/semi-icons')],
  145. use: [...srcScssUse, resolve('packages/semi-webpack/lib/semi-theme-loader.js')],
  146. },
  147. {
  148. test: [/\.jsx?$/],
  149. include: [path.resolve(__dirname, 'src')],
  150. use: {
  151. loader: 'esbuild-loader',
  152. options: {
  153. loader: 'jsx', // Remove this if you're not using JSX
  154. target: 'esnext' // Syntax to compile to (see options below for possible values)
  155. },
  156. },
  157. },
  158. {
  159. test: [/\.tsx?$/],
  160. include: [path.resolve(__dirname, 'src')],
  161. use: {
  162. loader: 'esbuild-loader',
  163. options: {
  164. loader: 'tsx', // Remove this if you're not using JSX
  165. target: 'esnext' // Syntax to compile to (see options below for possible values)
  166. },
  167. },
  168. }
  169. ],
  170. },
  171. plugins: [plugins.extractText()],
  172. });
  173. };
  174. exports.onCreateNode = ({ node, getNode, actions }) => {
  175. const { createNodeField } = actions;
  176. if (node.internal.type === 'Mdx') {
  177. const mdxNode = getNode(node.parent);
  178. const levels = mdxNode.relativePath.split(path.sep);
  179. const locale = getLocale(mdxNode.name);
  180. createNodeField({
  181. node,
  182. name: 'slug',
  183. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  184. });
  185. createNodeField({
  186. node,
  187. name: 'type',
  188. value: `${levels[0]}`,
  189. });
  190. createNodeField({
  191. node,
  192. name: 'typeOrder',
  193. value: items.indexOf(levels[0]),
  194. });
  195. createNodeField({
  196. node,
  197. name: 'locale',
  198. value: locale,
  199. });
  200. }
  201. };
  202. exports.onPreBootstrap = ({ Joi }) => {
  203. let orderFunc = require('./content/order');
  204. console.log('starting order mdx');
  205. orderFunc();
  206. };
  207. exports.createPages = async ({ actions, graphql, reporter }) => {
  208. const { createPage } = actions;
  209. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  210. // 开始处理搜索数据
  211. // console.log('building search data.');
  212. const searchData = await graphql(`
  213. query MyQuery {
  214. allMdx {
  215. nodes {
  216. id
  217. fields {
  218. slug
  219. type
  220. typeOrder
  221. }
  222. frontmatter {
  223. brief
  224. localeCode
  225. title
  226. }
  227. tableOfContents
  228. mdxAST
  229. }
  230. }
  231. }`);
  232. // 在此你可以处理searchData(GraphQL查询的raw数据) 或者传入回调 处理运算后的数据
  233. processGraphQLData(searchData, processedData => {});
  234. fs.copyFileSync('./search/data_client.json', './static/search_data_client.json');
  235. // console.log('building search data success.')
  236. // 搜索数据处理结束
  237. const result = await graphql(`
  238. query {
  239. allMdx(
  240. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  241. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  242. ) {
  243. edges {
  244. previous {
  245. fields {
  246. slug
  247. }
  248. id
  249. frontmatter {
  250. title
  251. localeCode
  252. icon
  253. }
  254. }
  255. node {
  256. fields {
  257. slug
  258. }
  259. id
  260. frontmatter {
  261. localeCode
  262. order
  263. icon
  264. }
  265. }
  266. next {
  267. fields {
  268. slug
  269. }
  270. id
  271. frontmatter {
  272. title
  273. localeCode
  274. icon
  275. }
  276. }
  277. }
  278. }
  279. }
  280. `);
  281. // Handle errors
  282. if (result.errors) {
  283. reporter.panicOnBuild('Error while running GraphQL query.');
  284. return;
  285. }
  286. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  287. createPage({
  288. path: node.fields.slug,
  289. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  290. component: blogPostTemplate,
  291. context: {
  292. slug: node.fields.slug,
  293. next,
  294. previous,
  295. // id: node.id,
  296. },
  297. });
  298. });
  299. };
  300. exports.onPostBootstrap = async () => {
  301. const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js');
  302. await addPageDataVersion(loader);
  303. };
  304. exports.onPostBuild = async () => {
  305. const publicPath = path.join(__dirname, 'public');
  306. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  307. for (let file of htmlAndJSFiles) {
  308. await addPageDataVersion(file);
  309. }
  310. };