webpack.common.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. /* eslint-disable camelcase */
  2. const { VueLoaderPlugin } = require('vue-loader')
  3. const path = require('path')
  4. const BabelLoaderExcludeNodeModulesExcept = require('babel-loader-exclude-node-modules-except')
  5. const webpack = require('webpack')
  6. const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
  7. const WorkboxPlugin = require('workbox-webpack-plugin')
  8. const { merge } = require('webpack-merge')
  9. const modules = require('./webpack.modules.js')
  10. const { readFileSync } = require('fs')
  11. const appVersion = readFileSync('./version.php').toString().match(/OC_VersionString[^']+'([^']+)/)?.[1] ?? 'unknown'
  12. const formatOutputFromModules = (modules) => {
  13. // merge all configs into one object, and use AppID to generate the fileNames
  14. // with the following format:
  15. // AppId-fileName: path/to/js-file.js
  16. const moduleEntries = Object.keys(modules).map(moduleKey => {
  17. const module = modules[moduleKey]
  18. const entries = Object.keys(module).map(entryKey => {
  19. const entry = module[entryKey]
  20. return { [`${moduleKey}-${entryKey}`]: entry }
  21. })
  22. return Object.assign({}, ...Object.values(entries))
  23. })
  24. return Object.assign({}, ...Object.values(moduleEntries))
  25. }
  26. const modulesToBuild = (modules) => {
  27. const MODULE = process?.env?.MODULE
  28. if (MODULE) {
  29. if (!modules[MODULE]) {
  30. throw new Error(`No module "${MODULE}" found`)
  31. }
  32. return formatOutputFromModules({
  33. [MODULE]: modules[MODULE],
  34. })
  35. }
  36. return formatOutputFromModules(modules)
  37. }
  38. const baseEntries = {
  39. entry: modulesToBuild(modules),
  40. }
  41. const standaloneEntries = {
  42. entry: modulesToBuild({
  43. core: {
  44. login_standalone: path.join(__dirname, 'core/src', 'login.js'),
  45. },
  46. }),
  47. }
  48. const baseConfig = {
  49. output: {
  50. // Step away from the src folder and extract to the js folder
  51. path: path.join(__dirname, 'dist'),
  52. // Let webpack determine automatically where it's located
  53. publicPath: 'auto',
  54. filename: '[name].js?v=[contenthash]',
  55. chunkFilename: '[name]-[id].js?v=[contenthash]',
  56. // Make sure sourcemaps have a proper path and do not
  57. // leak local paths https://github.com/webpack/webpack/issues/3603
  58. devtoolNamespace: 'nextcloud',
  59. devtoolModuleFilenameTemplate(info) {
  60. const rootDir = process?.cwd()
  61. const rel = path.relative(rootDir, info.absoluteResourcePath)
  62. return `webpack:///nextcloud/${rel}`
  63. },
  64. },
  65. module: {
  66. rules: [
  67. {
  68. test: /davclient/,
  69. loader: 'exports-loader',
  70. options: {
  71. type: 'commonjs',
  72. exports: 'dav',
  73. },
  74. },
  75. {
  76. test: /\.css$/,
  77. use: ['style-loader', 'css-loader'],
  78. },
  79. {
  80. test: /\.scss$/,
  81. use: ['style-loader', 'css-loader', 'sass-loader'],
  82. },
  83. {
  84. test: /\.vue$/,
  85. loader: 'vue-loader',
  86. exclude: BabelLoaderExcludeNodeModulesExcept([
  87. 'vue-material-design-icons',
  88. 'emoji-mart-vue-fast',
  89. ]),
  90. },
  91. {
  92. test: /\.tsx?$/,
  93. use: [
  94. 'babel-loader',
  95. {
  96. // Fix TypeScript syntax errors in Vue
  97. loader: 'ts-loader',
  98. options: {
  99. transpileOnly: true,
  100. },
  101. },
  102. ],
  103. exclude: BabelLoaderExcludeNodeModulesExcept([]),
  104. },
  105. {
  106. test: /\.js$/,
  107. loader: 'babel-loader',
  108. // automatically detect necessary packages to
  109. // transpile in the node_modules folder
  110. exclude: BabelLoaderExcludeNodeModulesExcept([
  111. '@nextcloud/dialogs',
  112. '@nextcloud/event-bus',
  113. 'davclient.js',
  114. 'nextcloud-vue-collections',
  115. 'p-finally',
  116. 'p-limit',
  117. 'p-locate',
  118. 'p-queue',
  119. 'p-timeout',
  120. 'p-try',
  121. 'semver',
  122. 'striptags',
  123. 'toastify-js',
  124. 'v-tooltip',
  125. 'yocto-queue',
  126. ]),
  127. },
  128. {
  129. test: /\.(png|jpe?g|gif|svg|woff2?|eot|ttf)$/,
  130. type: 'asset/inline',
  131. },
  132. {
  133. test: /\.handlebars/,
  134. loader: 'handlebars-loader',
  135. },
  136. {
  137. resourceQuery: /raw/,
  138. type: 'asset/source',
  139. },
  140. ],
  141. },
  142. plugins: [
  143. new VueLoaderPlugin(),
  144. new NodePolyfillPlugin(),
  145. new webpack.ProvidePlugin({
  146. // Provide jQuery to jquery plugins as some are loaded before $ is exposed globally.
  147. // We need to provide the path to node_moduels as otherwise npm link will fail due
  148. // to tribute.js checking for jQuery in @nextcloud/vue
  149. jQuery: path.resolve(path.join(__dirname, 'node_modules/jquery')),
  150. // Shim ICAL to prevent using the global object (window.ICAL).
  151. // The library ical.js heavily depends on instanceof checks which will
  152. // break if two separate versions of the library are used (e.g. bundled one
  153. // and global one).
  154. ICAL: 'ical.js',
  155. }),
  156. new WorkboxPlugin.GenerateSW({
  157. swDest: 'preview-service-worker.js',
  158. clientsClaim: true,
  159. skipWaiting: true,
  160. exclude: [/.*/], // don't do pre-caching
  161. inlineWorkboxRuntime: true,
  162. sourcemap: false,
  163. // Increase perfs with less logging
  164. disableDevLogs: true,
  165. // Define runtime caching rules.
  166. runtimeCaching: [{
  167. // Match any preview file request
  168. // /apps/files_trashbin/preview?fileId=156380&a=1
  169. // /core/preview?fileId=155842&a=1
  170. urlPattern: /^.*\/(apps|core)(\/[a-z-_]+)?\/preview.*/i,
  171. // Apply a strategy.
  172. handler: 'CacheFirst',
  173. options: {
  174. // Use a custom cache name.
  175. cacheName: 'previews',
  176. // Only cache 10000 images.
  177. expiration: {
  178. maxAgeSeconds: 3600 * 24 * 7, // one week
  179. maxEntries: 10000,
  180. },
  181. },
  182. }],
  183. }),
  184. // Make appName & appVersion available as a constants for '@nextcloud/vue' components
  185. new webpack.DefinePlugin({ appName: JSON.stringify('Nextcloud') }),
  186. new webpack.DefinePlugin({ appVersion: JSON.stringify(appVersion) }),
  187. // @nextcloud/moment since v1.3.0 uses `moment/min/moment-with-locales.js`
  188. // Which works only in Node.js and is not compatible with Webpack bundling
  189. // It has an unused function `localLocale` that requires locales by invalid relative path `./locale`
  190. // Though it is not used, Webpack tries to resolve it with `require.context` and fails
  191. new webpack.IgnorePlugin({
  192. resourceRegExp: /^\.\/locale$/,
  193. contextRegExp: /moment\/min$/,
  194. }),
  195. ],
  196. externals: {
  197. OC: 'OC',
  198. OCA: 'OCA',
  199. OCP: 'OCP',
  200. },
  201. resolve: {
  202. alias: {
  203. // make sure to use the handlebar runtime when importing
  204. handlebars: 'handlebars/runtime',
  205. vue$: path.resolve('./node_modules/vue'),
  206. },
  207. extensions: ['*', '.ts', '.js', '.vue'],
  208. extensionAlias: {
  209. /**
  210. * Resolve TypeScript files when using fully-specified esm import paths
  211. * https://github.com/webpack/webpack/issues/13252
  212. */
  213. '.js': ['.js', '.ts'],
  214. },
  215. symlinks: true,
  216. fallback: {
  217. fs: false,
  218. },
  219. },
  220. }
  221. const optimizationConfig = {
  222. optimization: {
  223. splitChunks: {
  224. automaticNameDelimiter: '-',
  225. minChunks: 3, // minimum number of chunks that must share the module
  226. cacheGroups: {
  227. vendors: {
  228. // split every dependency into one bundle
  229. test: /[\\/]node_modules[\\/]/,
  230. // necessary to keep this name to properly inject it
  231. // see OC_Template.php
  232. name: 'core-common',
  233. chunks: 'all',
  234. },
  235. },
  236. },
  237. },
  238. }
  239. module.exports = [
  240. merge(baseConfig, baseEntries, optimizationConfig, {
  241. output: {
  242. clean: false,
  243. },
  244. }),
  245. merge(baseConfig, standaloneEntries, {
  246. output: {
  247. clean: {
  248. keep: /icons\.css/, // Keep static icons css
  249. },
  250. },
  251. }),
  252. ]