webpack.conf.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 TerserPlugin = isProd && require('terser-webpack-plugin');
  8. const deepmerge = isProd && require('deepmerge');
  9. const projectConfig = require('./plaid.conf');
  10. const mergedConfig = shallowMerge(defaultOptions, projectConfig);
  11. const INIT_FUNC_NAME = 'VMInitInjection';
  12. // Copied from gulpfile.js: strip alphabetic suffix
  13. const VM_VER = require('../package.json').version.replace(/-[^.]*/, '');
  14. const WEBPACK_OPTS = {
  15. node: {
  16. process: false,
  17. setImmediate: false,
  18. },
  19. performance: {
  20. maxEntrypointSize: 1e6,
  21. maxAssetSize: 0.5e6,
  22. },
  23. };
  24. const minimizerOptions = {
  25. cache: true,
  26. parallel: true,
  27. sourceMap: true,
  28. terserOptions: {
  29. output: {
  30. ascii_only: true,
  31. },
  32. },
  33. };
  34. const pickEnvs = (items) => {
  35. return Object.assign({}, ...items.map(x => ({
  36. [`process.env.${x.key}`]: JSON.stringify(
  37. 'val' in x ? x.val
  38. : process.env[x.key] ?? x.def,
  39. ),
  40. })));
  41. };
  42. const definitions = new webpack.DefinePlugin({
  43. ...pickEnvs([
  44. { key: 'DEBUG', def: false },
  45. { key: 'VM_VER', val: VM_VER },
  46. { key: 'SYNC_GOOGLE_CLIENT_ID' },
  47. { key: 'SYNC_GOOGLE_CLIENT_SECRET' },
  48. { key: 'SYNC_ONEDRIVE_CLIENT_ID' },
  49. { key: 'SYNC_ONEDRIVE_CLIENT_SECRET' },
  50. ]),
  51. 'process.env.INIT_FUNC_NAME': JSON.stringify(INIT_FUNC_NAME),
  52. });
  53. // avoid running webpack bootstrap in a potentially hacked environment
  54. // after documentElement was replaced which triggered reinjection of content scripts
  55. const skipReinjectionHeader = `if (window['${INIT_FUNC_NAME}'] !== 1)`;
  56. // {entryName: path}
  57. const entryGlobals = {
  58. common: './src/common/safe-globals.js',
  59. injected: './src/injected/safe-injected-globals.js',
  60. };
  61. /**
  62. * Adds a watcher for files in entryGlobals to properly recompile the project on changes.
  63. */
  64. const addWrapper = (config, name, callback) => {
  65. if (!callback) { callback = name; name = ''; }
  66. const globals = Object.entries(entryGlobals).filter(([key]) => name === key || !name);
  67. const dirs = globals.map(([key]) => key).join('|');
  68. config.module.rules.push({
  69. test: new RegExp(`/(${dirs})/index\\.js$`.replace(/\//g, /[/\\]/.source)),
  70. use: [{
  71. loader: './scripts/fake-dep-loader.js',
  72. options: {
  73. files: globals.map(([, path]) => path),
  74. },
  75. }],
  76. });
  77. const reader = () => (
  78. globals.map(([, path]) => (
  79. fs.readFileSync(path, { encoding: 'utf8' })
  80. .replace(/export\s+(?=const\s)/g, '')
  81. ))
  82. ).join('\n');
  83. config.plugins.push(new WrapperWebpackPlugin(callback(reader)));
  84. };
  85. const modify = (page, entry, init) => modifyWebpackConfig(
  86. (config) => {
  87. Object.assign(config, WEBPACK_OPTS);
  88. config.plugins.push(definitions);
  89. config.optimization.minimizer.find((m, i, arr) => (
  90. m.constructor.name === 'TerserPlugin' && arr.splice(i, 1)
  91. ));
  92. config.optimization.minimizer.push(...!isProd ? [] : [
  93. new TerserPlugin({
  94. chunkFilter: ({ name }) => name.startsWith('public/'),
  95. ...minimizerOptions,
  96. }),
  97. new TerserPlugin(deepmerge.all([{}, minimizerOptions, {
  98. chunkFilter: ({ name }) => !name.startsWith('public/'),
  99. terserOptions: {
  100. compress: {
  101. ecma: 8, // ES2017 Object.entries and so on
  102. passes: 2, // necessary now since we removed plaid's minimizer
  103. unsafe_arrows: true, // it's 'safe' since we don't rely on function prototypes
  104. },
  105. },
  106. }])),
  107. ]);
  108. if (!entry) init = page;
  109. if (init) init(config);
  110. return config;
  111. }, {
  112. projectConfig: {
  113. ...mergedConfig,
  114. ...entry && { pages: { [page]: { entry } } },
  115. },
  116. },
  117. );
  118. module.exports = Promise.all([
  119. modify((config) => {
  120. addWrapper(config, 'common', getGlobals => ({
  121. header: () => `{ ${getGlobals()}`,
  122. footer: '}',
  123. test: /^(?!injected|public).*\.js$/,
  124. }));
  125. /* Embedding as <style> to ensure uiTheme option doesn't cause FOUC.
  126. * Note that in production build there's no <head> in html but document.head is still
  127. * auto-created per the specification so our styles will be placed correctly anyway. */
  128. if (isProd) {
  129. config.plugins.push(new HTMLInlineCSSWebpackPlugin({
  130. replace: {
  131. target: '<body>',
  132. position: 'before',
  133. },
  134. }));
  135. config.plugins.find(p => (
  136. p.constructor.name === 'MiniCssExtractPlugin'
  137. && Object.assign(p.options, { ignoreOrder: true })
  138. ));
  139. }
  140. config.plugins.push(new class ListBackgroundScripts {
  141. apply(compiler) {
  142. compiler.hooks.afterEmit.tap(this.constructor.name, compilation => {
  143. const dist = compilation.outputOptions.path;
  144. const path = `${dist}/manifest.json`;
  145. const manifest = JSON.parse(fs.readFileSync(path, { encoding: 'utf8' }));
  146. const bgId = 'background/index';
  147. const bgEntry = compilation.entrypoints.get(bgId);
  148. const scripts = bgEntry.chunks.map(c => c.files[0]);
  149. if (`${manifest.background.scripts}` !== `${scripts}`) {
  150. manifest.background.scripts = scripts;
  151. fs.writeFileSync(path,
  152. JSON.stringify(manifest, null, isProd ? 0 : 2),
  153. { encoding: 'utf8' });
  154. }
  155. fs.promises.unlink(`${dist}/${bgId}.html`).catch(() => {});
  156. });
  157. }
  158. }());
  159. }),
  160. modify('injected', './src/injected', (config) => {
  161. addWrapper(config, getGlobals => ({
  162. header: () => `${skipReinjectionHeader} { ${getGlobals()}`,
  163. footer: '}',
  164. }));
  165. }),
  166. modify('injected-web', './src/injected/web', (config) => {
  167. config.output.libraryTarget = 'commonjs2';
  168. addWrapper(config, getGlobals => ({
  169. header: () => `${skipReinjectionHeader}
  170. window['${INIT_FUNC_NAME}'] = function () {
  171. var module = { exports: {} };
  172. ${getGlobals()}`,
  173. footer: `
  174. module = module.exports;
  175. return module.__esModule ? module.default : module;
  176. };0;`,
  177. }));
  178. }),
  179. ]);