From 0df90887d378534ec185d92bd259e5baa89afd9c Mon Sep 17 00:00:00 2001 From: Pavel Denisjuk Date: Tue, 1 Aug 2023 11:35:27 +0200 Subject: [PATCH] chore: remove packages-v6 [skip ci] --- example.lerna.json | 2 +- package.json | 3 +- packages-v6/admin/index.tsx | 7 - packages-v6/admin/package.json | 9 - packages-v6/cli/babel.config.js | 11 - packages-v6/cli/package.json | 29 - packages-v6/cli/src/bin.js | 12 - packages-v6/cli/src/buildPackage.ts | 65 -- packages-v6/cli/src/cli.ts | 72 -- packages-v6/cli/src/utils.ts | 50 -- packages-v6/cli/tsconfig.build.json | 12 - packages-v6/cli/tsconfig.json | 16 - packages-v6/core/babel.config.js | 23 - packages-v6/core/package.json | 117 ---- packages-v6/core/src/artifacts/admin/index.ts | 114 --- .../admin/injectSourceFromPlugins.ts | 36 - .../src/artifacts/admin/template/package.json | 17 - .../admin/template/public/index.html | 10 - .../src/artifacts/admin/template/src/App.tsx | 38 - .../artifacts/admin/template/src/index.tsx | 5 - .../artifacts/admin/template/tsconfig.json | 7 - .../core/src/artifacts/bundle/buildApp.ts | 215 ------ .../bundle/config/ModuleGraphPlugin.ts | 148 ---- .../bundle/config/WebpackDevServerUtils.ts | 141 ---- .../src/artifacts/bundle/config/buildFile.ts | 128 ---- .../core/src/artifacts/bundle/config/env.ts | 54 -- .../bundle/config/getProcessForPort.ts | 76 -- .../src/artifacts/bundle/config/modules.ts | 83 --- .../core/src/artifacts/bundle/config/paths.ts | 55 -- .../artifacts/bundle/config/prepareUrls.ts | 66 -- .../artifacts/bundle/config/webpack.config.ts | 650 ------------------ .../bundle/config/webpackDevServer.config.ts | 74 -- .../src/artifacts/bundle/createWatchConfig.ts | 151 ---- .../core/src/artifacts/bundle/utils.ts | 29 - .../core/src/artifacts/bundle/watchApp.ts | 14 - packages-v6/core/src/compose.ts | 66 -- packages-v6/core/src/definePlugin.ts | 184 ----- packages-v6/core/src/definePreset.ts | 13 - packages-v6/core/src/defineProject.ts | 5 - packages-v6/core/src/index.ts | 31 - packages-v6/core/src/types.ts | 63 -- packages-v6/core/src/utils/getRoot.ts | 13 - packages-v6/core/src/utils/index.ts | 50 -- packages-v6/core/src/utils/logger.ts | 84 --- packages-v6/core/src/webiny.ts | 183 ----- packages-v6/core/tsconfig.build.json | 15 - packages-v6/core/tsconfig.json | 18 - packages-v6/preset-aws/babel.config.js | 23 - packages-v6/preset-aws/package.json | 32 - packages-v6/preset-aws/src/index.ts | 7 - packages-v6/preset-aws/tsconfig.build.json | 12 - packages-v6/preset-aws/tsconfig.json | 16 - packages-v6/pulumi-sdk/LICENSE | 21 - packages-v6/pulumi-sdk/README.md | 89 --- packages-v6/pulumi-sdk/babel.config.js | 23 - packages-v6/pulumi-sdk/jest.config.js | 5 - packages-v6/pulumi-sdk/package.json | 68 -- .../pulumi-sdk/src/ApplicationBuilder.ts | 55 -- .../src/ApplicationBuilderGeneric.ts | 87 --- .../src/ApplicationBuilderLegacy.ts | 80 --- .../pulumi-sdk/src/ApplicationConfig.ts | 18 - packages-v6/pulumi-sdk/src/ApplicationHook.ts | 8 - packages-v6/pulumi-sdk/src/Pulumi.ts | 149 ---- packages-v6/pulumi-sdk/src/PulumiApp.ts | 223 ------ packages-v6/pulumi-sdk/src/PulumiResource.ts | 60 -- .../pulumi-sdk/src/downloadBinaries.ts | 96 --- packages-v6/pulumi-sdk/src/index.ts | 12 - .../pulumi-sdk/src/utils/getPulumiWorkDir.ts | 5 - .../pulumi-sdk/src/utils/mergeAppHooks.ts | 17 - .../pulumi-sdk/src/utils/tagResources.ts | 259 ------- packages-v6/pulumi-sdk/tsconfig.build.json | 12 - packages-v6/pulumi-sdk/tsconfig.json | 12 - scripts/buildPackages/src/getBatches.ts | 2 +- scripts/buildWithCache.js | 4 +- scripts/checkTsConfigs.js | 2 +- scripts/generateTsConfigsInPackages.js | 2 +- 76 files changed, 6 insertions(+), 4657 deletions(-) delete mode 100644 packages-v6/admin/index.tsx delete mode 100644 packages-v6/admin/package.json delete mode 100644 packages-v6/cli/babel.config.js delete mode 100644 packages-v6/cli/package.json delete mode 100755 packages-v6/cli/src/bin.js delete mode 100644 packages-v6/cli/src/buildPackage.ts delete mode 100644 packages-v6/cli/src/cli.ts delete mode 100644 packages-v6/cli/src/utils.ts delete mode 100644 packages-v6/cli/tsconfig.build.json delete mode 100644 packages-v6/cli/tsconfig.json delete mode 100644 packages-v6/core/babel.config.js delete mode 100644 packages-v6/core/package.json delete mode 100644 packages-v6/core/src/artifacts/admin/index.ts delete mode 100644 packages-v6/core/src/artifacts/admin/injectSourceFromPlugins.ts delete mode 100644 packages-v6/core/src/artifacts/admin/template/package.json delete mode 100644 packages-v6/core/src/artifacts/admin/template/public/index.html delete mode 100644 packages-v6/core/src/artifacts/admin/template/src/App.tsx delete mode 100644 packages-v6/core/src/artifacts/admin/template/src/index.tsx delete mode 100644 packages-v6/core/src/artifacts/admin/template/tsconfig.json delete mode 100644 packages-v6/core/src/artifacts/bundle/buildApp.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/ModuleGraphPlugin.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/WebpackDevServerUtils.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/buildFile.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/env.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/getProcessForPort.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/modules.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/paths.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/prepareUrls.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/webpack.config.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/config/webpackDevServer.config.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/createWatchConfig.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/utils.ts delete mode 100644 packages-v6/core/src/artifacts/bundle/watchApp.ts delete mode 100644 packages-v6/core/src/compose.ts delete mode 100644 packages-v6/core/src/definePlugin.ts delete mode 100644 packages-v6/core/src/definePreset.ts delete mode 100644 packages-v6/core/src/defineProject.ts delete mode 100644 packages-v6/core/src/index.ts delete mode 100644 packages-v6/core/src/types.ts delete mode 100644 packages-v6/core/src/utils/getRoot.ts delete mode 100644 packages-v6/core/src/utils/index.ts delete mode 100644 packages-v6/core/src/utils/logger.ts delete mode 100644 packages-v6/core/src/webiny.ts delete mode 100644 packages-v6/core/tsconfig.build.json delete mode 100644 packages-v6/core/tsconfig.json delete mode 100644 packages-v6/preset-aws/babel.config.js delete mode 100644 packages-v6/preset-aws/package.json delete mode 100644 packages-v6/preset-aws/src/index.ts delete mode 100644 packages-v6/preset-aws/tsconfig.build.json delete mode 100644 packages-v6/preset-aws/tsconfig.json delete mode 100644 packages-v6/pulumi-sdk/LICENSE delete mode 100644 packages-v6/pulumi-sdk/README.md delete mode 100644 packages-v6/pulumi-sdk/babel.config.js delete mode 100644 packages-v6/pulumi-sdk/jest.config.js delete mode 100644 packages-v6/pulumi-sdk/package.json delete mode 100644 packages-v6/pulumi-sdk/src/ApplicationBuilder.ts delete mode 100644 packages-v6/pulumi-sdk/src/ApplicationBuilderGeneric.ts delete mode 100644 packages-v6/pulumi-sdk/src/ApplicationBuilderLegacy.ts delete mode 100644 packages-v6/pulumi-sdk/src/ApplicationConfig.ts delete mode 100644 packages-v6/pulumi-sdk/src/ApplicationHook.ts delete mode 100644 packages-v6/pulumi-sdk/src/Pulumi.ts delete mode 100644 packages-v6/pulumi-sdk/src/PulumiApp.ts delete mode 100644 packages-v6/pulumi-sdk/src/PulumiResource.ts delete mode 100644 packages-v6/pulumi-sdk/src/downloadBinaries.ts delete mode 100644 packages-v6/pulumi-sdk/src/index.ts delete mode 100644 packages-v6/pulumi-sdk/src/utils/getPulumiWorkDir.ts delete mode 100644 packages-v6/pulumi-sdk/src/utils/mergeAppHooks.ts delete mode 100644 packages-v6/pulumi-sdk/src/utils/tagResources.ts delete mode 100644 packages-v6/pulumi-sdk/tsconfig.build.json delete mode 100644 packages-v6/pulumi-sdk/tsconfig.json diff --git a/example.lerna.json b/example.lerna.json index 15dd1f56892..4b623585c1e 100644 --- a/example.lerna.json +++ b/example.lerna.json @@ -1,5 +1,5 @@ { - "packages": ["packages/*", "packages-v6/*"], + "packages": ["packages/*"], "version": "0.0.0", "npmClient": "yarn", "command": { diff --git a/package.json b/package.json index 7d1cecde31c..d822c730488 100644 --- a/package.json +++ b/package.json @@ -209,8 +209,7 @@ "lerna": { "version": "0.0.0", "packages": [ - "packages/*", - "packages-v6/*" + "packages/*" ] }, "resolutions": { diff --git a/packages-v6/admin/index.tsx b/packages-v6/admin/index.tsx deleted file mode 100644 index 95272139a34..00000000000 --- a/packages-v6/admin/index.tsx +++ /dev/null @@ -1,7 +0,0 @@ -import React from "react"; - -console.log("Admin component"); - -export const Admin: React.FC = ({ children }) => { - return <>{children}; -}; diff --git a/packages-v6/admin/package.json b/packages-v6/admin/package.json deleted file mode 100644 index 9dd4c13ba09..00000000000 --- a/packages-v6/admin/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "private": true, - "name": "@webiny/admin", - "sideEffects": false, - "main": "./src/index.tsx", - "dependencies": { - "react": "^17.0.2" - } -} diff --git a/packages-v6/cli/babel.config.js b/packages-v6/cli/babel.config.js deleted file mode 100644 index b98239bf9ee..00000000000 --- a/packages-v6/cli/babel.config.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - presets: [ - [ - "@babel/env", - { - modules: "commonjs" - } - ], - "@babel/typescript" - ] -}; diff --git a/packages-v6/cli/package.json b/packages-v6/cli/package.json deleted file mode 100644 index bdb31051b40..00000000000 --- a/packages-v6/cli/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "private": true, - "name": "@webiny/cli2", - "version": "0.0.0", - "sideEffects": false, - "bin": { - "wby": "./src/bin.js" - }, - "main": "./src/index.ts", - "scripts": { - "build": "yarn wby build package" - }, - "dependencies": { - "@webiny/core": "^5.33.5", - "execa": "^5.1.1", - "load-json-file": "^6.2.0", - "ts-morph": "^14.0.0", - "yargs": "^17.3.1" - }, - "devDependencies": { - "@types/yargs": "^17.0.8", - "ts-node": "^10.5.0" - }, - "webiny": { - "moduleTypes": [ - "cjs" - ] - } -} diff --git a/packages-v6/cli/src/bin.js b/packages-v6/cli/src/bin.js deleted file mode 100755 index 3cb7ffa3306..00000000000 --- a/packages-v6/cli/src/bin.js +++ /dev/null @@ -1,12 +0,0 @@ -#!/usr/bin/env node -process.env.NODE_PATH = process.cwd(); - -require("ts-node").register({ - dir: process.cwd() -}); - -const { runCli } = require("./cli"); -(async () => { - await runCli(); - process.exit(); -})(); diff --git a/packages-v6/cli/src/buildPackage.ts b/packages-v6/cli/src/buildPackage.ts deleted file mode 100644 index 2d828a9ab39..00000000000 --- a/packages-v6/cli/src/buildPackage.ts +++ /dev/null @@ -1,65 +0,0 @@ -import execa from "execa"; -import loadJson from "load-json-file"; -import { join } from "path"; - -interface BuildPackageParams { - directory: string; -} - -enum ModuleType { - ESM = "esm", - CJS = "cjs" -} - -interface WebinyPackageConfig { - moduleTypes: ModuleType[]; -} - -function getBabelParams(type: ModuleType): string[] { - return [ - "src", - "--extensions", - ".ts,.tsx", - "--out-dir", - `lib/${type}`, - "--source-maps", - "--copy-files" - ]; -} - -export async function buildPackage({ directory }: BuildPackageParams) { - const packageJson: Record = await loadJson(join(directory, "package.json")); - if (!packageJson) { - throw Error(`package.json not found in "${directory}"!`); - } - - const config = packageJson["webiny"] as WebinyPackageConfig | undefined; - const moduleTypes = config ? config.moduleTypes : [ModuleType.CJS, ModuleType.ESM]; - - const promises = []; - - // Build ESM - if (moduleTypes.includes(ModuleType.ESM)) { - promises.push( - execa("babel", getBabelParams(ModuleType.ESM), { - cwd: directory, - env: { BABEL_ENV: ModuleType.ESM } - }) - ); - } - - // Build CJS - if (moduleTypes.includes(ModuleType.CJS)) { - promises.push( - execa("babel", getBabelParams(ModuleType.CJS), { - cwd: directory, - env: { BABEL_ENV: ModuleType.CJS } - }) - ); - } - - // Generate TS declarations - promises.push(execa("ttsc", ["-p", "tsconfig.build.json"], { cwd: directory })); - - return await Promise.all(promises); -} diff --git a/packages-v6/cli/src/cli.ts b/packages-v6/cli/src/cli.ts deleted file mode 100644 index 3528eaeea52..00000000000 --- a/packages-v6/cli/src/cli.ts +++ /dev/null @@ -1,72 +0,0 @@ -import * as yargs from "yargs"; -import type { MiddlewareFunction, Options } from "yargs"; -import { Webiny } from "@webiny/core"; - -interface ParsedOptions { - // Even though `debug` has a default value, and will always be present, we have to mark it as optional - // because the `.middleware()` function doesn't accept a generic type and will complain about any required parameter. - debug?: boolean; - env?: string; -} - -export const runCli = () => { - let webiny: Webiny; - - // `yargs` middleware allows us to setup Webiny based on the parsed CLI arguments. - const setupContext: MiddlewareFunction = async args => { - if (args._.includes("build") && args._.includes("package")) { - return; - } - - const { initializeWebiny } = await import("@webiny/core"); - webiny = await initializeWebiny({ debug: args.debug || false, env: args.env }); - }; - - const envOption: Record = { env: { type: "string", required: true } }; - const watchOption: Record = { watch: { type: "boolean", default: false } }; - - return yargs - .scriptName("webiny") - .usage("$0 [args]") - .middleware(setupContext) - .option("debug", { - default: false, - global: true, - type: "boolean" - }) - .command("watch", "Watch [admin|website]", yargs => { - yargs.command("admin", "Watch the admin app", {}, async () => { - await webiny.buildAdmin({ watch: true }); - }); - }) - .command("build", "Build [package|api|admin|website]", yargs => { - yargs.command("package", "Build a package", {}, async () => { - const { buildPackage } = await import("./buildPackage"); - await buildPackage({ directory: process.cwd() }); - }); - - yargs.command("admin", "Build the admin app", {}, async () => { - return webiny.buildAdmin({ watch: false }); - }); - - yargs.command( - "api", - "Build API", - { ...envOption, ...watchOption }, - async ({ watch }) => { - return webiny.buildApi({ watch: Boolean(watch) }); - } - ); - }) - .command( - "deploy-api", - "Deploy API", - { ...envOption, preview: { type: "boolean", default: false } }, - () => { - console.log("Deploy API"); - // import("@webiny/deploy").then(m => m.default({ preview: args.preview })); - } - ) - .help() - .parse(); -}; diff --git a/packages-v6/cli/src/utils.ts b/packages-v6/cli/src/utils.ts deleted file mode 100644 index 5168feabae5..00000000000 --- a/packages-v6/cli/src/utils.ts +++ /dev/null @@ -1,50 +0,0 @@ -import path from "path"; -import { Node, Project, SourceFile, VariableDeclaration } from "ts-morph"; - -const extensions = [".js", ".ts", ".tsx"]; - -export const getModulePath = (modulePath: string) => { - const filePath = modulePath.replace(/\\/g, "/"); - if (extensions.includes(path.extname(filePath))) { - return filePath.split(".").slice(0, -1).join("."); - } - return filePath; -}; - -export const createMorphProject = (files: string[]) => { - const project = new Project(); - for (const file of files) { - project.addSourceFileAtPath(file); - } - return project; -}; - -export const getDeclaration = (name: string, source: SourceFile) => { - const declaration = source.getFirstDescendant(node => { - if (!Node.isVariableDeclaration(node)) { - return false; - } - - return node.getName() === name; - }) as VariableDeclaration; - - if (!declaration) { - throw Error(`Unable to find "${name}" declaration!`); - } - - return declaration; -}; - -export const getSourceFile = (project: Project, file: string) => { - if (!file) { - console.log("File variable not sent."); - return null; - } - - const source = project.getSourceFile(file); - if (source) { - return source; - } - - return null; -}; diff --git a/packages-v6/cli/tsconfig.build.json b/packages-v6/cli/tsconfig.build.json deleted file mode 100644 index fade0a52c5f..00000000000 --- a/packages-v6/cli/tsconfig.build.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "../../tsconfig.build.json", - "include": ["src"], - "references": [{ "path": "../core/tsconfig.build.json" }], - "compilerOptions": { - "rootDir": "./src", - "outDir": "./dist", - "declarationDir": "./dist", - "paths": { "~/*": ["./src/*"] }, - "baseUrl": "." - } -} diff --git a/packages-v6/cli/tsconfig.json b/packages-v6/cli/tsconfig.json deleted file mode 100644 index c8c9dfa393b..00000000000 --- a/packages-v6/cli/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["src", "__tests__/**/*.ts"], - "references": [{ "path": "../core" }], - "compilerOptions": { - "rootDirs": ["./src", "./__tests__"], - "outDir": "./dist", - "declarationDir": "./dist", - "paths": { - "~/*": ["./src/*"], - "@webiny/core/*": ["../core/src/*"], - "@webiny/core": ["../core/src"] - }, - "baseUrl": "." - } -} diff --git a/packages-v6/core/babel.config.js b/packages-v6/core/babel.config.js deleted file mode 100644 index 7859534ae7e..00000000000 --- a/packages-v6/core/babel.config.js +++ /dev/null @@ -1,23 +0,0 @@ -const sharedPresets = [require.resolve("@babel/preset-typescript")]; -const shared = { - presets: sharedPresets -}; - -module.exports = { - env: { - esm: shared, - cjs: { - ...shared, - presets: [ - [ - require.resolve("@babel/preset-env"), - { - modules: "commonjs" - } - ], - ...sharedPresets - ], - plugins: [[require.resolve("@babel/plugin-transform-runtime"), { useESModules: false }]] - } - } -}; diff --git a/packages-v6/core/package.json b/packages-v6/core/package.json deleted file mode 100644 index 1ca6367d265..00000000000 --- a/packages-v6/core/package.json +++ /dev/null @@ -1,117 +0,0 @@ -{ - "private": true, - "name": "@webiny/core", - "version": "0.0.0", - "types": "./lib/types/index.d.ts", - "exports": { - ".": { - "import": "./src/index.ts", - "require": "./src/index.ts" - } - }, - "dependencies": { - "@babel/core": "^7.17.5", - "@babel/plugin-transform-runtime": "^7.17.0", - "@babel/preset-env": "^7.16.11", - "@babel/preset-react": "^7.16.7", - "@babel/preset-typescript": "^7.16.7", - "@babel/runtime": "^7.17.2", - "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3", - "@svgr/webpack": "6.1.1", - "@webiny/global-config": "^5.33.5", - "@webiny/plugins": "^5.33.5", - "@webiny/pulumi-sdk-v6": "^5.33.5", - "@webiny/telemetry": "^5.33.5", - "address": "^1.1.2", - "babel-loader": "^8.2.3", - "case-sensitive-paths-webpack-plugin": "2.4.0", - "chalk": "^4.1.2", - "chokidar": "^3.5.3", - "css-loader": "6.5.1", - "css-minimizer-webpack-plugin": "3.2.0", - "detect-port-alt": "^1.1.6", - "dotenv": "^16.0.0", - "eslint": "^8.16.0", - "eslint-config-react-app": "^6.0.0", - "eslint-webpack-plugin": "^3.1.1", - "file-loader": "6.2.0", - "find-up": "5.0.0", - "fork-ts-checker-webpack-plugin": "^6.5.0", - "fs-extra": "^10.0.1", - "get-yarn-workspaces": "1.0.2", - "html-webpack-plugin": "^5.5.0", - "is-root": "^2.1.0", - "mini-css-extract-plugin": "2.4.5", - "postcss-flexbugs-fixes": "5.0.2", - "postcss-loader": "6.2.1", - "postcss-normalize": "10.0.1", - "postcss-preset-env": "7.0.1", - "prompts": "^2.4.2", - "raw-loader": "4.0.2", - "react": "^17.0.2", - "react-dev-utils": "12.0.0", - "react-dom": "^17.0.2", - "react-native-web": "0.12.3", - "react-refresh": "^0.11.0", - "read-json-sync": "2.0.1", - "resolve": "^1.22.0", - "resolve-url-loader": "4.0.0", - "sass": "1.44.0", - "sass-loader": "12.3.0", - "scheduler": "0.19.1", - "style-loader": "3.3.1", - "terser-webpack-plugin": "^5.3.1", - "ts-morph": "^13.0.3", - "ttypescript": "^1.5.12", - "typescript": "^4.1.3", - "url": "0.11.0", - "url-loader": "4.1.1", - "webpack": "5.68.0", - "webpack-bundle-analyzer": "^4.5.0", - "webpack-dev-server": "4.7.4", - "webpack-manifest-plugin": "4.0.2", - "webpackbar": "5.0.2" - }, - "devDependencies": { - "@babel/cli": "^7.17.0", - "@types/read-json-sync": "^2.0.0", - "@types/resolve": "^1.20.1", - "@types/webpack": "5.28.0", - "@types/webpack-dev-server": "^4.7.2", - "@types/webpack-env": "1.16.3", - "concurrently": "^7.0.0", - "rimraf": "3.0.2" - }, - "scripts": { - "build:esm": "cross-env BABEL_ENV=esm babel src --extensions '.ts,.tsx' --out-dir 'lib/esm' --source-maps --ignore='**/template/**' --copy-files", - "build:cjs": "cross-env BABEL_ENV=cjs babel src --extensions '.ts,.tsx' --out-dir 'lib/cjs' --source-maps --ignore='**/template/**' --copy-files", - "build": "yarn rimraf ./lib && yarn build:cjs && yarn build:esm && yarn declarations", - "declarations": "ttsc -p tsconfig.build.json" - }, - "webiny": { - "moduleTypes": [ - "cjs", - "esm" - ] - }, - "adio": { - "ignore": { - "src": [ - "@material/base", - "@webiny/admin" - ], - "dependencies": [ - "@babel/core", - "@babel/preset-react", - "@babel/plugin-syntax-object-rest-spread", - "@svgr/webpack", - "@types/webpack-env", - "babel-plugin-lodash", - "chalk", - "raw-loader", - "sass", - "webpack-bundle-analyzer" - ] - } - } -} diff --git a/packages-v6/core/src/artifacts/admin/index.ts b/packages-v6/core/src/artifacts/admin/index.ts deleted file mode 100644 index 08ceb5a2c2a..00000000000 --- a/packages-v6/core/src/artifacts/admin/index.ts +++ /dev/null @@ -1,114 +0,0 @@ -import fs from "fs-extra"; -import path from "path"; -import { createMorphProject, getSourceFile } from "../../utils"; -import { useWebiny } from "../../webiny"; -import { injectSourceFromPlugins } from "./injectSourceFromPlugins"; -import { BabelConfigModifier, WebpackConfigModifier } from "../bundle/config/webpack.config"; -import { Plugin, PluginAdminConfig } from "../../definePlugin"; - -interface Options { - watch: boolean; -} - -interface AdminPlugin extends Plugin { - admin: PluginAdminConfig; -} - -interface AdminConfigWithBabel extends PluginAdminConfig { - babel: BabelConfigModifier; -} - -interface AdminConfigWithWebpack extends PluginAdminConfig { - webpack: WebpackConfigModifier; -} - -interface AdminBabelPlugin extends AdminPlugin { - admin: AdminConfigWithBabel; -} - -interface AdminWebpackPlugin extends AdminPlugin { - admin: AdminConfigWithWebpack; -} - -function isAdminPlugin(plugin: Plugin | AdminPlugin): plugin is AdminPlugin { - return plugin.admin !== undefined; -} - -function hasBabelModifier(plugin: AdminPlugin | AdminBabelPlugin): plugin is AdminBabelPlugin { - return plugin.admin.babel !== undefined; -} - -function hasWebpackModifier( - plugin: AdminPlugin | AdminWebpackPlugin -): plugin is AdminWebpackPlugin { - return plugin.admin.webpack !== undefined; -} - -export async function buildAdmin({ watch }: Options) { - const webiny = useWebiny(); - const outputPath = webiny.getOutputPath(); - const adminPlugins = webiny.getPlugins().filter(isAdminPlugin); - - const generatedRoot = path.join(outputPath, "generated", "admin"); - const IndexJs = path.resolve(generatedRoot, "src", "index.tsx"); - const AppJs = path.resolve(generatedRoot, "src", "App.tsx"); - const Html = path.resolve(generatedRoot, "public", "index.html"); - - // Create base source - fs.copySync(__dirname + "/template", generatedRoot, { overwrite: true }); - - const project = createMorphProject([AppJs]); - - const source = getSourceFile(project, AppJs); - if (!source) { - throw Error("Missing admin App.tsx file."); - } - - injectSourceFromPlugins(source, adminPlugins); - await project.save(); - - // Switch to the directory where the generated code is located. - process.chdir(generatedRoot); - - const babelConfigModifier: BabelConfigModifier = config => { - return adminPlugins - .filter(hasBabelModifier) - .map(plugin => plugin.admin.babel) - .reduce((config, modifier) => modifier(config), config); - }; - - const webpackConfigModifier: WebpackConfigModifier = config => { - return adminPlugins - .filter(hasWebpackModifier) - .map(plugin => plugin.admin.webpack) - .reduce((config, modifier) => modifier(config), config); - }; - - if (watch) { - // Watch the app! - const { watchApp } = await import("../bundle/watchApp"); - - // Return a Promise that will never be resolved, to keep the process running. - return new Promise(() => { - watchApp({ - cwd: generatedRoot, - entry: IndexJs, - html: Html, - babelConfigModifier, - webpackConfigModifier - }); - }); - } - - // Build the app! - const { buildApp } = await import("../bundle/buildApp"); - - await buildApp({ - cwd: generatedRoot, - entry: IndexJs, - html: Html, - output: path.join(outputPath, "dist", "admin"), - babelConfigModifier, - webpackConfigModifier - }); -} diff --git a/packages-v6/core/src/artifacts/admin/injectSourceFromPlugins.ts b/packages-v6/core/src/artifacts/admin/injectSourceFromPlugins.ts deleted file mode 100644 index cb3e4e30734..00000000000 --- a/packages-v6/core/src/artifacts/admin/injectSourceFromPlugins.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { ArrayLiteralExpression, SourceFile } from "ts-morph"; -import { Plugin } from "../../index"; -import { getDeclaration, getModulePath } from "../../utils"; - -export function injectSourceFromPlugins(source: SourceFile, plugins: Plugin[]) { - const configModifiers = getDeclaration("configModifiers", source); - const pluginsModifiers = getDeclaration("pluginsModifiers", source); - - const configModifiersArray = configModifiers.getInitializer() as ArrayLiteralExpression; - const pluginsModifiersArray = pluginsModifiers.getInitializer() as ArrayLiteralExpression; - - [...plugins].reverse().forEach(plugin => { - const appConfig = plugin.admin!; - const factoryName = `create${plugin.name}`; - - if (appConfig.plugin) { - source.addImportDeclaration({ - defaultImport: factoryName, - moduleSpecifier: getModulePath(appConfig.plugin) - }); - - pluginsModifiersArray.addElement(`${factoryName}(config)`); - } - - if (appConfig.config) { - const configModifierName = `${factoryName}Config`; - - source.addImportDeclaration({ - defaultImport: configModifierName, - moduleSpecifier: getModulePath(appConfig.config) - }); - - configModifiersArray.addElement(configModifierName); - } - }); -} diff --git a/packages-v6/core/src/artifacts/admin/template/package.json b/packages-v6/core/src/artifacts/admin/template/package.json deleted file mode 100644 index 5b6a5cc21a7..00000000000 --- a/packages-v6/core/src/artifacts/admin/template/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "admin", - "version": "0.1.0", - "private": true, - "browserslist": { - "development": [ - "last 2 chrome versions", - "last 2 firefox versions", - "last 2 edge versions" - ], - "production": [ - ">0.25%", - "not op_mini all", - "ie 11" - ] - } -} diff --git a/packages-v6/core/src/artifacts/admin/template/public/index.html b/packages-v6/core/src/artifacts/admin/template/public/index.html deleted file mode 100644 index c5dc3828370..00000000000 --- a/packages-v6/core/src/artifacts/admin/template/public/index.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - webpack App - - -
- - diff --git a/packages-v6/core/src/artifacts/admin/template/src/App.tsx b/packages-v6/core/src/artifacts/admin/template/src/App.tsx deleted file mode 100644 index e685eca661c..00000000000 --- a/packages-v6/core/src/artifacts/admin/template/src/App.tsx +++ /dev/null @@ -1,38 +0,0 @@ -import React from "react"; -import { Admin } from "@webiny/admin"; -import { composeAsync, AdminConfig, ConfigModifier, PluginsModifier } from "@webiny/core"; - -const Bootstrap = React.lazy( - () => - new Promise<{ default: React.ComponentType }>(async resolve => { - // Config phase (ADD GENERATED CONFIG MODIFIERS HERE!) - const configModifiers: ConfigModifier[] = []; - - console.log("Loading configs... 12345"); - const config = await composeAsync(configModifiers)({} as AdminConfig); - - // Generated plugins (ADD GENERATED PLUGINS MODIFIERS HERE!) - const pluginsModifiers: PluginsModifier[] = []; - - console.log("Loading plugins..."); - const plugins = await composeAsync(pluginsModifiers)([]); - - console.log(config, plugins); - - resolve({ - default: () => ( - - {plugins.map((element, key) => React.cloneElement(element, { key }))} - - ) - }); - }) -); - -export const App = () => { - return ( - - - - ); -}; diff --git a/packages-v6/core/src/artifacts/admin/template/src/index.tsx b/packages-v6/core/src/artifacts/admin/template/src/index.tsx deleted file mode 100644 index 56ee8da053e..00000000000 --- a/packages-v6/core/src/artifacts/admin/template/src/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import React from "react"; -import ReactDOM from "react-dom"; -import { App } from "./App"; - -ReactDOM.render(, document.getElementById("root")); diff --git a/packages-v6/core/src/artifacts/admin/template/tsconfig.json b/packages-v6/core/src/artifacts/admin/template/tsconfig.json deleted file mode 100644 index b41c77e1d02..00000000000 --- a/packages-v6/core/src/artifacts/admin/template/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../../tsconfig", - "include": ["src"], - "compilerOptions": { - "composite": false - } -} diff --git a/packages-v6/core/src/artifacts/bundle/buildApp.ts b/packages-v6/core/src/artifacts/bundle/buildApp.ts deleted file mode 100644 index 5769aada8a7..00000000000 --- a/packages-v6/core/src/artifacts/bundle/buildApp.ts +++ /dev/null @@ -1,215 +0,0 @@ -import fs from "fs-extra"; -import webpack from "webpack"; -// @ts-ignore -import chalk from "react-dev-utils/chalk"; -// @ts-ignore -import checkRequiredFiles from "react-dev-utils/checkRequiredFiles"; -// @ts-ignore -import formatWebpackMessages from "react-dev-utils/formatWebpackMessages"; -// @ts-ignore -import FileSizeReporter from "react-dev-utils/FileSizeReporter"; -// @ts-ignore -import printBuildError from "react-dev-utils/printBuildError"; -// @ts-ignore -import { checkBrowsers } from "react-dev-utils/browsersHelper"; -import { applyDefaults } from "./utils"; -import getPaths, { Paths } from "./config/paths"; -import { useWebiny } from "../../webiny"; -import { Logger } from "../../utils/logger"; -import { BabelConfigModifier, WebpackConfigModifier } from "./config/webpack.config"; - -export interface BuildOptions { - cwd: string; - entry: string; - html: string; - output: string; - babelConfigModifier: BabelConfigModifier; - webpackConfigModifier: WebpackConfigModifier; -} - -export const buildApp = async (options: BuildOptions) => { - applyDefaults(); - const { logger } = useWebiny(); - - process.env.NODE_ENV = "production"; - const paths = getPaths({ appIndexJs: options.entry, cwd: options.cwd }); - - // Makes the script crash on unhandled rejections instead of silently - // ignoring them. In the future, promise rejections that are not handled will - // terminate the Node.js process with a non-zero exit code. - process.on("unhandledRejection", err => { - throw err; - }); - - // Ensure environment variables are read. - const { createWebpackConfig } = await import("./config/webpack.config"); - - const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild; - const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; - - // These sizes are pretty large. We'll warn for bundles exceeding them. - const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024; - const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024; - - const isInteractive = process.stdout.isTTY; - - // Warn and crash if required files are missing - if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); - } - - // We require that you explicitly set browsers and do not fall back to browsers list defaults. - await checkBrowsers(paths.appPath, isInteractive); - - // Generate configuration - paths.appBuild = options.output; - let config = createWebpackConfig(process.env.NODE_ENV, { - paths, - babelConfigModifier: options.babelConfigModifier - }); - - // Apply webpack modifiers - if (options.webpackConfigModifier) { - config = options.webpackConfigModifier(config); - } - // First, read the current file sizes in build directory. - // This lets us display how much they changed later. - const existingFileSizes = await measureFileSizesBeforeBuild(paths.appBuild); - - // Remove all content but keep the directory so that - // if you're in it, you don't end up in Trash - fs.emptyDirSync(paths.appBuild); - - // Merge with the public folder - copyPublicFolder(paths); - - // Start the webpack build - try { - const { stats, previousFileSizes, warnings } = await build({ - config, - previousFileSizes: existingFileSizes, - logger - }); - if (warnings.length) { - logger.warning("Compiled with warnings.\n"); - logger.log(warnings.join("\n\n")); - logger.log( - "\nSearch for the " + - chalk.underline(chalk.yellow("keywords")) + - " to learn more about each warning." - ); - logger.log( - "To ignore, add " + - chalk.cyan("// eslint-disable-next-line") + - " to the line before.\n" - ); - } else { - logger.success("Compiled successfully.\n"); - } - - logger.log("File sizes after gzip:\n"); - printFileSizesAfterBuild( - stats, - previousFileSizes, - paths.appBuild, - WARN_AFTER_BUNDLE_GZIP_SIZE, - WARN_AFTER_CHUNK_GZIP_SIZE - ); - logger.log("\n"); - } catch (err) { - const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === "true"; - if (tscCompileOnError) { - logger.warning( - "Compiled with the following type errors (you may want to check these before deploying your app):\n" - ); - printBuildError(err); - } else { - logger.error(err); - logger.error("Failed to compile.\n"); - printBuildError(err); - process.exit(1); - } - } -}; - -// Create the production build and print the deployment instructions. -interface BuildParams { - config: webpack.Configuration; - previousFileSizes: FileSizeReporter.OpaqueFileSizes; - logger: Logger; -} - -interface BuildOutput { - stats: webpack.Stats; - previousFileSizes: FileSizeReporter.OpaqueFileSizes; - warnings: string[]; -} - -function build({ config, previousFileSizes, logger }: BuildParams): Promise { - const compiler = webpack(config); - - return new Promise((resolve, reject) => { - compiler.run((err, stats) => { - let messages; - if (err) { - if (!err.message) { - return reject(err); - } - - let errMessage = err.message; - - // Add additional information for postcss errors - if (err.hasOwnProperty("postcssNode")) { - // @ts-ignore - const selector = err["postcssNode"].selector; - errMessage += "\nCompileError: Begins at CSS selector " + selector; - } - - messages = formatWebpackMessages({ - errors: [errMessage], - warnings: [] - }); - } else { - messages = formatWebpackMessages( - stats!.toJson({ - all: false, - warnings: true, - errors: true - }) - ); - } - if (Array.isArray(messages.errors) && messages.errors.length) { - // Only keep the first error. Others are often indicative - // of the same problem, but confuse the reader with noise. - if (messages.errors.length > 1) { - messages.errors.length = 1; - } - return reject(new Error(messages.errors.join("\n\n"))); - } - if ( - process.env.CI && - (typeof process.env.CI !== "string" || process.env.CI.toLowerCase() !== "false") && - messages.warnings.length - ) { - logger.warning( - "\nTreating warnings as errors because process.env.CI = true.\n" + - "Most CI servers set it automatically.\n" - ); - return reject(new Error(messages.warnings.join("\n\n"))); - } - - return resolve({ - stats: stats!, - previousFileSizes, - warnings: messages.warnings - }); - }); - }); -} - -function copyPublicFolder(paths: Paths) { - fs.copySync(paths.appPublic, paths.appBuild, { - dereference: true, - filter: file => file !== paths.appHtml - }); -} diff --git a/packages-v6/core/src/artifacts/bundle/config/ModuleGraphPlugin.ts b/packages-v6/core/src/artifacts/bundle/config/ModuleGraphPlugin.ts deleted file mode 100644 index 1cd11c44eaf..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/ModuleGraphPlugin.ts +++ /dev/null @@ -1,148 +0,0 @@ -// noinspection JSVoidFunctionReturnValueUsed - -import webpack from "webpack"; -import fs from "fs-extra"; -import { resolve, dirname } from "path"; -import readJson from "read-json-sync"; -import { watch } from "chokidar"; -import { tsCompile, babelCompile } from "./buildFile"; -// @ts-ignore -import getPackages from "get-yarn-workspaces"; -import { WebpackError } from "webpack"; -import { useWebiny } from "../../../webiny"; -import { Webiny } from "../../../types"; - -const workspaces = getPackages() as string[]; - -export class ModuleGraphPlugin { - private toWatch: Set = new Set(); - private fileMap: Map = new Map(); - private compilation: webpack.Compilation | null = null; - private devServerTap: { fn: Function } | null = null; - private checkTs: null | (() => Promise) = null; - private webiny: Webiny; - - constructor() { - this.webiny = useWebiny(); - } - - private async buildFile(path: string) { - const file = path.replace(/\\/g, "/"); - this.webiny.logger.debug("Changed file", this.webiny.logger.debug.hl(file)); - const workspace = workspaces.find(workspace => file.startsWith(workspace)); - - if (!workspace) { - this.webiny.logger.warning(`Workspace not found! Can't build file.`); - return; - } - - const destination = this.fileMap.get(file); - if (!destination) { - this.webiny.logger.warning(`Destination for ${file} was not found.`); - return; - } - - try { - await babelCompile({ workspace, source: file, destination }); - if (file.endsWith(".ts") || file.endsWith(".tsx")) { - this.checkTs = async () => { - if (!this.compilation) { - return; - } - - this.webiny.logger.debug( - `Checking types for ${this.webiny.logger.debug.hl(file)}...` - ); - try { - await tsCompile({ workspace, source: file }); - } catch (err) { - this.compilation.errors.push(this.formatError(file, err)); - } - }; - } - } catch (err) { - console.log(err); - this.showError(path, err); - } - } - - private formatError(file: string, err: Error): WebpackError { - const error = new WebpackError(err.message); - error.hideStack = true; - error.file = file; - return error; - } - - private showError(file: string, err: Error) { - if (!this.devServerTap || !this.compilation) { - return; - } - const error = this.formatError(file, err); - - // @ts-ignore - const stats = this.compilation.getStats(); - stats.compilation.errors.push(error); - this.devServerTap.fn(stats); - } - - apply(compiler: webpack.Compiler) { - const className = this.constructor.name; - const skip = [".artifacts", "node_modules", "data:"]; - - const watcher = watch([]); - watcher - .on("change", path => { - this.buildFile(path); - }) - .on("error", error => { - console.log(`Watcher error: ${error}`); - }); - - compiler.hooks.done.intercept({ - register: tap => { - if (tap.name === "webpack-dev-server" && tap.type === "sync") { - this.devServerTap = tap; - } - return tap; - } - }); - - compiler.hooks.afterCompile.tapPromise(className, async () => { - if (this.checkTs) { - await this.checkTs(); - } - }); - - compiler.hooks.compilation.tap(className, compilation => { - this.compilation = compilation; - compilation.hooks.finishModules.tap(className, modules => { - const normalModules = modules as Iterable; - Array.from(normalModules) - .filter(m => { - return m.resource && !skip.some(part => m.resource.includes(part)); - }) - .map(m => m.resource.replace(/\\/g, "/")) - .filter(m => !this.toWatch.has(m)) - .forEach(file => { - // Map module file to original source file - const sourceMap = `${file}.map`; - if (fs.existsSync(sourceMap)) { - const content = readJson(sourceMap); - const originalFile = resolve( - dirname(sourceMap), - content.sources[0] - ).replace(/\\/g, "/"); - - this.fileMap.set(file, originalFile); - this.fileMap.set(originalFile, file); - this.toWatch.add(originalFile); - watcher.add(originalFile); - } else { - this.toWatch.add(file); - watcher.add(file); - } - }); - }); - }); - } -} diff --git a/packages-v6/core/src/artifacts/bundle/config/WebpackDevServerUtils.ts b/packages-v6/core/src/artifacts/bundle/config/WebpackDevServerUtils.ts deleted file mode 100644 index 86f56a3210c..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/WebpackDevServerUtils.ts +++ /dev/null @@ -1,141 +0,0 @@ -import chalk from "chalk"; -// @ts-ignore -import detect from "detect-port-alt"; -import isRoot from "is-root"; -// @ts-ignore -import prompts from "prompts"; -import { getProcessForPort } from "./getProcessForPort"; -import webpack from "webpack"; -import { URLs } from "./prepareUrls"; - -const isInteractive = process.stdout.isTTY; - -function clearConsole() { - process.stdout.write(process.platform === "win32" ? "\x1B[2J\x1B[0f" : "\x1B[2J\x1B[3J\x1B[H"); -} - -export function printInstructions(appName: string, urls: URLs) { - console.log(); - console.log(`You can now view ${chalk.bold(appName)} in the browser.`); - console.log(); - - console.log(` ${chalk.bold("Local:")} ${urls.localUrlForTerminal}`); - console.log(` ${chalk.bold("On Your Network:")} ${urls.lanUrlForTerminal}`); - - console.log(); - console.log("Note that the development build is not optimized."); - console.log(`To create a production build, use ` + `${chalk.cyan(`yarn build`)}.`); - console.log(); -} - -interface CreateCompiler { - appName: string; - config: webpack.Configuration; - urls: URLs; - webpack: typeof webpack; -} - -export function createCompiler({ appName, config, urls, webpack }: CreateCompiler) { - // "Compiler" is a low-level interface to webpack. - // It lets us listen to some events and provide our own custom messages. - let compiler; - try { - compiler = webpack(config); - } catch (err) { - console.log(chalk.red("Failed to compile.")); - console.log(); - console.log(err.message || err); - console.log(); - process.exit(1); - } - - // "invalid" event fires when you have changed a file, and webpack is - // recompiling a bundle. WebpackDevServer takes care to pause serving the - // bundle, so if you refresh, it'll wait instead of serving the old one. - // "invalid" is short for "bundle invalidated", it doesn't imply any errors. - compiler.hooks.invalid.tap("invalid", () => { - if (isInteractive) { - clearConsole(); - } - }); - - let isFirstCompile = true; - - // "done" event fires when webpack has finished recompiling the bundle. - // Whether or not you have warnings or errors, you will get this event. - compiler.hooks.done.tap("done", async stats => { - const statsData = stats.toJson({ - all: false, - warnings: true, - errors: true - }); - - if (isInteractive) { - clearConsole(); - } - - if (statsData?.errors?.length) { - console.log(); - } - - const isSuccessful = !statsData?.errors?.length && !statsData?.warnings?.length; - - if (isSuccessful && (isInteractive || isFirstCompile)) { - printInstructions(appName, urls); - } - isFirstCompile = false; - }); - - return compiler; -} - -export function choosePort(host: string, defaultPort: number) { - return detect(defaultPort, host).then( - (port: number) => - new Promise(resolve => { - if (port === defaultPort) { - return resolve(port); - } - const message = - process.platform !== "win32" && defaultPort < 1024 && !isRoot() - ? `Admin permissions are required to run a server on a port below 1024.` - : `Something is already running on port ${defaultPort}.`; - if (isInteractive) { - clearConsole(); - const existingProcess = getProcessForPort(defaultPort); - const question = { - type: "confirm", - name: "shouldChangePort", - message: - chalk.yellow( - message + - `${existingProcess ? ` Probably:\n ${existingProcess}` : ""}` - ) + "\n\nWould you like to run the app on another port instead?", - initial: true - }; - prompts(question).then( - ({ shouldChangePort }: { shouldChangePort: boolean }) => { - if (shouldChangePort) { - resolve(port); - } else { - resolve(null); - } - } - ); - } else { - console.log(chalk.red(message)); - resolve(null); - } - }), - (err: Error) => { - throw new Error( - [ - chalk.red(`Could not find an open port at ${chalk.bold(host)}.`), - "\n", - "Network error message: " + err.message, - "\n" - ].join("") - ); - } - ); -} diff --git a/packages-v6/core/src/artifacts/bundle/config/buildFile.ts b/packages-v6/core/src/artifacts/bundle/config/buildFile.ts deleted file mode 100644 index cbf2195101a..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/buildFile.ts +++ /dev/null @@ -1,128 +0,0 @@ -import fs from "fs-extra"; -import { join, extname, relative } from "path"; -import { transformFileAsync } from "@babel/core"; -import ts from "ttypescript"; -import { ParsedCommandLine } from "typescript"; - -const BABEL_COMPILE_EXTENSIONS = [".js", ".jsx", ".ts", ".tsx"]; - -interface BabelCompile { - source: string; - destination: string; - workspace: string; -} - -interface BuildVariant { - source: string; - workspace: string; - variant: string; -} - -async function buildVariant({ variant, source, workspace }: BuildVariant) { - const { code, map } = (await transformFileAsync(source, { - envName: variant, - cwd: workspace, - sourceMaps: true - })) as babel.BabelFileResult; - - const mapJson = JSON.stringify(map); - - const destination = join( - workspace, - "lib", - variant, - relative(workspace + "/src", source) - ).replace(/\.tsx?$/, ".js"); - - await Promise.all([ - fs.writeFile(destination, code, "utf8"), - fs.writeFile(destination + ".map", mapJson, "utf8") - ]); -} - -export async function babelCompile({ source, destination, workspace }: BabelCompile) { - if (BABEL_COMPILE_EXTENSIONS.includes(extname(source))) { - // const start = Date.now(); - - await Promise.all([ - buildVariant({ - variant: "esm", - source, - workspace - }), - buildVariant({ - variant: "cjs", - source, - workspace - }) - ]); - - // const duration = (Date.now() - start) / 1000; - // console.log(`Babel compiled in ${duration}s`); - return; - } - - return fs.copyFile(source, destination); -} - -const tsProgramCache: Map = new Map(); - -interface TsCompile { - source: string; - workspace: string; -} - -export async function tsCompile({ source, workspace }: TsCompile) { - // const start = Date.now(); - - let parsedJsonConfigFile = tsProgramCache.get(workspace); - - if (!parsedJsonConfigFile) { - const { config: readTsConfig } = ts.readConfigFile( - join(workspace, "tsconfig.build.json"), - ts.sys.readFile - ); - - parsedJsonConfigFile = ts.parseJsonConfigFileContent(readTsConfig, ts.sys, workspace); - } - - const { projectReferences, options, errors } = parsedJsonConfigFile; - - const program = ts.createProgram({ - projectReferences, - options: { ...options, skipLibCheck: true }, - rootNames: [source], - configFileParsingDiagnostics: errors - }); - - const { diagnostics, emitSkipped } = program.emit(); - const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(diagnostics, errors); - - if (allDiagnostics.length) { - const formatHost = { - getCanonicalFileName(path: string) { - return path; - }, - getCurrentDirectory() { - return workspace; - }, - getNewLine() { - return ts.sys.newLine; - } - }; - - const message = ts.formatDiagnostics(allDiagnostics, formatHost); - if (message) { - // const duration = (Date.now() - start) / 1000; - // console.log(`TS compiled with errors in ${duration}s`); - throw Error(message); - } - } - - if (emitSkipped) { - throw Error("TypeScript compilation failed."); - } - - // const duration = (Date.now() - start) / 1000; - // console.log(`TS compiled in ${duration}s`); -} diff --git a/packages-v6/core/src/artifacts/bundle/config/env.ts b/packages-v6/core/src/artifacts/bundle/config/env.ts deleted file mode 100644 index 37531365756..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/env.ts +++ /dev/null @@ -1,54 +0,0 @@ -import fs from "fs"; -import path from "path"; - -const NODE_ENV = process.env.NODE_ENV; -if (!NODE_ENV) { - throw new Error("The NODE_ENV environment variable is required but was not specified."); -} - -// We support resolving modules according to `NODE_PATH`. -// This lets you use absolute paths in imports inside large monorepos: -// https://github.com/facebook/create-react-app/issues/253. -// It works similar to `NODE_PATH` in Node itself: -// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders -// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored. -// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims. -// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421 -// We also resolve them to make sure all tools using them work consistently. -const appDirectory = fs.realpathSync(process.cwd()); -process.env.NODE_PATH = (process.env.NODE_PATH || "") - .split(path.delimiter) - .filter(folder => folder && !path.isAbsolute(folder)) - .map(folder => path.resolve(appDirectory, folder)) - .join(path.delimiter); - -// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be -// injected into the application via DefinePlugin in Webpack configuration. -const REACT_APP = /^REACT_APP_/i; - -interface Env { - [key: string]: string; -} - -export function getClientEnvironment(publicUrl: string) { - const raw = Object.keys(process.env) - .filter(key => REACT_APP.test(key)) - .reduce((env, key) => ({ ...env, [key]: process.env[key] as string }), { - // Useful for determining whether we’re running in production mode. - // Most importantly, it switches React into the correct mode. - NODE_ENV: process.env.NODE_ENV || "development", - // Useful for resolving the correct path to static assets in `public`. - // For example, . - // This should only be used as an escape hatch. Normally you would put - // images into the `src` and `import` them in code to get their paths. - PUBLIC_URL: publicUrl - }); - - // Stringify all values so we can feed into Webpack DefinePlugin - const stringified: Record = {}; - for (const key of Object.keys(raw)) { - stringified[`process.env.${key}`] = JSON.stringify(raw[key]); - } - - return { raw, stringified }; -} diff --git a/packages-v6/core/src/artifacts/bundle/config/getProcessForPort.ts b/packages-v6/core/src/artifacts/bundle/config/getProcessForPort.ts deleted file mode 100644 index acf5c3f3f5b..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/getProcessForPort.ts +++ /dev/null @@ -1,76 +0,0 @@ -import chalk from "chalk"; -import { execSync, execFileSync, ExecFileSyncOptions, ExecSyncOptions } from "child_process"; -import path from "path"; - -const execOptions = { - encoding: "utf8", - stdio: [ - "pipe", // stdin (default) - "pipe", // stdout (default) - "ignore" //stderr - ] -}; - -function isProcessAReactApp(processCommand: string) { - return /^node .*react-scripts\/scripts\/start\.js\s?$/.test(processCommand); -} - -function getProcessIdOnPort(port: number) { - const output = execFileSync( - "lsof", - ["-i:" + port, "-P", "-t", "-sTCP:LISTEN"], - execOptions as ExecFileSyncOptions - ) as string; - - return output.split("\n")[0].trim(); -} - -function getPackageNameInDirectory(directory: string) { - const packagePath = path.join(directory.trim(), "package.json"); - - try { - return require(packagePath).name; - } catch (e) { - return null; - } -} - -function getProcessCommand(processId: string, processDirectory: string) { - let command = execSync( - "ps -o command -p " + processId + " | sed -n 2p", - execOptions as ExecSyncOptions - ) as string; - - command = command.replace(/\n$/, ""); - - if (isProcessAReactApp(command)) { - const packageName = getPackageNameInDirectory(processDirectory); - return packageName ? packageName : command; - } - return command; -} - -function getDirectoryOfProcessById(processId: string) { - const output = execSync( - "lsof -p " + processId + ' | awk \'$4=="cwd" {for (i=9; i<=NF; i++) printf "%s ", $i}\'', - execOptions as ExecSyncOptions - ) as string; - - return output.trim(); -} - -export function getProcessForPort(port: number) { - try { - const processId = getProcessIdOnPort(port); - const directory = getDirectoryOfProcessById(processId); - const command = getProcessCommand(processId, directory); - return ( - chalk.cyan(command) + - chalk.grey(" (pid " + processId + ")\n") + - chalk.blue(" in ") + - chalk.cyan(directory) - ); - } catch (e) { - return null; - } -} diff --git a/packages-v6/core/src/artifacts/bundle/config/modules.ts b/packages-v6/core/src/artifacts/bundle/config/modules.ts deleted file mode 100644 index 7b1c701dc85..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/modules.ts +++ /dev/null @@ -1,83 +0,0 @@ -import fs from "fs"; -import path from "path"; -// @ts-ignore -import chalk from "react-dev-utils/chalk"; -import resolve from "resolve"; -import { Paths } from "./paths"; - -/** - * Get additional module paths based on the baseUrl of a compilerOptions object. - */ -function getAdditionalModulePaths(options: { baseUrl?: string } = {}, paths: Paths) { - const baseUrl = options.baseUrl; - - // We need to explicitly check for null and undefined (and not a falsy value) because - // TypeScript treats an empty string as `.`. - if (baseUrl == null) { - // If there's no baseUrl set we respect NODE_PATH - // Note that NODE_PATH is deprecated and will be removed - // in the next major release of create-react-app. - - const nodePath = process.env.NODE_PATH || ""; - return nodePath.split(path.delimiter).filter(Boolean); - } - - const baseUrlResolved = path.resolve(paths.appPath, baseUrl); - - // We don't need to do anything if `baseUrl` is set to `node_modules`. This is - // the default behavior. - if (path.relative(paths.appNodeModules, baseUrlResolved) === "") { - return null; - } - - // Allow the user set the `baseUrl` to `appSrc`. - if (path.relative(paths.appSrc, baseUrlResolved) === "") { - return [paths.appSrc]; - } - - // If the path is equal to the root directory we ignore it here. - // We don't want to allow importing from the root directly as source files are - // not transpiled outside of `src`. We do allow importing them with the - // absolute path (e.g. `src/Components/Button.js`) but we set that up with - // an alias. - if (path.relative(paths.appPath, baseUrlResolved) === "") { - return null; - } - - // Otherwise, throw an error. - throw new Error( - chalk.red.bold( - "Your project's `baseUrl` can only be set to `src` or `node_modules`." + - " Create React App does not support other values at this time." - ) - ); -} - -function getModules(paths: Paths) { - // Check if TypeScript is setup - const hasTsConfig = fs.existsSync(paths.appTsConfig); - - let config; - - // If there's a tsconfig.json we assume it's a - // TypeScript project and set up the config - // based on tsconfig.json - if (hasTsConfig) { - const ts = require(resolve.sync("typescript", { - basedir: paths.appNodeModules - })); - config = ts.readConfigFile(paths.appTsConfig, ts.sys.readFile).config; - } - - config = config || {}; - const options = config.compilerOptions || {}; - - const additionalModulePaths = getAdditionalModulePaths(options, paths); - - return { - additionalModulePaths: additionalModulePaths, - hasTsConfig - }; -} - -export default ({ paths }: { paths: Paths }) => getModules(paths); diff --git a/packages-v6/core/src/artifacts/bundle/config/paths.ts b/packages-v6/core/src/artifacts/bundle/config/paths.ts deleted file mode 100644 index c9c7f5edb19..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/paths.ts +++ /dev/null @@ -1,55 +0,0 @@ -import path from "path"; -import fs from "fs"; -// @ts-ignore -import getWorkspaces from "get-yarn-workspaces"; - -const isFolder = (p: string) => fs.statSync(p).isDirectory(); -const fixPath = (pkg: string) => pkg.replace(/\//g, path.sep); - -const allWorkspaces = () => { - return (getWorkspaces() as string[]).filter(isFolder).map(fixPath); -}; - -interface Params { - appIndexJs: string; - cwd: string; -} - -export interface Paths { - appPath: string; - appBuild: string; - appPublic: string; - appHtml: string; - appIndexJs: string; - appPackageJson: string; - appSrc: string; - appTsConfig: string; - yarnLockFile: string; - appNodeModules: string; - publicUrl: string; - servedPath: string; - allWorkspaces: string[]; -} - -export default ({ appIndexJs, cwd }: Params): Paths => { - // Make sure any symlinks in the project folder are resolved: - // https://github.com/facebook/create-react-app/issues/637 - const appDirectory = fs.realpathSync(cwd); - const resolveApp = (relativePath: string) => path.resolve(appDirectory, relativePath); - - return { - appPath: resolveApp("."), - appBuild: resolveApp("build"), - appPublic: resolveApp("public"), - appHtml: resolveApp("public/index.html"), - appIndexJs: appIndexJs, - appPackageJson: resolveApp("package.json"), - appSrc: resolveApp("src"), - appTsConfig: resolveApp("tsconfig.json"), - yarnLockFile: resolveApp("yarn.lock"), - appNodeModules: resolveApp("node_modules"), - publicUrl: "/", - servedPath: "/", - allWorkspaces: allWorkspaces() - }; -}; diff --git a/packages-v6/core/src/artifacts/bundle/config/prepareUrls.ts b/packages-v6/core/src/artifacts/bundle/config/prepareUrls.ts deleted file mode 100644 index b9148f1b591..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/prepareUrls.ts +++ /dev/null @@ -1,66 +0,0 @@ -import address from "address"; -import url from "url"; -import chalk from "chalk"; - -export interface URLs { - lanUrlForConfig: string; - lanUrlForTerminal: string | undefined; - localUrlForTerminal: string; - localUrlForBrowser: string; -} - -export function prepareUrls(protocol: string, host: string, port: number, pathname = "/"): URLs { - const formatUrl = (hostname: string) => { - return url.format({ - protocol, - hostname, - port, - pathname - }); - }; - - const prettyPrintUrl = (hostname: string): string => { - return url.format({ - protocol, - hostname, - port: chalk.bold(port), - pathname - }); - }; - - const isUnspecifiedHost = host === "0.0.0.0" || host === "::"; - let prettyHost, lanUrlForConfig, lanUrlForTerminal; - - if (isUnspecifiedHost) { - prettyHost = "localhost"; - try { - // This can only return an IPv4 address - lanUrlForConfig = address.ip(); - if (lanUrlForConfig) { - // Check if the address is a private ip - // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces - if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(lanUrlForConfig)) { - // Address is private, format it for later use - lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig); - } else { - // Address is not private, so we will discard it - lanUrlForConfig = undefined; - } - } - } catch (_e) { - // ignored - } - } else { - prettyHost = host; - } - - const localUrlForTerminal = prettyPrintUrl(prettyHost); - const localUrlForBrowser = formatUrl(prettyHost); - - return { - lanUrlForConfig, - lanUrlForTerminal, - localUrlForTerminal, - localUrlForBrowser - }; -} diff --git a/packages-v6/core/src/artifacts/bundle/config/webpack.config.ts b/packages-v6/core/src/artifacts/bundle/config/webpack.config.ts deleted file mode 100644 index 5124ab0185e..00000000000 --- a/packages-v6/core/src/artifacts/bundle/config/webpack.config.ts +++ /dev/null @@ -1,650 +0,0 @@ -import path from "path"; -import webpack from "webpack"; -import HtmlWebpackPlugin from "html-webpack-plugin"; -// @ts-ignore -import CaseSensitivePathsPlugin from "case-sensitive-paths-webpack-plugin"; -import TerserPlugin from "terser-webpack-plugin"; -// @ts-ignore -import MiniCssExtractPlugin from "mini-css-extract-plugin"; -import CssMinimizerPlugin from "css-minimizer-webpack-plugin"; -import { WebpackManifestPlugin } from "webpack-manifest-plugin"; -// @ts-ignore -import InlineChunkHtmlPlugin from "react-dev-utils/InlineChunkHtmlPlugin"; -// @ts-ignore -import InterpolateHtmlPlugin from "react-dev-utils/InterpolateHtmlPlugin"; -// @ts-ignore -import getCSSModuleLocalIdent from "react-dev-utils/getCSSModuleLocalIdent"; -// @ts-ignore -import ModuleNotFoundPlugin from "react-dev-utils/ModuleNotFoundPlugin"; -import { getClientEnvironment } from "./env"; -import ESLintPlugin from "eslint-webpack-plugin"; -import ForkTsCheckerWebpackPlugin from "fork-ts-checker-webpack-plugin"; -import WebpackBar from "webpackbar"; -import ReactRefreshWebpackPlugin from "@pmmmwh/react-refresh-webpack-plugin"; -import { Paths } from "./paths"; -import getModules from "./modules"; -import { ModuleGraphPlugin } from "./ModuleGraphPlugin"; - -const materialNodeModules = require.resolve("@material/base/package.json").split("@material")[0]; -const sassIncludePaths = [ - path.resolve("./src"), - path.resolve("./node_modules"), - materialNodeModules -]; - -// Generates a unique static folder name, for example "static-mi7aan0cqpo". -const STATIC_FOLDER = "static"; - -// 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 imageInlineSizeLimit = parseInt(process.env.IMAGE_INLINE_SIZE_LIMIT || "10000"); - -// style files regexes -const cssRegex = /\.css$/; -const cssModuleRegex = /\.module\.css$/; -const sassRegex = /\.(scss|sass)$/; -const sassModuleRegex = /\.module\.(scss|sass)$/; -const sassLoader = { - loader: require.resolve("sass-loader"), - options: { - sourceMap: true, - sassOptions: { - includePaths: sassIncludePaths, - quietDeps: true - } - } -}; - -export interface BabelConfig { - [key: string]: any; -} - -export interface BabelConfigModifier { - (config: BabelConfig): BabelConfig; -} - -export interface WebpackConfigModifier { - (config: webpack.Configuration): webpack.Configuration; -} - -interface CreateWebpackConfigParams { - paths: Paths; - babelConfigModifier?: BabelConfigModifier; -} - -interface CreateWebpackConfig { - (webpackEnv: string, params: CreateWebpackConfigParams): webpack.Configuration; -} - -export const createWebpackConfig: CreateWebpackConfig = ( - webpackEnv, - { paths, babelConfigModifier } -): webpack.Configuration => { - const isEnvDevelopment = webpackEnv === "development"; - const isEnvProduction = webpackEnv === "production"; - - const modules = getModules({ paths }); - - if (!babelConfigModifier) { - babelConfigModifier = v => v; - } - - // Variable used for enabling profiling in Production - // passed into alias object. Uses a flag if passed into the build command - const isEnvProductionProfile = isEnvProduction && process.argv.includes("--profile"); - - // 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. - // In development, we always serve from the root. This makes config easier. - const publicPath = isEnvProduction ? paths.servedPath : "/"; - // Some apps do not use client-side routing with pushState. - // For these, "homepage" can be set to "." to enable relative asset paths. - const shouldUseRelativeAssetPaths = publicPath === "./"; - - // Source maps are resource heavy and can cause out of memory issue for large source files. - const shouldUseSourceMap = isEnvDevelopment || process.env.GENERATE_SOURCEMAP === "true"; - - // `publicUrl` is just like `publicPath`, but we will provide it to our app - // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. - // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. - const publicUrl = isEnvProduction ? publicPath.slice(0, -1) : ""; - // Get environment variables to inject into our app. - const env = getClientEnvironment(publicUrl); - - return { - target: "web", - mode: isEnvProduction ? "production" : "development", - // Stop compilation early in production - bail: isEnvProduction, - devtool: shouldUseSourceMap ? "source-map" : false, - // These are the "entry points" to our application. - // This means they will be the "root" imports that are included in JS bundle. - entry: [ - // Finally, this is your app's code: - paths.appIndexJs - // We include the app code last so that if there is a runtime error during - // initialization, it doesn't blow up the WebpackDevServer client, and - // changing JS code would still trigger a refresh. - ].filter(Boolean), - output: { - clean: true, - // 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_FOLDER}/js/[name].[contenthash:8].js` - : `${STATIC_FOLDER}/js/[name].js`, - - // There are also additional JS chunk files if you use code splitting. - chunkFilename: isEnvProduction - ? `${STATIC_FOLDER}/js/[name].[contenthash:8].chunk.js` - : `${STATIC_FOLDER}/js/[name].chunk.js`, - // We inferred the "public path" (such as / or /my-project) from homepage. - // We use "/" in development. - publicPath, - // Point sourcemap entries to original disk location (format as URL on Windows) - devtoolModuleFilenameTemplate: (info: { absoluteResourcePath: string }) => { - if (isEnvProduction) { - return path - .relative(paths.appSrc, info.absoluteResourcePath) - .replace(/\\/g, "/"); - } - - return path.resolve(info.absoluteResourcePath).replace(/\\/g, "/"); - }, - // 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" - }, - optimization: { - minimize: isEnvProduction, - minimizer: [ - // This is only used in production mode - new TerserPlugin({ - terserOptions: { - parse: { - // We want terser to parse ecma 8 code. However, we don't want it - // to apply any minification steps that turns valid ecma 5 code - // into invalid ecma 5 code. This is why the 'compress' and 'output' - // sections only apply transformations that are ecma 5 safe - // https://github.com/facebook/create-react-app/pull/4234 - ecma: 2015 - }, - compress: { - ecma: 5, - // Disabled because of an issue with Uglify breaking seemingly valid code: - // https://github.com/facebook/create-react-app/issues/2376 - // Pending further investigation: - // https://github.com/mishoo/UglifyJS2/issues/2011 - comparisons: false, - // Disabled because of an issue with Terser breaking valid code: - // https://github.com/facebook/create-react-app/issues/5250 - // Pending further investigation: - // https://github.com/terser-js/terser/issues/120 - inline: 2 - }, - mangle: { - safari10: true - }, - // Added for profiling in devtools - keep_classnames: isEnvProductionProfile, - keep_fnames: isEnvProductionProfile, - output: { - ecma: 5, - comments: false, - // Turned on because emoji and regex is not minified properly using default - // https://github.com/facebook/create-react-app/issues/2488 - ascii_only: true - }, - sourceMap: shouldUseSourceMap - } - }), - // @ts-ignore Ignoring this due to type mismatch. No time to dig into this right now. - new CssMinimizerPlugin({ - minimizerOptions: { - preset: ["default", { minifyFontValues: { removeQuotes: false } }] - } - }) - ], - // Automatically split vendor and commons - // https://twitter.com/wSokra/status/969633336732905474 - // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366 - splitChunks: { - chunks: "all", - name: false - }, - // Keep the runtime chunk separated to enable long term caching - // https://twitter.com/wSokra/status/969679223278505985 - // https://github.com/facebook/create-react-app/issues/5358 - runtimeChunk: { - // @ts-ignore - name: entrypoint => `runtime-${entrypoint.name}` - } - }, - resolve: { - // This allows you to set a fallback for where Webpack should look for modules. - // We placed these paths second because we want `node_modules` to "win" - // if there are any conflicts. This matches Node resolution mechanism. - // https://github.com/facebook/create-react-app/issues/253 - modules: ["node_modules", paths.appNodeModules].concat( - modules.additionalModulePaths || [] - ), - // These are the reasonable defaults supported by the Node ecosystem. - // We also include JSX as a common component filename extension to support - // some tools, although we do not recommend using it, see: - // https://github.com/facebook/create-react-app/issues/290 - // `web` extension prefixes have been added for better support - // for React Native Web. - extensions: [".mjs", ".cjs", ".ts", ".tsx", ".json", ".jsx", ".js"], - alias: { - // Support React Native Web - // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ - "react-native": require.resolve("react-native-web"), - react: require.resolve("react"), - // Allows for better profiling with ReactDevTools - ...(isEnvProductionProfile && { - "react-dom$": require.resolve("react-dom/profiling"), - "scheduler/tracing": require.resolve("scheduler/tracing-profiling") - }) - }, - fallback: { - path: false - } - }, - module: { - strictExportPresence: true, - rules: [ - { - // "oneOf" will traverse all following loaders until one will - // match the requirements. When no loader matches it will fall - // back to the "file" loader at the end of the loader list. - oneOf: [ - { - test: /\.m?js$/, - include: /node_modules/, - type: "javascript/auto", - resolve: { - fullySpecified: false - } - }, - { - test: /\.svg$/i, - issuer: /\.[jt]sx?$/, - use: [ - { - loader: require.resolve("@svgr/webpack"), - options: { - svgoConfig: { - plugins: [ - { - name: "preset-default", - params: { - overrides: { - removeViewBox: false - } - } - } - ] - } - } - }, - { - ...getUrlLoader() - } - ] - }, - // "url" loader works like "file" loader except that it embeds assets - // smaller than specified limit in bytes as data URLs to avoid requests. - // A missing `test` is equivalent to a match. - { - test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], - ...getUrlLoader() - }, - // Process application JS with Babel. - // The preset includes JSX, Flow, TypeScript, and some ESnext features. - { - test: /\.(js|mjs|jsx|ts|tsx)$/, - include: [paths.appSrc, paths.appIndexJs, ...paths.allWorkspaces], - loader: require.resolve("babel-loader"), - options: babelConfigModifier({ - sourceType: "unambiguous", - presets: [ - require.resolve("@babel/preset-env"), - require.resolve("@babel/preset-react"), - require.resolve("@babel/preset-typescript") - ], - plugins: [ - [ - "babel-plugin-module-resolver", - { - cwd: paths.appPath, - alias: { - "~": "./src" - } - } - ], - isEnvDevelopment && require.resolve("react-refresh/babel") - ].filter(Boolean), - // This is a feature of `babel-loader` for webpack (not Babel itself). - // It enables caching results in ./node_modules/.cache/babel-loader/ - // directory for faster rebuilds. - cacheDirectory: true, - // See #6846 for context on why cacheCompression is disabled - cacheCompression: false, - compact: isEnvProduction, - sourceMaps: shouldUseSourceMap - }) - }, - - // "postcss" loader applies autoprefixer to our CSS. - // "css" loader resolves paths in CSS and adds assets as dependencies. - // "style" loader turns CSS into JS modules that inject