gatsby-node.js 11 KB

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