webpack.conf.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. const { modifyWebpackConfig, shallowMerge, defaultOptions } = require('@gera2ld/plaid');
  2. const { isProd } = require('@gera2ld/plaid/util');
  3. const fs = require('fs');
  4. const webpack = require('webpack');
  5. const WrapperWebpackPlugin = require('wrapper-webpack-plugin');
  6. const HTMLInlineCSSWebpackPlugin = isProd && require('html-inline-css-webpack-plugin').default;
  7. const projectConfig = require('./plaid.conf');
  8. const mergedConfig = shallowMerge(defaultOptions, projectConfig);
  9. const INIT_FUNC_NAME = 'VMInitInjection';
  10. // Copied from gulpfile.js: strip alphabetic suffix
  11. const VM_VER = require('../package.json').version.replace(/-[^.]*/, '');
  12. const pickEnvs = (items) => {
  13. return Object.assign({}, ...items.map(x => ({
  14. [`process.env.${x.key}`]: JSON.stringify(
  15. 'val' in x ? x.val
  16. : process.env[x.key] ?? x.def
  17. ),
  18. })));
  19. };
  20. const definitions = new webpack.DefinePlugin({
  21. ...pickEnvs([
  22. { key: 'DEBUG', def: false },
  23. { key: 'VM_VER', val: VM_VER },
  24. { key: 'SYNC_GOOGLE_CLIENT_ID' },
  25. { key: 'SYNC_GOOGLE_CLIENT_SECRET' },
  26. { key: 'SYNC_ONEDRIVE_CLIENT_ID' },
  27. { key: 'SYNC_ONEDRIVE_CLIENT_SECRET' },
  28. ]),
  29. 'process.env.INIT_FUNC_NAME': JSON.stringify(INIT_FUNC_NAME),
  30. });
  31. // avoid running webpack bootstrap in a potentially hacked environment
  32. // after documentElement was replaced which triggered reinjection of content scripts
  33. const skipReinjectionHeader = `if (window['${INIT_FUNC_NAME}'] !== 1)`;
  34. // {entryName: path}
  35. const entryGlobals = {
  36. common: './src/common/safe-globals.js',
  37. injected: './src/injected/safe-injected-globals.js',
  38. };
  39. /**
  40. * Adds a watcher for files in entryGlobals to properly recompile the project on changes.
  41. */
  42. const addWrapper = (config, name, callback) => {
  43. if (!callback) { callback = name; name = ''; }
  44. const globals = Object.entries(entryGlobals).filter(([key]) => name === key || !name);
  45. const dirs = globals.map(([key]) => key).join('|');
  46. config.module.rules.push({
  47. test: new RegExp(`/(${dirs})/index\\.js$`.replace(/\//g, /[/\\]/.source)),
  48. use: [{
  49. loader: './scripts/fake-dep-loader.js',
  50. options: {
  51. files: globals.map(([, path]) => path),
  52. },
  53. }],
  54. });
  55. const reader = () => (
  56. globals.map(([, path]) => (
  57. fs.readFileSync(path, { encoding: 'utf8' })
  58. .replace(/export\s+(?=const\s)/g, '')
  59. ))
  60. ).join('\n');
  61. config.plugins.push(new WrapperWebpackPlugin(callback(reader)));
  62. };
  63. const modify = (page, entry, init) => modifyWebpackConfig(
  64. (config) => {
  65. config.node = {
  66. process: false,
  67. setImmediate: false,
  68. };
  69. config.plugins.push(definitions);
  70. if (!entry) init = page;
  71. if (init) init(config);
  72. return config;
  73. }, {
  74. projectConfig: {
  75. ...mergedConfig,
  76. ...entry && { pages: { [page]: { entry }} },
  77. },
  78. },
  79. );
  80. module.exports = Promise.all([
  81. modify((config) => {
  82. addWrapper(config, 'common', getGlobals => ({
  83. header: () => `{ ${getGlobals()}`,
  84. footer: '}',
  85. test: /^(?!injected|public).*\.js$/,
  86. }));
  87. /* Embedding as <style> to ensure uiTheme option doesn't cause FOUC.
  88. * Note that in production build there's no <head> in html but document.head is still
  89. * auto-created per the specification so our styles will be placed correctly anyway. */
  90. if (isProd) config.plugins.push(new HTMLInlineCSSWebpackPlugin({
  91. replace: {
  92. target: '<body>',
  93. position: 'before',
  94. },
  95. }));
  96. config.plugins.push(new class ListBackgroundScripts {
  97. apply(compiler) {
  98. compiler.hooks.afterEmit.tap(this.constructor.name, compilation => {
  99. const dist = compilation.outputOptions.path;
  100. const path = `${dist}/manifest.json`;
  101. const manifest = JSON.parse(fs.readFileSync(path, {encoding: 'utf8'}));
  102. const bgId = 'background/index';
  103. const bgEntry = compilation.entrypoints.get(bgId);
  104. const scripts = bgEntry.chunks.map(c => c.files[0]);
  105. if (`${manifest.background.scripts}` !== `${scripts}`) {
  106. manifest.background.scripts = scripts;
  107. fs.writeFileSync(path,
  108. JSON.stringify(manifest, null, isProd ? 0 : 2),
  109. {encoding: 'utf8'});
  110. }
  111. try {
  112. fs.unlinkSync(`${dist}/${bgId}.html`);
  113. } catch (e) {}
  114. });
  115. }
  116. });
  117. }),
  118. modify('injected', './src/injected', (config) => {
  119. addWrapper(config, getGlobals => ({
  120. header: () => `${skipReinjectionHeader} { ${getGlobals()}`,
  121. footer: '}',
  122. }));
  123. }),
  124. modify('injected-web', './src/injected/web', (config) => {
  125. config.output.libraryTarget = 'commonjs2';
  126. addWrapper(config, getGlobals => ({
  127. header: () => `${skipReinjectionHeader}
  128. window['${INIT_FUNC_NAME}'] = function () {
  129. var module = { exports: {} };
  130. ${getGlobals()}`,
  131. footer: `
  132. module = module.exports;
  133. return module.__esModule ? module.default : module;
  134. };0;`,
  135. }));
  136. }),
  137. ]);