webpack-util.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. const fs = require('fs');
  2. const babelCore = require('@babel/core');
  3. const WrapperWebpackPlugin = require('wrapper-webpack-plugin');
  4. // {entryName: path}
  5. const entryGlobals = {
  6. 'common': ['common'],
  7. 'injected/content': ['injected', 'injected/content'],
  8. 'injected/web': ['injected', 'injected/web'],
  9. };
  10. /**
  11. * Adds a watcher for files in entryGlobals to properly recompile the project on changes.
  12. */
  13. function addWrapperWithGlobals(name, config, defsObj, callback) {
  14. config.module.rules.push({
  15. test: new RegExp(`/${name}/.*?\\.js$`.replace(/\//g, /[/\\]/.source)),
  16. use: [{
  17. loader: './scripts/fake-dep-loader.js',
  18. options: { files: entryGlobals[name] },
  19. }],
  20. });
  21. const defsRe = new RegExp(`\\b(${
  22. Object.keys(defsObj)
  23. .join('|')
  24. .replace(/\./g, '\\.')
  25. })\\b`, 'g');
  26. const reader = () => (
  27. entryGlobals[name]
  28. .map(path => readGlobalsFile(path))
  29. .join('\n')
  30. .replace(defsRe, s => defsObj[s])
  31. );
  32. config.plugins.push(new WrapperWebpackPlugin(callback(reader)));
  33. }
  34. function getCodeMirrorThemes() {
  35. const name = 'neo.css';
  36. return fs.readdirSync(
  37. require.resolve(`codemirror/theme/${name}`).slice(0, -name.length),
  38. { withFileTypes: true },
  39. ).map(e => e.isFile() && e.name.endsWith('.css') && e.name.slice(0, -4))
  40. .filter(Boolean);
  41. }
  42. function getUniqIdB64() {
  43. return Buffer.from(
  44. new Uint32Array(2)
  45. .map(() => Math.random() * (2 ** 32))
  46. .buffer,
  47. ).toString('base64');
  48. }
  49. function readGlobalsFile(path, babelOpts = {}) {
  50. const { ast, code = !ast } = babelOpts;
  51. const filename = `./src/${path}/safe-globals.js`;
  52. const src = fs.readFileSync(filename, { encoding: 'utf8' })
  53. .replace(/\bexport\s+(function\s+(\w+))/g, 'const $2 = $1')
  54. .replace(/\bexport\s+(?=(const|let)\s)/g, '');
  55. const res = babelCore.transformSync(src, {
  56. ...babelOpts,
  57. ast,
  58. code,
  59. filename,
  60. });
  61. return ast ? res : res.code;
  62. }
  63. exports.addWrapperWithGlobals = addWrapperWithGlobals;
  64. exports.getCodeMirrorThemes = getCodeMirrorThemes;
  65. exports.getUniqIdB64 = getUniqIdB64;
  66. exports.readGlobalsFile = readGlobalsFile;