gatsby-node.js 11 KB

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