gatsby-node.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. 'process.env.D2C_URL': JSON.stringify(process.env.D2C_URL),
  179. })],
  180. });
  181. };
  182. exports.onCreateNode = ({ node, getNode, actions }) => {
  183. const { createNodeField } = actions;
  184. if (node.internal.type === 'Mdx') {
  185. const mdxNode = getNode(node.parent);
  186. const levels = mdxNode.relativePath.split(path.sep);
  187. const locale = getLocale(mdxNode.name);
  188. createNodeField({
  189. node,
  190. name: 'slug',
  191. value: `${locale}/${levels[0]}/${levels[1]}`, // eg: zh-CN/chart/area
  192. });
  193. createNodeField({
  194. node,
  195. name: 'type',
  196. value: `${levels[0]}`,
  197. });
  198. createNodeField({
  199. node,
  200. name: 'typeOrder',
  201. value: items.indexOf(levels[0]),
  202. });
  203. createNodeField({
  204. node,
  205. name: 'locale',
  206. value: locale,
  207. });
  208. }
  209. };
  210. exports.onPreBootstrap = ({ Joi }) => {
  211. let orderFunc = require('./content/order');
  212. console.log('starting order mdx');
  213. orderFunc();
  214. };
  215. exports.createPages = async ({ actions, graphql, reporter }) => {
  216. const { createPage } = actions;
  217. const blogPostTemplate = path.resolve('src/templates/postTemplate.js');
  218. const result = await graphql(`
  219. query {
  220. allMdx(
  221. filter: { fields: { type: { nin: ["principles", "concepts"] } } }
  222. sort: { order: ASC, fields: [frontmatter___order, fields___locale, fields___typeOrder, fields___slug] }
  223. ) {
  224. edges {
  225. previous {
  226. fields {
  227. slug
  228. }
  229. id
  230. frontmatter {
  231. title
  232. localeCode
  233. icon
  234. }
  235. }
  236. node {
  237. fields {
  238. slug
  239. }
  240. id
  241. frontmatter {
  242. localeCode
  243. order
  244. icon
  245. }
  246. }
  247. next {
  248. fields {
  249. slug
  250. }
  251. id
  252. frontmatter {
  253. title
  254. localeCode
  255. icon
  256. }
  257. }
  258. }
  259. }
  260. }
  261. `);
  262. // Handle errors
  263. if (result.errors) {
  264. reporter.panicOnBuild('Error while running GraphQL query.');
  265. return;
  266. }
  267. result.data.allMdx.edges.forEach(({ next, previous, node }) => {
  268. createPage({
  269. path: node.fields.slug,
  270. // path: node.frontmatter.localeCode ? node.frontmatter.localeCode + '/' + node.fields.slug : 'zh-CN/' + node.fields.slug,
  271. component: blogPostTemplate,
  272. context: {
  273. slug: node.fields.slug,
  274. next,
  275. previous,
  276. // id: node.id,
  277. },
  278. });
  279. });
  280. };
  281. exports.onPostBootstrap = async () => {
  282. const loader = path.join(__dirname, 'node_modules/gatsby/cache-dir/loader.js');
  283. await addPageDataVersion(loader);
  284. };
  285. exports.onPostBuild = async () => {
  286. const publicPath = path.join(__dirname, 'public');
  287. const htmlAndJSFiles = glob.sync(`${publicPath}/**/*.{html,js}`);
  288. for (let file of htmlAndJSFiles) {
  289. await addPageDataVersion(file);
  290. }
  291. };