webpack.conf.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. const { modifyWebpackConfig, shallowMerge, defaultOptions } = require('@gera2ld/plaid');
  2. const { isProd } = require('@gera2ld/plaid/util');
  3. const webpack = require('webpack');
  4. const TerserPlugin = isProd && require('terser-webpack-plugin');
  5. const deepmerge = isProd && require('deepmerge');
  6. const { ListBackgroundScriptsPlugin } = require('./manifest-helper');
  7. const { addWrapperWithGlobals, getUniqIdB64 } = require('./webpack-util');
  8. const ProtectWebpackBootstrapPlugin = require('./webpack-protect-bootstrap-plugin');
  9. const projectConfig = require('./plaid.conf');
  10. const mergedConfig = shallowMerge(defaultOptions, projectConfig);
  11. // Avoiding collisions with globals of a content-mode userscript
  12. const INIT_FUNC_NAME = `Violentmonkey:${getUniqIdB64()}`;
  13. const VAULT_ID = '__VAULT_ID__';
  14. const HANDSHAKE_ID = '__HANDSHAKE_ID__';
  15. // eslint-disable-next-line import/no-dynamic-require
  16. const VM_VER = require(`${defaultOptions.distDir}/manifest.json`).version;
  17. const WEBPACK_OPTS = {
  18. node: {
  19. global: false,
  20. process: false,
  21. setImmediate: false,
  22. },
  23. performance: {
  24. maxEntrypointSize: 1e6,
  25. maxAssetSize: 0.5e6,
  26. },
  27. };
  28. const MIN_OPTS = {
  29. cache: true,
  30. extractComments: false,
  31. parallel: true,
  32. sourceMap: true,
  33. terserOptions: {
  34. compress: {
  35. // `terser` often inlines big one-time functions inside a small "hot" function
  36. reduce_funcs: false,
  37. reduce_vars: false,
  38. },
  39. output: {
  40. ascii_only: true,
  41. comments: false,
  42. wrap_func_args: false, // disabling a premature optimization designed for old browsers
  43. },
  44. },
  45. };
  46. const MIN_OPTS_PUBLIC = isProd && {
  47. include: 'public/',
  48. ...MIN_OPTS,
  49. };
  50. const MIN_OPTS_MAIN = isProd && deepmerge.all([{}, MIN_OPTS, {
  51. exclude: 'public/',
  52. terserOptions: {
  53. compress: {
  54. ecma: 8, // ES2017 Object.entries and so on
  55. passes: 2, // necessary now since we removed plaid's minimizer
  56. unsafe_arrows: true, // it's 'safe' since we don't rely on function prototypes
  57. },
  58. },
  59. }]);
  60. const pickEnvs = (items) => {
  61. return Object.assign({}, ...items.map(x => ({
  62. [`process.env.${x.key}`]: JSON.stringify(
  63. 'val' in x ? x.val
  64. : process.env[x.key] ?? x.def,
  65. ),
  66. })));
  67. };
  68. const defsObj = {
  69. ...pickEnvs([
  70. { key: 'DEBUG', def: false },
  71. { key: 'VM_VER', val: VM_VER },
  72. { key: 'SYNC_GOOGLE_CLIENT_ID' },
  73. { key: 'SYNC_GOOGLE_CLIENT_SECRET' },
  74. { key: 'SYNC_ONEDRIVE_CLIENT_ID' },
  75. { key: 'SYNC_ONEDRIVE_CLIENT_SECRET' },
  76. ]),
  77. 'process.env.INIT_FUNC_NAME': JSON.stringify(INIT_FUNC_NAME),
  78. 'process.env.VAULT_ID': VAULT_ID,
  79. 'process.env.HANDSHAKE_ID': HANDSHAKE_ID,
  80. 'process.env.HANDSHAKE_ACK': '1',
  81. };
  82. // avoid running webpack bootstrap in a potentially hacked environment
  83. // after documentElement was replaced which triggered reinjection of content scripts
  84. const skipReinjectionHeader = `if (window['${INIT_FUNC_NAME}'] !== 1)`;
  85. const modify = (page, entry, init) => modifyWebpackConfig(
  86. (config) => {
  87. Object.assign(config, WEBPACK_OPTS);
  88. config.plugins.push(new webpack.DefinePlugin({
  89. ...defsObj,
  90. // Conditional compilation to remove unsafe and unused stuff from `injected`
  91. 'process.env.IS_INJECTED': JSON.stringify(/injected/.test(page) && page),
  92. }));
  93. config.optimization.minimizer.find((m, i, arr) => (
  94. m.constructor.name === 'TerserPlugin' && arr.splice(i, 1)
  95. ));
  96. config.optimization.minimizer.push(...!isProd ? [] : [
  97. new TerserPlugin(MIN_OPTS_PUBLIC),
  98. new TerserPlugin(MIN_OPTS_MAIN),
  99. ]);
  100. if (!entry) init = page;
  101. if (init) init(config);
  102. return config;
  103. }, {
  104. projectConfig: {
  105. ...mergedConfig,
  106. ...entry && { pages: { [page]: { entry } } },
  107. },
  108. },
  109. );
  110. module.exports = Promise.all([
  111. modify((config) => {
  112. addWrapperWithGlobals('common', config, defsObj, getGlobals => ({
  113. header: () => `{ ${getGlobals()}`,
  114. footer: '}',
  115. test: /^(?!injected|public).*\.js$/,
  116. }));
  117. config.plugins.push(new ListBackgroundScriptsPlugin({
  118. minify: false, // keeping readable
  119. }));
  120. }),
  121. modify('injected', './src/injected', (config) => {
  122. config.plugins.push(new ProtectWebpackBootstrapPlugin());
  123. addWrapperWithGlobals('injected/content', config, defsObj, getGlobals => ({
  124. header: () => `${skipReinjectionHeader} { ${getGlobals()}`,
  125. footer: '}',
  126. }));
  127. }),
  128. modify('injected-web', './src/injected/web', (config) => {
  129. // TODO: replace WebPack's Object.*, .call(), .apply() with safe calls
  130. config.output.libraryTarget = 'commonjs2';
  131. config.plugins.push(new ProtectWebpackBootstrapPlugin());
  132. addWrapperWithGlobals('injected/web', config, defsObj, getGlobals => ({
  133. header: () => `${skipReinjectionHeader}
  134. window['${INIT_FUNC_NAME}'] = function (IS_FIREFOX,${HANDSHAKE_ID},${VAULT_ID}) {
  135. const module = { __proto__: null };
  136. ${getGlobals()}`,
  137. footer: `
  138. const { exports } = module;
  139. return exports.__esModule ? exports.default : exports;
  140. };0;`,
  141. }));
  142. }),
  143. ]);