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. 'semi-site-header': process.env.SEMI_SITE_HEADER || '@douyinfe/semi-site-header',
  108. '@douyinfe/semi-ui': resolve('packages/semi-ui'),
  109. '@douyinfe/semi-foundation': resolve('packages/semi-foundation'),
  110. '@douyinfe/semi-icons': resolve('packages/semi-icons/src/'),
  111. '@douyinfe/semi-theme-default': resolve('packages/semi-theme-default'),
  112. '@douyinfe/semi-illustrations': resolve('packages/semi-illustrations/src/'),
  113. '@douyinfe/semi-animation-react': resolve('packages/semi-animation-react/'),
  114. '@douyinfe/semi-animation-styled': resolve('packages/semi-animation-styled/'),
  115. 'services': resolve('src/services'),
  116. 'utils': resolve('src/utils'),
  117. 'context': resolve('src/context'),
  118. 'components': resolve('src/components'),
  119. 'locale': resolve('src/locale'),
  120. 'src':resolve('src')
  121. },
  122. },
  123. module: {
  124. rules: [
  125. ...semiDvJsxRule,
  126. {
  127. include: [path.resolve(__dirname, 'src')],
  128. oneOf: [
  129. {
  130. test: /\.module\.s(a|c)ss$/,
  131. use: [...srcScssModuleUse],
  132. },
  133. {
  134. test: /\.s(a|c)ss$/,
  135. use: [...srcScssUse],
  136. },
  137. {
  138. test: /\.css$/,
  139. use: [...srcCssUse],
  140. },
  141. ],
  142. },
  143. {
  144. test: /\.s(a|c)ss$/,
  145. include: [resolve('packages/semi-ui'), resolve('packages/semi-foundation'), resolve('packages/semi-icons')],
  146. use: [...srcScssUse, resolve('packages/semi-webpack/lib/semi-theme-loader.js')],
  147. },
  148. {
  149. test: [/\.jsx?$/],
  150. include: [path.resolve(__dirname, 'src')],
  151. use: {
  152. loader: 'esbuild-loader',
  153. options: {
  154. loader: 'jsx', // Remove this if you're not using JSX
  155. target: 'esnext' // Syntax to compile to (see options below for possible values)
  156. },
  157. },
  158. },
  159. {
  160. test: [/\.tsx?$/],
  161. include: [path.resolve(__dirname, 'src')],
  162. use: {
  163. loader: 'esbuild-loader',
  164. options: {
  165. loader: 'tsx', // Remove this if you're not using JSX
  166. target: 'esnext' // Syntax to compile to (see options below for possible values)
  167. },
  168. },
  169. }
  170. ],
  171. },
  172. plugins: [plugins.extractText()],
  173. });
  174. };
  175. exports.onCreateNode = ({ node, getNode, actions }) => {
  176. const { createNodeField } = actions;
  177. if (node.internal.type === 'Mdx') {
  178. const mdxNode = getNode(node.parent);
  179. const levels = mdxNode.relativePath.split(path.sep);
  180. const locale = getLocale(mdxNode.name);
  181. createNodeField({
  182. node,
  183. name: 'slug',
  184. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  185. });
  186. createNodeField({
  187. node,
  188. name: 'type',
  189. value: `${levels[0]}`,
  190. });
  191. createNodeField({
  192. node,
  193. name: 'typeOrder',
  194. value: items.indexOf(levels[0]),
  195. });
  196. createNodeField({
  197. node,
  198. name: 'locale',
  199. value: locale,
  200. });
  201. }
  202. };
  203. exports.onPreBootstrap = ({ Joi }) => {
  204. let orderFunc = require('./content/order');
  205. console.log('starting order mdx');
  206. orderFunc();
  207. };
  208. exports.createPages = async ({ actions, graphql, reporter }) => {
  209. const { createPage } = actions;
  210. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  211. // 开始处理搜索数据
  212. // console.log('building search data.');
  213. const searchData = await graphql(`
  214. query MyQuery {
  215. allMdx {
  216. nodes {
  217. id
  218. fields {
  219. slug
  220. type
  221. typeOrder
  222. }
  223. frontmatter {
  224. brief
  225. localeCode
  226. title
  227. }
  228. tableOfContents
  229. mdxAST
  230. }
  231. }
  232. }`);
  233. // 在此你可以处理searchData(GraphQL查询的raw数据) 或者传入回调 处理运算后的数据
  234. processGraphQLData(searchData, processedData => {});
  235. // 搜索有用到,但是目前没有搜索,先注释掉,不然影响文档站的本地调试
  236. // fs.copyFileSync('./search/data_client.json', './static/search_data_client.json');
  237. // console.log('building search data success.')
  238. // 搜索数据处理结束
  239. const result = await graphql(`
  240. query {
  241. allMdx(
  242. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  243. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  244. ) {
  245. edges {
  246. previous {
  247. fields {
  248. slug
  249. }
  250. id
  251. frontmatter {
  252. title
  253. localeCode
  254. icon
  255. }
  256. }
  257. node {
  258. fields {
  259. slug
  260. }
  261. id
  262. frontmatter {
  263. localeCode
  264. order
  265. icon
  266. }
  267. }
  268. next {
  269. fields {
  270. slug
  271. }
  272. id
  273. frontmatter {
  274. title
  275. localeCode
  276. icon
  277. }
  278. }
  279. }
  280. }
  281. }
  282. `);
  283. // Handle errors
  284. if (result.errors) {
  285. reporter.panicOnBuild('Error while running GraphQL query.');
  286. return;
  287. }
  288. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  289. createPage({
  290. path: node.fields.slug,
  291. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  292. component: blogPostTemplate,
  293. context: {
  294. slug: node.fields.slug,
  295. next,
  296. previous,
  297. // id: node.id,
  298. },
  299. });
  300. });
  301. };
  302. exports.onPostBootstrap = async () => {
  303. const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js');
  304. await addPageDataVersion(loader);
  305. };
  306. exports.onPostBuild = async () => {
  307. const publicPath = path.join(__dirname, 'public');
  308. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  309. for (let file of htmlAndJSFiles) {
  310. await addPageDataVersion(file);
  311. }
  312. };