gatsby-node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 items = ['basic', 'chart'];
  11. const sha1 = require('sha1');
  12. const hash = sha1(`${new Date().getTime()}${Math.random()}`);
  13. const glob = require('glob');
  14. const addPageDataVersion = async file => {
  15. const stats = fs.statSync(file);
  16. if (stats.isFile()) {
  17. console.log(`Adding version to page-data.json app-data.json designToken.json in ${file}..`);
  18. let content = fs.readFileSync(file, 'utf8');
  19. const result = content.replace(
  20. /page-data.json(\?v=[a-f0-9]{32})?/g,
  21. `page-data.json?v=${hash}`
  22. ).replace(/app-data.json(\?v=[a-f0-9]{32})?/g,
  23. `app-data.json?v=${hash}`
  24. ).replace(/designToken.json(\?v=[a-f0-9]{32})?/g,
  25. `designToken.json?v=${hash}`);
  26. fs.writeFileSync(file, result, 'utf8');
  27. }
  28. };
  29. function resolve(dir) {
  30. return path.resolve(__dirname, dir);
  31. }
  32. const getLocale = path => {
  33. let pathname = path || window.location.pathname;
  34. let locale = 'zh-CN';
  35. if (/en-US/.test(pathname)) {
  36. locale = 'en-US';
  37. }
  38. return locale;
  39. };
  40. exports.onCreateWebpackConfig = ({ stage, rules, loaders, plugins, actions }) => {
  41. const isSSR = stage.includes('html');
  42. const sassLoader = () => 'sass-loader';
  43. const miniCssExtract = (...args) => loaders.miniCssExtract(...args);
  44. const cssLoader = (options = {}) => ({
  45. loader: 'css-loader',
  46. options: {
  47. ...options,
  48. },
  49. });
  50. const semiOptions = { esbuild: true };
  51. const srcScssModuleUse = [];
  52. const srcScssUse = [];
  53. const srcCssUse = [];
  54. const semiDvScssUse = [];
  55. const semiDvJsxRule = [];
  56. // for semi
  57. semiOptions.scssUse = [
  58. loaders.css({
  59. importLoaders: 3,
  60. }),
  61. loaders.postcss(),
  62. sassLoader(),
  63. ];
  64. semiOptions.cssUse = [loaders.css({ importLoaders: 1 }), loaders.postcss()];
  65. semiOptions.scssPaths = [resolve('packages/semi-foundation'), resolve('packages/semi-ui'), resolve('packages/semi-icons')],
  66. semiOptions.paths = [
  67. function check(path) {
  68. return (
  69. (/packages\/semi-foundation/i.test(path) ||
  70. /packages\/semi-ui/i.test(path) ||
  71. /packages\/semi-icons/i.test(path)) &&
  72. !(/packages\/semi-foundation\/node_modules/i.test(path) || /packages\/semi-ui\/node_modules/i.test(path))
  73. );
  74. },
  75. ];
  76. semiOptions.extract = isSSR
  77. ? {
  78. loader: { loader: MiniCssExtractPlugin.loader, options: {} },
  79. }
  80. : false;
  81. // for src
  82. srcScssModuleUse.push(
  83. cssLoader({
  84. importLoaders: 2,
  85. modules: {
  86. localIdentName: '[local]--[hash:base64:5]',
  87. },
  88. onlyLocals: isSSR,
  89. localsConvention: 'camelCase',
  90. }),
  91. loaders.postcss(),
  92. sassLoader()
  93. );
  94. srcScssUse.push(cssLoader({ importLoaders: 2 }), loaders.postcss(), sassLoader());
  95. srcCssUse.push(cssLoader({ importLoaders: 1 }), loaders.postcss());
  96. if (!isSSR) {
  97. [semiOptions.scssUse, semiOptions.cssUse, srcScssModuleUse, srcScssUse, srcCssUse, semiDvScssUse].forEach(
  98. arr => {
  99. arr.unshift(miniCssExtract());
  100. }
  101. );
  102. }
  103. actions.setWebpackConfig({
  104. resolve: {
  105. alias: {
  106. 'semi-site-header': process.env.SEMI_SITE_HEADER || '@douyinfe/semi-site-header',
  107. 'semi-site-banner': process.env.SEMI_SITE_BANNER || '@douyinfe/semi-site-banner',
  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. "THEME_SWITCHER_URL":JSON.stringify(process.env['THEME_SWITCHER_URL']),
  174. "SEMI_SEARCH_URL":JSON.stringify(process.env['SEMI_SEARCH_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. const result = await graphql(`
  218. query {
  219. allMdx(
  220. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  221. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  222. ) {
  223. edges {
  224. previous {
  225. fields {
  226. slug
  227. }
  228. id
  229. frontmatter {
  230. title
  231. localeCode
  232. icon
  233. }
  234. }
  235. node {
  236. fields {
  237. slug
  238. }
  239. id
  240. frontmatter {
  241. localeCode
  242. order
  243. icon
  244. }
  245. }
  246. next {
  247. fields {
  248. slug
  249. }
  250. id
  251. frontmatter {
  252. title
  253. localeCode
  254. icon
  255. }
  256. }
  257. }
  258. }
  259. }
  260. `);
  261. // Handle errors
  262. if (result.errors) {
  263. reporter.panicOnBuild('Error while running GraphQL query.');
  264. return;
  265. }
  266. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  267. createPage({
  268. path: node.fields.slug,
  269. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  270. component: blogPostTemplate,
  271. context: {
  272. slug: node.fields.slug,
  273. next,
  274. previous,
  275. // id: node.id,
  276. },
  277. });
  278. });
  279. };
  280. exports.onPostBootstrap = async () => {
  281. const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js');
  282. await addPageDataVersion(loader);
  283. };
  284. exports.onPostBuild = async () => {
  285. const publicPath = path.join(__dirname, 'public');
  286. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  287. for (let file of htmlAndJSFiles) {
  288. await addPageDataVersion(file);
  289. }
  290. };