webpack.common.js 7.0 KB

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