diff --git a/.gitignore b/.gitignore index bc560d9747..b250579f83 100644 --- a/.gitignore +++ b/.gitignore @@ -51,7 +51,7 @@ deps seahub/thumbnail/thumb/* .virtualenv -.env +# .env .dumbjump .projectile .pytest_cache/ diff --git a/frontend/.env b/frontend/.env new file mode 100644 index 0000000000..e0c5b1fb33 --- /dev/null +++ b/frontend/.env @@ -0,0 +1,3 @@ +HOST = '0.0.0.0' +PORT = '3000' +PUBLIC_PATH = '/assets/bundles/' \ No newline at end of file diff --git a/frontend/config/jest/babelTransform.js b/frontend/config/jest/babelTransform.js new file mode 100644 index 0000000000..5b391e4055 --- /dev/null +++ b/frontend/config/jest/babelTransform.js @@ -0,0 +1,29 @@ +'use strict'; + +const babelJest = require('babel-jest').default; + +const hasJsxRuntime = (() => { + if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') { + return false; + } + + try { + require.resolve('react/jsx-runtime'); + return true; + } catch (e) { + return false; + } +})(); + +module.exports = babelJest.createTransformer({ + presets: [ + [ + require.resolve('babel-preset-react-app'), + { + runtime: hasJsxRuntime ? 'automatic' : 'classic', + }, + ], + ], + babelrc: false, + configFile: false, +}); diff --git a/frontend/config/paths.js b/frontend/config/paths.js index f86494a8a8..24549e817c 100644 --- a/frontend/config/paths.js +++ b/frontend/config/paths.js @@ -15,11 +15,18 @@ const resolveApp = relativePath => path.resolve(appDirectory, relativePath); // single-page apps that may serve index.html for nested URLs like /todos/42. // We can't use a relative path in HTML because we don't want to load something // like /todos/42/static/js/bundle.7289d.js. We have to know the root. -const publicUrlOrPath = getPublicUrlOrPath( - process.env.NODE_ENV === 'development', - require(resolveApp('package.json')).homepage, - process.env.PUBLIC_URL -); +// const publicUrlOrPath = getPublicUrlOrPath( +// process.env.NODE_ENV === 'development', +// require(resolveApp('package.json')).homepage, +// process.env.PUBLIC_URL +// ); + +const HOST = process.env.HOST || '0.0.0.0'; +const PORT = process.env.PORT || '3000'; +const publicPath = process.env.PUBLIC_PATH || '/assets/bundles/'; +const publicUrlOrPath = `http://${HOST}:${PORT}${publicPath}`; + +const buildPath = process.env.BUILD_PATH || 'build'; const moduleFileExtensions = [ 'web.mjs', @@ -52,7 +59,7 @@ const resolveModule = (resolveFn, filePath) => { module.exports = { dotenv: resolveApp('.env'), appPath: resolveApp('.'), - appBuild: resolveApp('build/frontend'), + appBuild: resolveApp('build/frontend'), // seafile custom defined appPublic: resolveApp('public'), appHtml: resolveApp('public/index.html'), appIndexJs: resolveModule(resolveApp, 'src/index'), @@ -64,6 +71,8 @@ module.exports = { testsSetup: resolveModule(resolveApp, 'src/setupTests'), proxySetup: resolveApp('src/setupProxy.js'), appNodeModules: resolveApp('node_modules'), + appWebpackCache: resolveApp('node_modules/.cache'), + appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'), swSrc: resolveModule(resolveApp, 'src/service-worker'), publicUrlOrPath, }; diff --git a/frontend/config/server.js b/frontend/config/server.js index 3e59690c34..b2809dbd24 100644 --- a/frontend/config/server.js +++ b/frontend/config/server.js @@ -1,35 +1,54 @@ 'use strict'; // https://github.com/webpack/webpack-dev-server/blob/master/examples/api/simple/server.js +const dotenv = require('dotenv'); + +dotenv.config(); process.env.NODE_ENV = 'development'; process.env.BABEL_ENV = 'development'; -var Webpack = require('webpack') -var WebpackDevServer = require('webpack-dev-server') -var configFactory = require('./webpack.config') -var config = configFactory('development'); +const Webpack = require('webpack') +const WebpackDevServer = require('webpack-dev-server') +const ignoredFiles = require('react-dev-utils/ignoredFiles'); +const configFactory = require('./webpack.config') +const paths = require('./paths'); +const getHttpsConfig = require('./getHttpsConfig'); -const compiler = Webpack(config); -const devServerOptions = Object.assign({}, config.devServer, { - stats: { - colors: true - }, +const HOST = process.env.HOST || '0.0.0.0'; +const PORT = process.env.PORT || '3000'; +const publicPath = process.env.PUBLIC_PATH || '/assets/bundles/'; + +const devServerOptions = { + allowedHosts: 'all', hot: true, - // Use 'ws' instead of 'sockjs-node' on server since we're using native - // websockets in `webpackHotDevClient`. - transportMode: 'ws', - // Prevent a WS client from getting injected as we're already including - // `webpackHotDevClient`. - injectClient: false, -}); + static: { + directory: paths.appBuild, + publicPath: publicPath, + watch: { + ignored: ignoredFiles(paths.appSrc), + }, + }, + client: { + overlay: false, + }, + headers: { + 'Access-Control-Allow-Origin': '*', + 'Access-Control-Allow-Methods': '*', + 'Access-Control-Allow-Headers': '*', + }, + // Enable gzip compression of generated files. + compress: true, + https: getHttpsConfig(), + host: HOST, + port: PORT, +}; console.log('Dev server options:', devServerOptions); -const server = new WebpackDevServer(compiler, devServerOptions); -server.listen(3000, '0.0.0.0', function (err, result) { - if (err) { - console.log(err) - } +const config = configFactory('development'); +const compiler = Webpack(config); +const server = new WebpackDevServer(devServerOptions, compiler); - console.log('Listening at 0.0.0.0:3000') -}) +server.startCallback(() => { + console.log(`Listening at http://${HOST}:${PORT}${publicPath}`); +}); diff --git a/frontend/config/webpack.config.js b/frontend/config/webpack.config.js index cda0c7e89d..3e0d0aa315 100644 --- a/frontend/config/webpack.config.js +++ b/frontend/config/webpack.config.js @@ -4,16 +4,15 @@ const fs = require('fs'); const path = require('path'); const webpack = require('webpack'); const resolve = require('resolve'); -const PnpWebpackPlugin = require('pnp-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin'); const TerserPlugin = require('terser-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); -const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); -const safePostCssParser = require('postcss-safe-parser'); -const ManifestPlugin = require('webpack-manifest-plugin'); +const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); +const { WebpackManifestPlugin } = require('webpack-manifest-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); +const WorkboxWebpackPlugin = require('workbox-webpack-plugin'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent'); const ESLintPlugin = require('eslint-webpack-plugin'); @@ -22,28 +21,40 @@ const paths = require('./paths'); const modules = require('./modules'); const getClientEnvironment = require('./env'); const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin'); -const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin'); +const NodePolyfillPlugin = require('node-polyfill-webpack-plugin') + +const ForkTsCheckerWebpackPlugin = + process.env.TSC_COMPILE_ON_ERROR === 'true' + ? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin') + : require('react-dev-utils/ForkTsCheckerWebpackPlugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); -const postcssNormalize = require('postcss-normalize'); +const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash'); const getEntries = require('./webpack.entry'); -const appPackageJson = require(paths.appPackageJson); - // Source maps are resource heavy and can cause out of memory issue for large source files. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false'; -const webpackDevClientEntry = require.resolve( - 'react-dev-utils/webpackHotDevClient' +const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime'); +const reactRefreshWebpackPluginRuntimeEntry = require.resolve( + '@pmmmwh/react-refresh-webpack-plugin' ); -const reactRefreshOverlayEntry = require.resolve( - 'react-dev-utils/refreshOverlayInterop' +const babelRuntimeEntry = require.resolve('babel-preset-react-app'); +const babelRuntimeEntryHelpers = require.resolve( + '@babel/runtime/helpers/esm/assertThisInitialized', + { paths: [babelRuntimeEntry] } ); +const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', { + paths: [babelRuntimeEntry], +}); // Some apps do not need the benefits of saving a web request, so not inlining the chunk // makes for a smoother build process. const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false'; +const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true'; +const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true'; + const imageInlineSizeLimit = parseInt( process.env.IMAGE_INLINE_SIZE_LIMIT || '10000' ); @@ -51,6 +62,11 @@ const imageInlineSizeLimit = parseInt( // Check if TypeScript is setup const useTypeScript = fs.existsSync(paths.appTsConfig); +// Check if Tailwind config exists +const useTailwind = fs.existsSync( + path.join(paths.appPath, 'tailwind.config.js') +); + // Get the path to the uncompiled service worker (if it exists). const swSrc = paths.swSrc; @@ -100,7 +116,6 @@ module.exports = function (webpackEnv) { loader: MiniCssExtractPlugin.loader, // css is located in `static/css`, use '../../' to locate index.html folder // in production `paths.publicUrlOrPath` can be a relative path - //! important options: { publicPath: '../../' } }, { @@ -113,22 +128,42 @@ module.exports = function (webpackEnv) { // package.json loader: require.resolve('postcss-loader'), options: { - // Necessary for external CSS imports to work - // https://github.com/facebook/create-react-app/issues/2677 - ident: 'postcss', - plugins: () => [ - require('postcss-flexbugs-fixes'), - require('postcss-preset-env')({ - autoprefixer: { - flexbox: 'no-2009', - }, - stage: 3, - }), - // Adds PostCSS Normalize as the reset css with default options, - // so that it honors browserslist config in package.json - // which in turn let's users customize the target behavior as per their needs. - postcssNormalize(), - ], + postcssOptions: { + // Necessary for external CSS imports to work + // https://github.com/facebook/create-react-app/issues/2677 + ident: 'postcss', + config: false, + plugins: !useTailwind + ? [ + 'postcss-flexbugs-fixes', + [ + 'postcss-preset-env', + { + autoprefixer: { + flexbox: 'no-2009', + }, + stage: 3, + }, + ], + // Adds PostCSS Normalize as the reset css with default options, + // so that it honors browserslist config in package.json + // which in turn let's users customize the target behavior as per their needs. + 'postcss-normalize', + ] + : [ + 'tailwindcss', + 'postcss-flexbugs-fixes', + [ + 'postcss-preset-env', + { + autoprefixer: { + flexbox: 'no-2009', + }, + stage: 3, + }, + ], + ], + }, sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, }, }, @@ -153,47 +188,10 @@ module.exports = function (webpackEnv) { return loaders; }; - const getOutput = (isEnvDevelopment) => { - let output = { - // The build folder. - path: isEnvProduction ? paths.appBuild : undefined, - // Add /* filename */ comments to generated require()s in the output. - pathinfo: isEnvDevelopment, - // There will be one main bundle, and one file per asynchronous chunk. - // In development, it does not produce real files. - filename: isEnvProduction - ? 'static/js/[name].js' - : isEnvDevelopment && 'static/js/[name].bundle.js', - // TODO: remove this when upgrading to webpack 5 - futureEmitAssets: true, - // There are also additional JS chunk files if you use code splitting. - chunkFilename: 'static/js/[name].chunk.js', - // Point sourcemap entries to original disk location (format as URL on Windows) - devtoolModuleFilenameTemplate: isEnvProduction - ? info => - path - .relative(paths.appSrc, info.absoluteResourcePath) - .replace(/\\/g, '/') - : isEnvDevelopment && - (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')), - // Prevents conflicts when multiple webpack runtimes (from different apps) - // are used on the same page. - jsonpFunction: `webpackJsonp${appPackageJson.name}`, - // this defaults to 'window', but by setting it to 'this' then - // module chunks which are built will work in web workers as well. - globalObject: 'this', - }; - if (isEnvDevelopment) { - // webpack uses `publicPath` to determine where the app is being served from. - // It requires a trailing slash, or the file assets will get an incorrect path. - // We inferred the "public path" (such as / or /my-project) from homepage. - output = Object.assign({}, output, {publicPath: 'http://127.0.0.1:3000/assets/bundles/'}); - } - return output; - }; - - return { + target: ['browserslist'], + // Webpack noise constrained to errors and warnings + stats: 'errors-warnings', mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development', // Stop compilation early in production bail: isEnvProduction, @@ -204,14 +202,56 @@ module.exports = function (webpackEnv) { : isEnvDevelopment && 'cheap-module-source-map', // These are the "entry points" to our application. // This means they will be the "root" imports that are included in JS bundle. - entry: getEntries(isEnvDevelopment), - output: getOutput(isEnvDevelopment), + entry: getEntries(), + output: { + // The build folder. + path: paths.appBuild, + // Add /* filename */ comments to generated require()s in the output. + pathinfo: isEnvDevelopment, + // There will be one main bundle, and one file per asynchronous chunk. + // In development, it does not produce real files. + filename: isEnvProduction + ? 'static/js/[name].[contenthash:8].js' + : isEnvDevelopment && 'static/js/[name].bundle.js', + // There are also additional JS chunk files if you use code splitting. + chunkFilename: isEnvProduction + ? 'static/js/[name].[contenthash:8].chunk.js' + : isEnvDevelopment && 'static/js/[name].chunk.js', + assetModuleFilename: 'static/media/[name].[hash][ext]', + // webpack uses `publicPath` to determine where the app is being served from. + // It requires a trailing slash, or the file assets will get an incorrect path. + // We inferred the "public path" (such as / or /my-project) from homepage. + ...(isEnvDevelopment && {publicPath: paths.publicUrlOrPath}), // The deployment environment does not require this parameter + // Point sourcemap entries to original disk location (format as URL on Windows) + devtoolModuleFilenameTemplate: isEnvProduction + ? info => + path + .relative(paths.appSrc, info.absoluteResourcePath) + .replace(/\\/g, '/') + : isEnvDevelopment && + (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')), + }, + cache: { + type: 'filesystem', + version: createEnvironmentHash(env.raw), + cacheDirectory: paths.appWebpackCache, + store: 'pack', + buildDependencies: { + defaultWebpack: ['webpack/lib/'], + config: [__filename], + tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f => + fs.existsSync(f) + ), + }, + }, + infrastructureLogging: { + level: 'none', + }, optimization: { minimize: isEnvProduction, minimizer: [ // This is only used in production mode new TerserPlugin({ - extractComments: false, terserOptions: { parse: { // We want terser to parse ecma 8 code. However, we don't want it @@ -249,27 +289,9 @@ module.exports = function (webpackEnv) { ascii_only: true, }, }, - sourceMap: shouldUseSourceMap, }), // This is only used in production mode - new OptimizeCSSAssetsPlugin({ - cssProcessorOptions: { - parser: safePostCssParser, - map: shouldUseSourceMap - ? { - // `inline: false` forces the sourcemap to be output into a - // separate file - inline: false, - // `annotation: true` appends the sourceMappingURL to the end of - // the css file, helping the browser find the sourcemap - annotation: true, - } - : false, - }, - cssProcessorPluginOptions: { - preset: ['default', { minifyFontValues: { removeQuotes: false } }], - }, - }), + new CssMinimizerPlugin(), ], // Automatically split vendor and commons // https://twitter.com/wSokra/status/969633336732905474 @@ -277,10 +299,9 @@ module.exports = function (webpackEnv) { splitChunks: { chunks: 'all', automaticNameDelimiter: '-', - name: true, cacheGroups: { - vendors: false, default: false, + defaultVendors: false, commons: { name: 'commons', minChunks: 3, @@ -325,9 +346,6 @@ module.exports = function (webpackEnv) { ...(modules.webpackAliases || {}), }, plugins: [ - // Adds support for installing with Plug'n'Play, leading to faster installs and adding - // guards against forgotten dependencies and such. - PnpWebpackPlugin, // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, @@ -335,22 +353,24 @@ module.exports = function (webpackEnv) { // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc, [ paths.appPackageJson, - reactRefreshOverlayEntry, + reactRefreshRuntimeEntry, + reactRefreshWebpackPluginRuntimeEntry, + babelRuntimeEntry, + babelRuntimeEntryHelpers, + babelRuntimeRegenerator, ]), ], }, - resolveLoader: { - plugins: [ - // Also related to Plug'n'Play, but this time it tells webpack to load its loaders - // from the current package. - PnpWebpackPlugin.moduleLoader(module), - ], - }, module: { strictExportPresence: true, rules: [ - // Disable require.ensure as it's not a standard language feature. - { parser: { requireEnsure: false } }, + // Handle node_modules packages that contain sourcemaps + shouldUseSourceMap && { + enforce: 'pre', + exclude: /@babel(?:\/|\\{1,2})runtime/, + test: /\.(js|mjs|jsx|ts|tsx|css)$/, + loader: require.resolve('source-map-loader'), + }, { // "oneOf" will traverse all following loaders until one will // match the requirements. When no loader matches it will fall @@ -360,11 +380,12 @@ module.exports = function (webpackEnv) { // https://github.com/jshttp/mime-db { test: [/\.avif$/], - loader: require.resolve('url-loader'), - options: { - limit: imageInlineSizeLimit, - mimetype: 'image/avif', - name: 'static/media/[name].[hash:8].[ext]', + type: 'asset', + mimetype: 'image/avif', + parser: { + dataUrlCondition: { + maxSize: imageInlineSizeLimit, + }, }, }, // "url" loader works like "file" loader except that it embeds assets @@ -372,10 +393,37 @@ module.exports = function (webpackEnv) { // A missing `test` is equivalent to a match. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], - loader: require.resolve('url-loader'), - options: { - limit: imageInlineSizeLimit, - name: 'static/media/[name].[hash:8].[ext]', + type: 'asset', + parser: { + dataUrlCondition: { + maxSize: imageInlineSizeLimit, + }, + }, + }, + { + test: /\.svg$/, + use: [ + { + loader: require.resolve('@svgr/webpack'), + options: { + prettier: false, + svgo: false, + svgoConfig: { + plugins: [{ removeViewBox: false }], + }, + titleProp: true, + ref: true, + }, + }, + { + loader: require.resolve('file-loader'), + options: { + name: 'static/media/[name].[hash].[ext]', + }, + }, + ], + issuer: { + and: [/\.(ts|tsx|js|jsx|md|mdx)$/], }, }, // Process application JS with Babel. @@ -396,20 +444,8 @@ module.exports = function (webpackEnv) { }, ], ], - + plugins: [ - [ - require.resolve('babel-plugin-named-asset-import'), - { - loaderMap: { - svg: { - ReactComponent: - '@svgr/webpack?-svgo,+titleProp,+ref![path]', - }, - }, - }, - ], - //! error // isEnvDevelopment && // shouldUseReactRefresh && // require.resolve('react-refresh/babel'), @@ -442,7 +478,7 @@ module.exports = function (webpackEnv) { cacheDirectory: true, // See #6846 for context on why cacheCompression is disabled cacheCompression: false, - + // Babel sourcemaps are needed for debugging into node_modules // code. Without the options below, debuggers like VSCode // show incorrect code and set breakpoints on the wrong lines. @@ -465,6 +501,9 @@ module.exports = function (webpackEnv) { sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, + modules: { + mode: 'icss', + }, }), // Don't consider CSS imports dead code even if the // containing package claims to have no side effects. @@ -482,6 +521,7 @@ module.exports = function (webpackEnv) { ? shouldUseSourceMap : isEnvDevelopment, modules: { + mode: 'local', getLocalIdent: getCSSModuleLocalIdent, }, }), @@ -498,6 +538,9 @@ module.exports = function (webpackEnv) { sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment, + modules: { + mode: 'icss', + }, }, 'sass-loader' ), @@ -518,12 +561,14 @@ module.exports = function (webpackEnv) { ? shouldUseSourceMap : isEnvDevelopment, modules: { + mode: 'local', getLocalIdent: getCSSModuleLocalIdent, }, }, 'sass-loader' ), }, + // Handle svg icons { test: /\.svg$/, use: [ @@ -548,23 +593,26 @@ module.exports = function (webpackEnv) { // This loader doesn't use a "test" so it will catch all modules // that fall through the other loaders. { - loader: require.resolve('file-loader'), // Exclude `js` files to keep "css" loader working as it injects // its runtime that would otherwise be processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. - exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/], - options: { - name: 'static/media/[name].[hash:8].[ext]', - }, + exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/], + type: 'asset/resource', }, // ** STOP ** Are you adding a new loader? // Make sure to add the new loader(s) before the "file" loader. ], }, - ], + ].filter(Boolean), }, plugins: [ + new webpack.ProvidePlugin({ + process: "process/browser.js", + }), + new NodePolyfillPlugin({ + excludeAliases: ['console'], + }), // Generates an `index.html` file with the