From f811d66acee0ebb903ec92c42b48e7dc0dedce18 Mon Sep 17 00:00:00 2001 From: wangsongsole Date: Mon, 18 Sep 2023 10:32:31 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20config:=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E7=8E=AF=E5=A2=83=E5=8F=98=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/env.js | 74 +++++++-------- scripts/build.js | 199 ++++++++++++++++++--------------------- scripts/start.js | 176 ++++++++++++++++------------------ scripts/test.js | 199 ++++++++++++++++++--------------------- src/assets/api.js | 37 +------- src/pages/login/login.js | 134 +++++++++++++------------- 6 files changed, 367 insertions(+), 452 deletions(-) diff --git a/config/env.js b/config/env.js index 3d1411bd..dddc2e94 100644 --- a/config/env.js +++ b/config/env.js @@ -1,17 +1,13 @@ -'use strict'; - -const fs = require('fs'); -const path = require('path'); -const paths = require('./paths'); +const fs = require("fs") +const path = require("path") +const paths = require("./paths") // Make sure that including paths.js after env.js will read .env variables. -delete require.cache[require.resolve('./paths')]; +delete require.cache[require.resolve("./paths")] -const NODE_ENV = process.env.NODE_ENV; +const NODE_ENV = process.env.NODE_ENV if (!NODE_ENV) { - throw new Error( - 'The NODE_ENV environment variable is required but was not specified.' - ); + throw new Error("The NODE_ENV environment variable is required but was not specified.") } // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use @@ -20,25 +16,25 @@ const dotenvFiles = [ // Don't include `.env.local` for `test` environment // since normally you expect tests to produce the same // results for everyone - NODE_ENV !== 'test' && `${paths.dotenv}.local`, + NODE_ENV !== "test" && `${paths.dotenv}.local`, `${paths.dotenv}.${NODE_ENV}`, - paths.dotenv, -].filter(Boolean); + paths.dotenv +].filter(Boolean) // Load environment variables from .env* files. Suppress warnings using silent // if this file is missing. dotenv will never modify any environment variables // that have already been set. Variable expansion is supported in .env files. // https://github.com/motdotla/dotenv // https://github.com/motdotla/dotenv-expand -dotenvFiles.forEach(dotenvFile => { +dotenvFiles.forEach((dotenvFile) => { if (fs.existsSync(dotenvFile)) { - require('dotenv-expand')( - require('dotenv').config({ - path: dotenvFile, + require("dotenv-expand")( + require("dotenv").config({ + path: dotenvFile }) - ); + ) } -}); +}) // We support resolving modules according to `NODE_PATH`. // This lets you use absolute paths in imports inside large monorepos: @@ -49,29 +45,29 @@ dotenvFiles.forEach(dotenvFile => { // 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 || '') +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); + .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; +const REACT_APP = /^REACT_APP_/i function getClientEnvironment(publicUrl) { const raw = Object.keys(process.env) - .filter(key => REACT_APP.test(key)) + .filter((key) => REACT_APP.test(key)) .reduce( (env, key) => { - env[key] = process.env[key]; - return env; + env[key] = process.env[key] + return env }, { // 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', + 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 @@ -89,18 +85,20 @@ function getClientEnvironment(publicUrl) { // react-refresh is not 100% stable at this time, // which is why it's disabled by default. // It is defined here so it is available in the webpackHotDevClient. - FAST_REFRESH: process.env.FAST_REFRESH !== 'false', + BASE_URL: process.env.BASE_URL, + UNIFIED_API: process.env.UNIFIED_API, + UNIFIED_URL: process.env.UNIFIED_URL } - ); + ) // Stringify all values so we can feed into webpack DefinePlugin const stringified = { - 'process.env': Object.keys(raw).reduce((env, key) => { - env[key] = JSON.stringify(raw[key]); - return env; - }, {}), - }; + "process.env": Object.keys(raw).reduce((env, key) => { + env[key] = JSON.stringify(raw[key]) + return env + }, {}) + } - return { raw, stringified }; + return { raw, stringified } } -module.exports = getClientEnvironment; +module.exports = getClientEnvironment diff --git a/scripts/build.js b/scripts/build.js index 230862f5..7c6922d6 100644 --- a/scripts/build.js +++ b/scripts/build.js @@ -1,213 +1,198 @@ -'use strict'; - // Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'production'; -process.env.NODE_ENV = 'production'; - +process.env.BABEL_ENV = "production" +process.env.NODE_ENV = "production" +process.env.BASE_URL = "https://marketapi2.1688sup.com" +process.env.UNIFIED_API = "https://api.user.1688sup.com/v1" +process.env.UNIFIED_URL = "https://user.1688sup.com/#/login" // 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; -}); +process.on("unhandledRejection", (err) => { + throw err +}) // Ensure environment variables are read. -require('../config/env'); +require("../config/env") +const path = require("path") +const chalk = require("react-dev-utils/chalk") +const fs = require("fs-extra") +const bfj = require("bfj") +const webpack = require("webpack") +const configFactory = require("../config/webpack.config") +const paths = require("../config/paths") +const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles") +const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages") +const printHostingInstructions = require("react-dev-utils/printHostingInstructions") +const FileSizeReporter = require("react-dev-utils/FileSizeReporter") +const printBuildError = require("react-dev-utils/printBuildError") -const path = require('path'); -const chalk = require('react-dev-utils/chalk'); -const fs = require('fs-extra'); -const bfj = require('bfj'); -const webpack = require('webpack'); -const configFactory = require('../config/webpack.config'); -const paths = require('../config/paths'); -const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); -const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); -const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); -const printBuildError = require('react-dev-utils/printBuildError'); - -const measureFileSizesBeforeBuild = - FileSizeReporter.measureFileSizesBeforeBuild; -const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; -const useYarn = fs.existsSync(paths.yarnLockFile); +const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild +const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild +const useYarn = fs.existsSync(paths.yarnLockFile) // 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 WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024 +const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024 -const isInteractive = process.stdout.isTTY; +const isInteractive = process.stdout.isTTY // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); + process.exit(1) } -const argv = process.argv.slice(2); -const writeStatsJson = argv.indexOf('--stats') !== -1; +const argv = process.argv.slice(2) +const writeStatsJson = argv.indexOf("--stats") !== -1 // Generate configuration -const config = configFactory('production'); +const config = configFactory("production") // We require that you explicitly set browsers and do not fall back to // browserslist defaults. -const { checkBrowsers } = require('react-dev-utils/browsersHelper'); +const { checkBrowsers } = require("react-dev-utils/browsersHelper") checkBrowsers(paths.appPath, isInteractive) .then(() => { // First, read the current file sizes in build directory. // This lets us display how much they changed later. - return measureFileSizesBeforeBuild(paths.appBuild); + return measureFileSizesBeforeBuild(paths.appBuild) }) - .then(previousFileSizes => { + .then((previousFileSizes) => { // 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); + fs.emptyDirSync(paths.appBuild) // Merge with the public folder - copyPublicFolder(); + copyPublicFolder() // Start the webpack build - return build(previousFileSizes); + return build(previousFileSizes) }) .then( ({ stats, previousFileSizes, warnings }) => { if (warnings.length) { - console.log(chalk.yellow('Compiled with warnings.\n')); - console.log(warnings.join('\n\n')); + console.log(chalk.yellow("Compiled with warnings.\n")) + console.log(warnings.join("\n\n")) console.log( - '\nSearch for the ' + - chalk.underline(chalk.yellow('keywords')) + - ' to learn more about each warning.' - ); + "\nSearch for the " + + chalk.underline(chalk.yellow("keywords")) + + " to learn more about each warning." + ) console.log( - 'To ignore, add ' + - chalk.cyan('// eslint-disable-next-line') + - ' to the line before.\n' - ); + "To ignore, add " + chalk.cyan("// eslint-disable-next-line") + " to the line before.\n" + ) } else { - console.log(chalk.green('Compiled successfully.\n')); + console.log(chalk.green("Compiled successfully.\n")) } - console.log('File sizes after gzip:\n'); + console.log("File sizes after gzip:\n") printFileSizesAfterBuild( stats, previousFileSizes, paths.appBuild, WARN_AFTER_BUNDLE_GZIP_SIZE, WARN_AFTER_CHUNK_GZIP_SIZE - ); - console.log(); + ) + console.log() - const appPackage = require(paths.appPackageJson); - const publicUrl = paths.publicUrlOrPath; - const publicPath = config.output.publicPath; - const buildFolder = path.relative(process.cwd(), paths.appBuild); - printHostingInstructions( - appPackage, - publicUrl, - publicPath, - buildFolder, - useYarn - ); + const appPackage = require(paths.appPackageJson) + const publicUrl = paths.publicUrlOrPath + const publicPath = config.output.publicPath + const buildFolder = path.relative(process.cwd(), paths.appBuild) + printHostingInstructions(appPackage, publicUrl, publicPath, buildFolder, useYarn) }, - err => { - const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; + (err) => { + const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === "true" if (tscCompileOnError) { console.log( chalk.yellow( - 'Compiled with the following type errors (you may want to check these before deploying your app):\n' + "Compiled with the following type errors (you may want to check these before deploying your app):\n" ) - ); - printBuildError(err); + ) + printBuildError(err) } else { - console.log(chalk.red('Failed to compile.\n')); - printBuildError(err); - process.exit(1); + console.log(chalk.red("Failed to compile.\n")) + printBuildError(err) + process.exit(1) } } ) - .catch(err => { + .catch((err) => { if (err && err.message) { - console.log(err.message); + console.log(err.message) } - process.exit(1); - }); + process.exit(1) + }) // Create the production build and print the deployment instructions. function build(previousFileSizes) { - console.log('Creating an optimized production build...'); + console.log("Creating an optimized production build...") - const compiler = webpack(config); + const compiler = webpack(config) return new Promise((resolve, reject) => { compiler.run((err, stats) => { - let messages; + let messages if (err) { if (!err.message) { - return reject(err); + return reject(err) } - let errMessage = err.message; + let errMessage = err.message // Add additional information for postcss errors - if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) { - errMessage += - '\nCompileError: Begins at CSS selector ' + - err['postcssNode'].selector; + if (Object.prototype.hasOwnProperty.call(err, "postcssNode")) { + errMessage += "\nCompileError: Begins at CSS selector " + err["postcssNode"].selector } messages = formatWebpackMessages({ errors: [errMessage], - warnings: [], - }); + warnings: [] + }) } else { - messages = formatWebpackMessages( - stats.toJson({ all: false, warnings: true, errors: true }) - ); + messages = formatWebpackMessages(stats.toJson({ all: false, warnings: true, errors: true })) } if (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; + messages.errors.length = 1 } - return reject(new Error(messages.errors.join('\n\n'))); + return reject(new Error(messages.errors.join("\n\n"))) } if ( process.env.CI && - (typeof process.env.CI !== 'string' || - process.env.CI.toLowerCase() !== 'false') && + (typeof process.env.CI !== "string" || process.env.CI.toLowerCase() !== "false") && messages.warnings.length ) { console.log( chalk.yellow( - '\nTreating warnings as errors because process.env.CI = true.\n' + - 'Most CI servers set it automatically.\n' + "\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 reject(new Error(messages.warnings.join("\n\n"))) } const resolveArgs = { stats, previousFileSizes, - warnings: messages.warnings, - }; + warnings: messages.warnings + } if (writeStatsJson) { return bfj - .write(paths.appBuild + '/bundle-stats.json', stats.toJson()) + .write(paths.appBuild + "/bundle-stats.json", stats.toJson()) .then(() => resolve(resolveArgs)) - .catch(error => reject(new Error(error))); + .catch((error) => reject(new Error(error))) } - return resolve(resolveArgs); - }); - }); + return resolve(resolveArgs) + }) + }) } function copyPublicFolder() { fs.copySync(paths.appPublic, paths.appBuild, { dereference: true, - filter: file => file !== paths.appHtml, - }); + filter: (file) => file !== paths.appHtml + }) } diff --git a/scripts/start.js b/scripts/start.js index 92c2671b..79ab445f 100644 --- a/scripts/start.js +++ b/scripts/start.js @@ -1,52 +1,59 @@ -'use strict'; - // Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'development'; -process.env.NODE_ENV = 'development'; +process.env.BABEL_ENV = "development" +process.env.NODE_ENV = "development" +process.env.BASE_URL = "http://test.marketapi.1688sup.com" +process.env.UNIFIED_API = "http://api.test.user.1688sup.com/v1" +process.env.UNIFIED_URL = "http://test.user.1688sup.com/#/login" + +//镜像环境 / 统一登陆灰度 +/* + baseurl = 'http://pre.marketapi.1688sup.com' + unifiedApi = 'http://api.gray.user.1688sup.com/v1'; + window.unifiedUrl = 'http://gray.user.1688sup.com/#/login'; +*/ // 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; -}); +process.on("unhandledRejection", (err) => { + throw err +}) // Ensure environment variables are read. -require('../config/env'); +require("../config/env") - -const fs = require('fs'); -const chalk = require('react-dev-utils/chalk'); -const webpack = require('webpack'); -const WebpackDevServer = require('webpack-dev-server'); -const clearConsole = require('react-dev-utils/clearConsole'); -const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); +const fs = require("fs") +const chalk = require("react-dev-utils/chalk") +const webpack = require("webpack") +const WebpackDevServer = require("webpack-dev-server") +const clearConsole = require("react-dev-utils/clearConsole") +const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles") const { choosePort, createCompiler, prepareProxy, - prepareUrls, -} = require('react-dev-utils/WebpackDevServerUtils'); -const openBrowser = require('react-dev-utils/openBrowser'); -const semver = require('semver'); -const paths = require('../config/paths'); -const configFactory = require('../config/webpack.config'); -const createDevServerConfig = require('../config/webpackDevServer.config'); -const getClientEnvironment = require('../config/env'); -const react = require(require.resolve('react', { paths: [paths.appPath] })); + prepareUrls +} = require("react-dev-utils/WebpackDevServerUtils") +const openBrowser = require("react-dev-utils/openBrowser") +const semver = require("semver") +const paths = require("../config/paths") +const configFactory = require("../config/webpack.config") +const createDevServerConfig = require("../config/webpackDevServer.config") +const getClientEnvironment = require("../config/env") +const react = require(require.resolve("react", { paths: [paths.appPath] })) -const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)); -const useYarn = fs.existsSync(paths.yarnLockFile); -const isInteractive = process.stdout.isTTY; +const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)) +const useYarn = fs.existsSync(paths.yarnLockFile) +const isInteractive = process.stdout.isTTY // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); + process.exit(1) } // Tools like Cloud9 rely on this. -const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000; -const HOST = process.env.HOST || '0.0.0.0'; +const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000 +const HOST = process.env.HOST || "0.0.0.0" if (process.env.HOST) { console.log( @@ -55,49 +62,38 @@ if (process.env.HOST) { chalk.bold(process.env.HOST) )}` ) - ); - console.log( - `If this was unintentional, check that you haven't mistakenly set it in your shell.` - ); - console.log( - `Learn more here: ${chalk.yellow('https://cra.link/advanced-config')}` - ); - console.log(); + ) + console.log(`If this was unintentional, check that you haven't mistakenly set it in your shell.`) + console.log(`Learn more here: ${chalk.yellow("https://cra.link/advanced-config")}`) + console.log() } // We require that you explicitly set browsers and do not fall back to // browserslist defaults. -const { checkBrowsers } = require('react-dev-utils/browsersHelper'); +const { checkBrowsers } = require("react-dev-utils/browsersHelper") checkBrowsers(paths.appPath, isInteractive) .then(() => { // We attempt to use the default port but if it is busy, we offer the user to // run on a different port. `choosePort()` Promise resolves to the next free port. - return choosePort(HOST, DEFAULT_PORT); + return choosePort(HOST, DEFAULT_PORT) }) - .then(port => { + .then((port) => { if (port == null) { // We have not found a port. - return; + return } - const config = configFactory('development'); - const protocol = process.env.HTTPS === 'true' ? 'https' : 'http'; - const appName = require(paths.appPackageJson).name; + const config = configFactory("development") + const protocol = process.env.HTTPS === "true" ? "https" : "http" + const appName = require(paths.appPackageJson).name - const useTypeScript = fs.existsSync(paths.appTsConfig); - const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; - const urls = prepareUrls( - protocol, - HOST, - port, - paths.publicUrlOrPath.slice(0, -1) - ); + const useTypeScript = fs.existsSync(paths.appTsConfig) + const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === "true" + const urls = prepareUrls(protocol, HOST, port, paths.publicUrlOrPath.slice(0, -1)) const devSocket = { - warnings: warnings => - devServer.sockWrite(devServer.sockets, 'warnings', warnings), - errors: errors => - devServer.sockWrite(devServer.sockets, 'errors', errors), - }; + warnings: (warnings) => devServer.sockWrite(devServer.sockets, "warnings", warnings), + errors: (errors) => devServer.sockWrite(devServer.sockets, "errors", errors) + } // Create a webpack compiler that is configured with custom messages. const compiler = createCompiler({ appName, @@ -107,60 +103,52 @@ checkBrowsers(paths.appPath, isInteractive) useYarn, useTypeScript, tscCompileOnError, - webpack, - }); + webpack + }) // Load proxy config - const proxySetting = require(paths.appPackageJson).proxy; - const proxyConfig = prepareProxy( - proxySetting, - paths.appPublic, - paths.publicUrlOrPath - ); + const proxySetting = require(paths.appPackageJson).proxy + const proxyConfig = prepareProxy(proxySetting, paths.appPublic, paths.publicUrlOrPath) // Serve webpack assets generated by the compiler over a web server. - const serverConfig = createDevServerConfig( - proxyConfig, - urls.lanUrlForConfig - ); - const devServer = new WebpackDevServer(compiler, serverConfig); + const serverConfig = createDevServerConfig(proxyConfig, urls.lanUrlForConfig) + const devServer = new WebpackDevServer(compiler, serverConfig) // Launch WebpackDevServer. - devServer.listen(port, HOST, err => { + devServer.listen(port, HOST, (err) => { if (err) { - return console.log(err); + return console.log(err) } if (isInteractive) { - clearConsole(); + clearConsole() } - if (env.raw.FAST_REFRESH && semver.lt(react.version, '16.10.0')) { + if (env.raw.FAST_REFRESH && semver.lt(react.version, "16.10.0")) { console.log( chalk.yellow( `Fast Refresh requires React 16.10 or higher. You are using React ${react.version}.` ) - ); + ) } - console.log(chalk.cyan('Starting the development server...\n')); - openBrowser(urls.localUrlForBrowser); - }); - - ['SIGINT', 'SIGTERM'].forEach(function (sig) { + console.log(chalk.cyan("Starting the development server...\n")) + openBrowser(urls.localUrlForBrowser) + }) + ;["SIGINT", "SIGTERM"].forEach(function (sig) { process.on(sig, function () { - devServer.close(); - process.exit(); - }); - }); + devServer.close() + process.exit() + }) + }) - if (process.env.CI !== 'true') { + if (process.env.CI !== "true") { // Gracefully exit when stdin ends - process.stdin.on('end', function () { - devServer.close(); - process.exit(); - }); + process.stdin.on("end", function () { + devServer.close() + process.exit() + }) } }) - .catch(err => { + .catch((err) => { if (err && err.message) { - console.log(err.message); + console.log(err.message) } - process.exit(1); - }); + process.exit(1) + }) diff --git a/scripts/test.js b/scripts/test.js index 938de119..e2172654 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -1,213 +1,198 @@ -'use strict'; - // Do this as the first thing so that any code reading it knows the right env. -process.env.BABEL_ENV = 'test'; -process.env.NODE_ENV = 'test'; - +process.env.BABEL_ENV = "test" +process.env.NODE_ENV = "test" +process.env.BASE_URL = "http://test.marketapi.1688sup.com" +process.env.UNIFIED_API = "http://api.test.user.1688sup.com/v1" +process.env.UNIFIED_URL = "http://test.user.1688sup.com/#/login" // 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; -}); +process.on("unhandledRejection", (err) => { + throw err +}) // Ensure environment variables are read. -require('../config/env'); +require("../config/env") +const path = require("path") +const chalk = require("react-dev-utils/chalk") +const fs = require("fs-extra") +const bfj = require("bfj") +const webpack = require("webpack") +const configFactory = require("../config/webpack.config") +const paths = require("../config/paths") +const checkRequiredFiles = require("react-dev-utils/checkRequiredFiles") +const formatWebpackMessages = require("react-dev-utils/formatWebpackMessages") +const printHostingInstructions = require("react-dev-utils/printHostingInstructions") +const FileSizeReporter = require("react-dev-utils/FileSizeReporter") +const printBuildError = require("react-dev-utils/printBuildError") -const path = require('path'); -const chalk = require('react-dev-utils/chalk'); -const fs = require('fs-extra'); -const bfj = require('bfj'); -const webpack = require('webpack'); -const configFactory = require('../config/webpack.config'); -const paths = require('../config/paths'); -const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles'); -const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages'); -const printHostingInstructions = require('react-dev-utils/printHostingInstructions'); -const FileSizeReporter = require('react-dev-utils/FileSizeReporter'); -const printBuildError = require('react-dev-utils/printBuildError'); - -const measureFileSizesBeforeBuild = - FileSizeReporter.measureFileSizesBeforeBuild; -const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild; -const useYarn = fs.existsSync(paths.yarnLockFile); +const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild +const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild +const useYarn = fs.existsSync(paths.yarnLockFile) // 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 WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024 +const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024 -const isInteractive = process.stdout.isTTY; +const isInteractive = process.stdout.isTTY // Warn and crash if required files are missing if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) { - process.exit(1); + process.exit(1) } -const argv = process.argv.slice(2); -const writeStatsJson = argv.indexOf('--stats') !== -1; +const argv = process.argv.slice(2) +const writeStatsJson = argv.indexOf("--stats") !== -1 // Generate configuration -const config = configFactory('production'); +const config = configFactory("production") // We require that you explicitly set browsers and do not fall back to // browserslist defaults. -const { checkBrowsers } = require('react-dev-utils/browsersHelper'); +const { checkBrowsers } = require("react-dev-utils/browsersHelper") checkBrowsers(paths.appPath, isInteractive) .then(() => { // First, read the current file sizes in build directory. // This lets us display how much they changed later. - return measureFileSizesBeforeBuild(paths.appBuild); + return measureFileSizesBeforeBuild(paths.appBuild) }) - .then(previousFileSizes => { + .then((previousFileSizes) => { // 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); + fs.emptyDirSync(paths.appBuild) // Merge with the public folder - copyPublicFolder(); + copyPublicFolder() // Start the webpack build - return build(previousFileSizes); + return build(previousFileSizes) }) .then( ({ stats, previousFileSizes, warnings }) => { if (warnings.length) { - console.log(chalk.yellow('Compiled with warnings.\n')); - console.log(warnings.join('\n\n')); + console.log(chalk.yellow("Compiled with warnings.\n")) + console.log(warnings.join("\n\n")) console.log( - '\nSearch for the ' + - chalk.underline(chalk.yellow('keywords')) + - ' to learn more about each warning.' - ); + "\nSearch for the " + + chalk.underline(chalk.yellow("keywords")) + + " to learn more about each warning." + ) console.log( - 'To ignore, add ' + - chalk.cyan('// eslint-disable-next-line') + - ' to the line before.\n' - ); + "To ignore, add " + chalk.cyan("// eslint-disable-next-line") + " to the line before.\n" + ) } else { - console.log(chalk.green('Compiled successfully.\n')); + console.log(chalk.green("Compiled successfully.\n")) } - console.log('File sizes after gzip:\n'); + console.log("File sizes after gzip:\n") printFileSizesAfterBuild( stats, previousFileSizes, paths.appBuild, WARN_AFTER_BUNDLE_GZIP_SIZE, WARN_AFTER_CHUNK_GZIP_SIZE - ); - console.log(); + ) + console.log() - const appPackage = require(paths.appPackageJson); - const publicUrl = paths.publicUrlOrPath; - const publicPath = config.output.publicPath; - const buildFolder = path.relative(process.cwd(), paths.appBuild); - printHostingInstructions( - appPackage, - publicUrl, - publicPath, - buildFolder, - useYarn - ); + const appPackage = require(paths.appPackageJson) + const publicUrl = paths.publicUrlOrPath + const publicPath = config.output.publicPath + const buildFolder = path.relative(process.cwd(), paths.appBuild) + printHostingInstructions(appPackage, publicUrl, publicPath, buildFolder, useYarn) }, - err => { - const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'; + (err) => { + const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === "true" if (tscCompileOnError) { console.log( chalk.yellow( - 'Compiled with the following type errors (you may want to check these before deploying your app):\n' + "Compiled with the following type errors (you may want to check these before deploying your app):\n" ) - ); - printBuildError(err); + ) + printBuildError(err) } else { - console.log(chalk.red('Failed to compile.\n')); - printBuildError(err); - process.exit(1); + console.log(chalk.red("Failed to compile.\n")) + printBuildError(err) + process.exit(1) } } ) - .catch(err => { + .catch((err) => { if (err && err.message) { - console.log(err.message); + console.log(err.message) } - process.exit(1); - }); + process.exit(1) + }) // Create the production build and print the deployment instructions. function build(previousFileSizes) { - console.log('Creating an optimized production build...'); + console.log("Creating an optimized production build...") - const compiler = webpack(config); + const compiler = webpack(config) return new Promise((resolve, reject) => { compiler.run((err, stats) => { - let messages; + let messages if (err) { if (!err.message) { - return reject(err); + return reject(err) } - let errMessage = err.message; + let errMessage = err.message // Add additional information for postcss errors - if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) { - errMessage += - '\nCompileError: Begins at CSS selector ' + - err['postcssNode'].selector; + if (Object.prototype.hasOwnProperty.call(err, "postcssNode")) { + errMessage += "\nCompileError: Begins at CSS selector " + err["postcssNode"].selector } messages = formatWebpackMessages({ errors: [errMessage], - warnings: [], - }); + warnings: [] + }) } else { - messages = formatWebpackMessages( - stats.toJson({ all: false, warnings: true, errors: true }) - ); + messages = formatWebpackMessages(stats.toJson({ all: false, warnings: true, errors: true })) } if (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; + messages.errors.length = 1 } - return reject(new Error(messages.errors.join('\n\n'))); + return reject(new Error(messages.errors.join("\n\n"))) } if ( process.env.CI && - (typeof process.env.CI !== 'string' || - process.env.CI.toLowerCase() !== 'false') && + (typeof process.env.CI !== "string" || process.env.CI.toLowerCase() !== "false") && messages.warnings.length ) { console.log( chalk.yellow( - '\nTreating warnings as errors because process.env.CI = true.\n' + - 'Most CI servers set it automatically.\n' + "\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 reject(new Error(messages.warnings.join("\n\n"))) } const resolveArgs = { stats, previousFileSizes, - warnings: messages.warnings, - }; + warnings: messages.warnings + } if (writeStatsJson) { return bfj - .write(paths.appBuild + '/bundle-stats.json', stats.toJson()) + .write(paths.appBuild + "/bundle-stats.json", stats.toJson()) .then(() => resolve(resolveArgs)) - .catch(error => reject(new Error(error))); + .catch((error) => reject(new Error(error))) } - return resolve(resolveArgs); - }); - }); + return resolve(resolveArgs) + }) + }) } function copyPublicFolder() { fs.copySync(paths.appPublic, paths.appBuild, { dereference: true, - filter: file => file !== paths.appHtml, - }); + filter: (file) => file !== paths.appHtml + }) } diff --git a/src/assets/api.js b/src/assets/api.js index d8a371ac..cfc51307 100644 --- a/src/assets/api.js +++ b/src/assets/api.js @@ -1,40 +1,7 @@ import { Notify } from "zent" -//镜像环境 -// export const baseurl = 'http://pre.marketapi.1688sup.com' -// const Version = "v1.3.0"; -// window.baseurl = 'http://pre.marketapi.1688sup.com' -/* 统一登陆灰度 - unifiedApi = 'http://api.gray.user.1688sup.com/v1'; - window.unifiedUrl = 'http://gray.user.1688sup.com/#/login'; -*/ - -let baseurl = "" -let unifiedApi = "" +let baseurl = process.env.BASE_URL let download_url = "https://ewm.83323.cn" -// 测试环境 -if (process.env.NODE_ENV == "test") { - baseurl = "http://test.marketapi.1688sup.com" - window.baseurl = "http://test.marketapi.1688sup.com" - unifiedApi = "http://api.test.user.1688sup.com/v1" - window.unifiedUrl = "http://test.user.1688sup.com/#/login" -} - -// 生产环境 -if (process.env.NODE_ENV == "production") { - baseurl = "https://marketapi2.1688sup.com" - window.baseurl = "https://marketapi2.1688sup.com" - unifiedApi = "https://api.user.1688sup.com/v1" - window.unifiedUrl = "https://user.1688sup.com/#/login" -} - -/* 开发环境 */ -if (process.env.NODE_ENV == "development") { - baseurl = "http://test.marketapi.1688sup.com" - window.baseurl = "http://test.marketapi.1688sup.com" - unifiedApi = "http://api.test.user.1688sup.com/v1" - window.unifiedUrl = "http://192.168.7.200:8888/#/login" -} const upload = (method, url, params, responseType) => { let obj = { @@ -672,7 +639,7 @@ export const postLoginStandby = (data) => { //获取权限codes export const getCodes = () => { - return req("get", `${unifiedApi}/menu/myCodes?systemId=2`) + return req("get", `${process.env.UNIFIED_API}/menu/myCodes?systemId=2`) } // logout退出登录 diff --git a/src/pages/login/login.js b/src/pages/login/login.js index 75290da9..e2a7db15 100644 --- a/src/pages/login/login.js +++ b/src/pages/login/login.js @@ -1,5 +1,5 @@ -import './login.less'; -import React, { Component } from 'react'; +import "./login.less" +import React, { Component } from "react" import { getAllEnum, handelResponse, @@ -7,55 +7,53 @@ import { postLoginCode, getVoucherWarningAccount, getCodes -} from '@/assets/api.js'; -import { Notify, BlockLoading } from 'zent'; -import { getMenus } from '@/tools/createRouter.js'; +} from "@/assets/api.js" +import { Notify, BlockLoading } from "zent" +import { getMenus } from "@/tools/createRouter.js" export default class App extends Component { constructor(props) { - super(props); - window['react'] = this; + super(props) + window["react"] = this } componentWillMount() { - const { token, head } = this.getQuery(this.props.location.search); + const { token, head } = this.getQuery(this.props.location.search) /* 判断是否有token */ if (token) { - sessionStorage.setItem('authorization', token); - this.onSubmit(token, head); - return; + sessionStorage.setItem("authorization", token) + this.onSubmit(token, head) + return } /* 调整统一登录平台 */ - this.toUnifiedLogin(); + this.toUnifiedLogin() } /* 解析url参数 */ getQuery = (url) => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( - (a, v) => ( - (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a - ), + (a, v) => ((a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a), {} - ); + ) /* 跳转统一登录平台 */ toUnifiedLogin() { setTimeout(() => { - window.location.href = `${window.unifiedUrl}?url=${encodeURIComponent( + window.location.href = `${process.env.UNIFIED_URL}?url=${encodeURIComponent( window.location.href - )}`; - }, 1500); + )}` + }, 1500) } //获取预警人权限 getAccountList() { getVoucherWarningAccount().then((res) => { if (!res) { - sessionStorage.setItem('isEarlyWarningMan', false); + sessionStorage.setItem("isEarlyWarningMan", false) } else { - sessionStorage.setItem('isEarlyWarningMan', true); + sessionStorage.setItem("isEarlyWarningMan", true) } - }); + }) } onSubmit(authorization, head) { @@ -66,77 +64,71 @@ export default class App extends Component { (response, msg) => { getAllEnum().then((res) => { handelResponse(res, (response, msg) => { - sessionStorage.setItem('enmu', JSON.stringify(response)); - }); - }); + sessionStorage.setItem("enmu", JSON.stringify(response)) + }) + }) /* 获取codes */ getCodes().then(({ codes }) => { - let menuList = getMenus(codes); + let menuList = getMenus(codes) - Notify.clear(); - Notify.success(msg); + Notify.clear() + Notify.success(msg) - this.getProductList(); - this.getAccountList(); - sessionStorage.setItem('showflag', true); + this.getProductList() + this.getAccountList() + sessionStorage.setItem("showflag", true) if (menuList && menuList.length > 0) { - sessionStorage.setItem('activeMenu', JSON.stringify(menuList)); - let market = menuList.filter((item) => item.id == 16); + sessionStorage.setItem("activeMenu", JSON.stringify(menuList)) + let market = menuList.filter((item) => item.id == 16) if (market && market[0]?.children.length > 0) { //菜单有营销计划 - sessionStorage.setItem('linkshowname', '营销计划管理'); - sessionStorage.setItem('pathname2', '/home/plan-list'); - sessionStorage.setItem( - 'menulinklist', - JSON.stringify(market[0].children) - ); + sessionStorage.setItem("linkshowname", "营销计划管理") + sessionStorage.setItem("pathname2", "/home/plan-list") + sessionStorage.setItem("menulinklist", JSON.stringify(market[0].children)) setTimeout(() => { - this.props.history.replace('/home/plan-list'); - }, 1000); + this.props.history.replace("/home/plan-list") + }, 1000) } else { try { menuList.forEach((item) => { if (item.children && item.children.length > 0) { item.children.forEach((it) => { if (it.level == 5) { - sessionStorage.setItem('pathname2', it.router); - sessionStorage.setItem('linkshowname', item.title); + sessionStorage.setItem("pathname2", it.router) + sessionStorage.setItem("linkshowname", item.title) - sessionStorage.setItem( - 'menulinklist', - JSON.stringify(item.children) - ); + sessionStorage.setItem("menulinklist", JSON.stringify(item.children)) setTimeout(() => { - this.props.history.replace(it.router); - }, 1000); - throw '终止循环'; + this.props.history.replace(it.router) + }, 1000) + throw "终止循环" } - }); + }) } else { - Notify.clear(); - Notify.warn('请先联系管理员配置权限菜单'); + Notify.clear() + Notify.warn("请先联系管理员配置权限菜单") } - }); + }) } catch (e) {} } } else { - Notify.clear(); - Notify.warn('请先联系管理员配置权限菜单'); + Notify.clear() + Notify.warn("请先联系管理员配置权限菜单") } - }); + }) }, (err) => { if (res.code == -2) { - Notify.error(res.message); + Notify.error(res.message) } else { - Notify.clear(); - Notify.error(res.message); + Notify.clear() + Notify.error(res.message) } } - ); + ) }) - .catch((err) => {}); + .catch((err) => {}) } /* 获取商品 */ @@ -145,25 +137,25 @@ export default class App extends Component { handelResponse( res, (req, msg) => { - sessionStorage.setItem('updatetime', Date.now()); - sessionStorage.setItem('productsList', JSON.stringify(req.data)); + sessionStorage.setItem("updatetime", Date.now()) + sessionStorage.setItem("productsList", JSON.stringify(req.data)) }, (err) => {} - ); - }); + ) + }) } render() { return ( -
+
- ); + ) } }