gatsby-node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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(),plugins.define({
  172. 'process.env.HEADER_CONFIG_HOST':JSON.stringify(process.env.HEADER_CONFIG_HOST)
  173. })],
  174. });
  175. };
  176. exports.onCreateNode = ({ node, getNode, actions }) => {
  177. const { createNodeField } = actions;
  178. if (node.internal.type === 'Mdx') {
  179. const mdxNode = getNode(node.parent);
  180. const levels = mdxNode.relativePath.split(path.sep);
  181. const locale = getLocale(mdxNode.name);
  182. createNodeField({
  183. node,
  184. name: 'slug',
  185. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  186. });
  187. createNodeField({
  188. node,
  189. name: 'type',
  190. value: `${levels[0]}`,
  191. });
  192. createNodeField({
  193. node,
  194. name: 'typeOrder',
  195. value: items.indexOf(levels[0]),
  196. });
  197. createNodeField({
  198. node,
  199. name: 'locale',
  200. value: locale,
  201. });
  202. }
  203. };
  204. exports.onPreBootstrap = ({ Joi }) => {
  205. let orderFunc = require('./content/order');
  206. console.log('starting order mdx');
  207. orderFunc();
  208. };
  209. exports.createPages = async ({ actions, graphql, reporter }) => {
  210. const { createPage } = actions;
  211. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  212. // 开始处理搜索数据
  213. // console.log('building search data.');
  214. const searchData = await graphql(`
  215. query MyQuery {
  216. allMdx {
  217. nodes {
  218. id
  219. fields {
  220. slug
  221. type
  222. typeOrder
  223. }
  224. frontmatter {
  225. brief
  226. localeCode
  227. title
  228. }
  229. tableOfContents
  230. mdxAST
  231. }
  232. }
  233. }`);
  234. // 在此你可以处理searchData(GraphQL查询的raw数据) 或者传入回调 处理运算后的数据
  235. processGraphQLData(searchData, processedData => {});
  236. // 搜索有用到,但是目前没有搜索,先注释掉,不然影响文档站的本地调试
  237. // fs.copyFileSync('./search/data_client.json', './static/search_data_client.json');
  238. // console.log('building search data success.')
  239. // 搜索数据处理结束
  240. const result = await graphql(`
  241. query {
  242. allMdx(
  243. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  244. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  245. ) {
  246. edges {
  247. previous {
  248. fields {
  249. slug
  250. }
  251. id
  252. frontmatter {
  253. title
  254. localeCode
  255. icon
  256. }
  257. }
  258. node {
  259. fields {
  260. slug
  261. }
  262. id
  263. frontmatter {
  264. localeCode
  265. order
  266. icon
  267. }
  268. }
  269. next {
  270. fields {
  271. slug
  272. }
  273. id
  274. frontmatter {
  275. title
  276. localeCode
  277. icon
  278. }
  279. }
  280. }
  281. }
  282. }
  283. `);
  284. // Handle errors
  285. if (result.errors) {
  286. reporter.panicOnBuild('Error while running GraphQL query.');
  287. return;
  288. }
  289. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  290. createPage({
  291. path: node.fields.slug,
  292. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  293. component: blogPostTemplate,
  294. context: {
  295. slug: node.fields.slug,
  296. next,
  297. previous,
  298. // id: node.id,
  299. },
  300. });
  301. });
  302. };
  303. exports.onPostBootstrap = async () => {
  304. const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js');
  305. await addPageDataVersion(loader);
  306. };
  307. exports.onPostBuild = async () => {
  308. const publicPath = path.join(__dirname, 'public');
  309. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  310. for (let file of htmlAndJSFiles) {
  311. await addPageDataVersion(file);
  312. }
  313. };