Commit 85f7696e by zhangleyuan

feat:项目代码初提交

parents
/*
* @Author: 吴文洁
* @Date: 2020-04-30 10:39:36
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-24 11:43:35
* @Description:
*/
module.exports = {
"parser": '@typescript-eslint/parser',
"plugins": [
"jsx-control-statements",
"@typescript-eslint"
],
"rules": {
"react/jsx-no-undef": [2, { "allowGlobals": true }]
},
"extends": ["react-app", "plugin:jsx-control-statements/recommended"],
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn start`
Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.<br />
You will also see any lint errors in the console.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn build`
Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn eject`
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
'use strict';
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')];
const NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV) {
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
const dotenvFiles = [
`${paths.dotenv}.${NODE_ENV}.local`,
`${paths.dotenv}.${NODE_ENV}`,
// 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`,
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 => {
if (fs.existsSync(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:
// 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;
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
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',
DEPLOY_ENV: process.env.DEPLOY_ENV,
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// 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,
// We support configuring the sockjs pathname during development.
// These settings let a developer run multiple simultaneous projects.
// They are used as the connection `hostname`, `pathname` and `port`
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
// and `sockPort` options in webpack-dev-server.
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
}
);
// 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;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const chalk = require('react-dev-utils/chalk');
const paths = require('./paths');
// Ensure the certificate and key provided are valid and if not
// throw an easy to debug error
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
let encrypted;
try {
// publicEncrypt will throw an error with an invalid cert
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'));
} catch (err) {
throw new Error(
`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`
);
}
try {
// privateDecrypt will throw an error with an invalid key
crypto.privateDecrypt(key, encrypted);
} catch (err) {
throw new Error(
`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${
err.message
}`
);
}
}
// Read file and throw an error if it doesn't exist
function readEnvFile(file, type) {
if (!fs.existsSync(file)) {
throw new Error(
`You specified ${chalk.cyan(
type
)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
);
}
return fs.readFileSync(file);
}
// Get the https config
// Return cert files if provided in env, otherwise just true or false
function getHttpsConfig() {
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env;
const isHttps = HTTPS === 'true';
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE);
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE);
const config = {
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
};
validateKeyAndCerts({ ...config, keyFile, crtFile });
return config;
}
return isHttps;
}
module.exports = getHttpsConfig;
'use strict';
// This is a custom Jest transformer turning style imports into empty objects.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'cssTransform';
},
};
'use strict';
const path = require('path');
const camelcase = require('camelcase');
// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html
module.exports = {
process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
// Based on how SVGR generates a component name:
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
const pascalCaseFilename = camelcase(path.parse(filename).name, {
pascalCase: true,
});
const componentName = `Svg${pascalCaseFilename}`;
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
return {
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
};
}),
};`;
}
return `module.exports = ${assetFilename};`;
},
};
'use strict';
const fs = require('fs');
const path = require('path');
const paths = require('./paths');
const chalk = require('react-dev-utils/chalk');
const resolve = require('resolve');
/**
* Get additional module paths based on the baseUrl of a compilerOptions object.
*
* @param {Object} options
*/
function getAdditionalModulePaths(options = {}) {
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.'
)
);
}
/**
* Get webpack aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getWebpackAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
src: paths.appSrc,
};
}
}
/**
* Get jest aliases based on the baseUrl of a compilerOptions object.
*
* @param {*} options
*/
function getJestAliases(options = {}) {
const baseUrl = options.baseUrl;
if (!baseUrl) {
return {};
}
const baseUrlResolved = path.resolve(paths.appPath, baseUrl);
if (path.relative(paths.appPath, baseUrlResolved) === '') {
return {
'^src/(.*)$': '<rootDir>/src/$1',
};
}
}
function getModules() {
// Check if TypeScript is setup
const hasTsConfig = fs.existsSync(paths.appTsConfig);
const hasJsConfig = fs.existsSync(paths.appJsConfig);
if (hasTsConfig && hasJsConfig) {
throw new Error(
'You have both a tsconfig.json and a jsconfig.json. If you are using TypeScript please remove your jsconfig.json file.'
);
}
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;
// Otherwise we'll check if there is jsconfig.json
// for non TS projects.
} else if (hasJsConfig) {
config = require(paths.appJsConfig);
}
config = config || {};
const options = config.compilerOptions || {};
const additionalModulePaths = getAdditionalModulePaths(options);
return {
additionalModulePaths: additionalModulePaths,
webpackAliases: getWebpackAliases(options),
jestAliases: getJestAliases(options),
hasTsConfig,
};
}
module.exports = getModules();
/*
* @Author: 吴文洁
* @Date: 2020-08-24 13:36:56
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-24 13:36:56
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
'use strict';
const path = require('path');
const fs = require('fs');
const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath');
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebook/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
const publicUrlOrPath = getPublicUrlOrPath(
process.env.NODE_ENV === 'development',
require(resolveApp('package.json')).homepage,
process.env.PUBLIC_URL
);
const moduleFileExtensions = [
'web.mjs',
'mjs',
'web.js',
'js',
'web.ts',
'ts',
'web.tsx',
'tsx',
'json',
'web.jsx',
'jsx',
];
// Resolve file paths in the same order as webpack
const resolveModule = (resolveFn, filePath) => {
const extension = moduleFileExtensions.find(extension =>
fs.existsSync(resolveFn(`${filePath}.${extension}`))
);
if (extension) {
return resolveFn(`${filePath}.${extension}`);
}
return resolveFn(`${filePath}.js`);
};
// config after eject: we're in ./config/
module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp('dist'),
appPublic: resolveApp('public'),
appHtml: resolveApp('public/index.html'),
appIndexJs: resolveModule(resolveApp, 'src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('src'),
appTsConfig: resolveApp('tsconfig.json'),
appJsConfig: resolveApp('jsconfig.json'),
yarnLockFile: resolveApp('yarn.lock'),
testsSetup: resolveModule(resolveApp, 'src/setupTests'),
proxySetup: resolveApp('src/setupProxy.js'),
appNodeModules: resolveApp('node_modules'),
publicUrlOrPath,
};
module.exports.moduleFileExtensions = moduleFileExtensions;
'use strict';
const { resolveModuleName } = require('ts-pnp');
exports.resolveModuleName = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveModuleName
);
};
exports.resolveTypeReferenceDirective = (
typescript,
moduleName,
containingFile,
compilerOptions,
resolutionHost
) => {
return resolveModuleName(
moduleName,
containingFile,
compilerOptions,
resolutionHost,
typescript.resolveTypeReferenceDirective
);
};
'use strict';
const fs = require('fs');
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware');
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware');
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware');
const ignoredFiles = require('react-dev-utils/ignoredFiles');
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware');
const paths = require('./paths');
const getHttpsConfig = require('./getHttpsConfig');
const host = process.env.HOST || '0.0.0.0';
const sockHost = process.env.WDS_SOCKET_HOST;
const sockPath = process.env.WDS_SOCKET_PATH; // default: '/sockjs-node'
const sockPort = process.env.WDS_SOCKET_PORT;
module.exports = function(proxy, allowedHost) {
return {
// WebpackDevServer 2.4.3 introduced a security fix that prevents remote
// websites from potentially accessing local content through DNS rebinding:
// https://github.com/webpack/webpack-dev-server/issues/887
// https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
// However, it made several existing use cases such as development in cloud
// environment or subdomains in development significantly more complicated:
// https://github.com/facebook/create-react-app/issues/2271
// https://github.com/facebook/create-react-app/issues/2233
// While we're investigating better solutions, for now we will take a
// compromise. Since our WDS configuration only serves files in the `public`
// folder we won't consider accessing them a vulnerability. However, if you
// use the `proxy` feature, it gets more dangerous because it can expose
// remote code execution vulnerabilities in backends like Django and Rails.
// So we will disable the host check normally, but enable it if you have
// specified the `proxy` setting. Finally, we let you override it if you
// really know what you're doing with a special environment variable.
disableHostCheck:
!proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',
// Enable gzip compression of generated files.
compress: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files won’t automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
contentBasePublicPath: paths.publicUrlOrPath,
// By default files from `contentBase` will not trigger a page reload.
watchContentBase: true,
// Enable hot reloading server. It will provide WDS_SOCKET_PATH endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// Use 'ws' instead of 'sockjs-node' on server since we're using native
// websockets in `webpackHotDevClient`.
transportMode: 'ws',
// Prevent a WS client from getting injected as we're already including
// `webpackHotDevClient`.
injectClient: false,
// Enable custom sockjs pathname for websocket connection to hot reloading server.
// Enable custom sockjs hostname, pathname and port for websocket connection
// to hot reloading server.
sockHost,
sockPath,
sockPort,
// It is important to tell WebpackDevServer to use the same "publicPath" path as
// we specified in the webpack config. When homepage is '.', default to serving
// from the root.
// remove last slash so user can land on `/test` instead of `/test/`
publicPath: paths.publicUrlOrPath.slice(0, -1),
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.hooks[...].tap` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(paths.appSrc),
},
https: getHttpsConfig(),
host,
overlay: false,
headers: {
'Access-Control-Allow-Origin': '*'
},
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
index: paths.publicUrlOrPath,
},
public: allowedHost,
// `proxy` is run between `before` and `after` `webpack-dev-server` hooks
proxy,
before(app, server) {
// Keep `evalSourceMapMiddleware` and `errorOverlayMiddleware`
// middlewares before `redirectServedPath` otherwise will not have any effect
// This lets us fetch source contents from webpack for the error overlay
app.use(evalSourceMapMiddleware(server));
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
if (fs.existsSync(paths.proxySetup)) {
// This registers user provided middleware for proxy reasons
require(paths.proxySetup)(app);
}
},
after(app) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
app.use(redirectServedPath(paths.publicUrlOrPath));
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath));
},
};
};
#! /usr/bin/env node
/*
* @Author: 吴文洁
* @Date: 2020-06-05 14:59:14
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-04 19:28:08
* @Description:
* @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
*/
const fs = require('fs')
const [
messageFile,
commitType,
] = process.env.HUSKY_GIT_PARAMS.split(' ');
if (commitType == null) {
const currentMessage = fs.readFileSync(messageFile, 'utf8');
// eslint-disable-next-line no-console
const pattern = new RegExp('(feat|fix|style|docs|refactor|pref|test):');
const _currentMessage = currentMessage.replace('\n', '');
if (!pattern.test(currentMessage) && currentMessage.indexOf('Merge branch') === -1) {
// eslint-disable-next-line no-console
console.error(`\x1b[31m ${_currentMessage}不符合commit-msg规范,具体规范请访问 http://wiki.ixm5.cn/pages/viewpage.action?pageId=2918494 \x1b[31m`);
process.exit(1);
}
if (_currentMessage.length <= 10) {
// eslint-disable-next-line no-console
console.error(`\x1b[31m ${_currentMessage}提交的信息字数不得少于5个字符`);
process.exit(1);
}
process.exit(0);
}
#! /usr/bin/env node
/*
* @Author: 吴文洁
* @Date: 2020-06-05 09:38:03
* @LastEditors: 吴文洁
* @LastEditTime: 2020-09-02 15:45:50
* @Description:
* @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
*/
const execSync = require('child_process').execSync;
// 获取当前分支名称
const branchName = execSync('git rev-parse --abbrev-ref HEAD').toString().trim();
// 校验分支名是否合法
const firstPattern = new RegExp('dev|rc|gray|master');
const secondPattern = new RegExp('(feature|hotfix)/[a-z]{4,}/[0-9]{8,}/[a-zA-Z-]{4,}');
const firstMatch = firstPattern.test(branchName);
const secondMatch = secondPattern.test(branchName);
if (!firstMatch && !secondMatch) {
// eslint-disable-next-line no-console
console.error(`\x1b[31m ${branchName}不符合分支规范,具体规范请访问 http://wiki.ixm5.cn/pages/viewpage.action?pageId=2918496 \x1b[31m`);
process.exit(1);
}
// 获取缓存区内容
// 通过diff指令获得所有改动过(不包括删除)的js文件路径
const fileNameStr = execSync('git diff --diff-filter=AM --cached HEAD --name-only').toString();
const fileNameList = fileNameStr.split('\n').filter(item => !!item);
// 获取需要检测的文件
const detectedFileList = fileNameList.filter(file => {
// 过滤掉空的和hooks文件夹下所有的文件
return file && file.indexOf('hooks') < 0;
});
// 遍历需要检测的文件
let errorFileList = [];
detectedFileList.forEach((file) => {
const results = execSync(`git diff --cached ${file}`);
const pattern = /^http:\/\/{1,}/;
if (pattern.test(results.toString())) {
errorFileList.push(file);
}
});
if (errorFileList.length > 0) {
const errorFileStr = JSON.stringify(errorFileList);
// eslint-disable-next-line no-console
console.error(`\x1b[31m ${errorFileStr}文件中存在不合法的http://,请将http替换为https \x1b[31m`);
process.exit(1);
}
// 校验是否有冲突
const conflictPattern = new RegExp('^<<<<<<<\\s|^=======$|^>>>>>>>\\s');
const conflictFileList = [];
fileNameList.forEach((file) => {
const results = execSync(`git diff --cached ${file}`);
if (conflictPattern.test(results)) {
conflictFileList.push(file);
}
})
if (conflictFileList.length > 0) {
const conflictFileStr = JSON.stringify(conflictFileList);
// eslint-disable-next-line no-console
console.error(`\x1b[31m ${conflictFileStr}文件中存在冲突,请解决冲突之后再提交 \x1b[31m`);
process.exit(1);
}
process.exit(0);
\ No newline at end of file
{
"name": "cloudclass",
"version": "0.1.0",
"private": true,
"homepage": "./",
"dependencies": {
"@babel/core": "7.9.0",
"@babel/plugin-transform-typescript": "^7.11.0",
"@babel/preset-typescript": "^7.10.4",
"@svgr/webpack": "4.3.3",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"@types/react": "^16.9.46",
"@types/react-dom": "^16.9.8",
"@types/react-router-dom": "^5.1.5",
"@types/underscore": "^1.10.22",
"@typescript-eslint/eslint-plugin": "^2.10.0",
"@typescript-eslint/parser": "^2.10.0",
"antd": "3.26.6",
"axios": "^0.20.0",
"babel-eslint": "10.1.0",
"babel-jest": "^24.9.0",
"babel-loader": "8.1.0",
"babel-plugin-jsx-control-statements": "^4.1.0",
"babel-plugin-named-asset-import": "^0.3.6",
"babel-preset-react-app": "^9.1.2",
"camelcase": "^5.3.1",
"case-sensitive-paths-webpack-plugin": "2.3.0",
"cross-env": "^7.0.2",
"css-loader": "3.4.2",
"dotenv": "8.2.0",
"dotenv-expand": "5.1.0",
"eslint": "^6.6.0",
"eslint-config-react-app": "^5.2.1",
"eslint-loader": "3.0.3",
"eslint-plugin-flowtype": "4.6.0",
"eslint-plugin-import": "2.20.1",
"eslint-plugin-jsx-a11y": "6.2.3",
"eslint-plugin-jsx-control-statements": "^2.2.1",
"eslint-plugin-react": "7.19.0",
"eslint-plugin-react-hooks": "^1.6.1",
"file-loader": "4.3.0",
"fs-extra": "^8.1.0",
"html-webpack-plugin": "4.0.0-beta.11",
"husky": "^4.2.5",
"identity-obj-proxy": "3.0.0",
"jest": "24.9.0",
"jest-environment-jsdom-fourteen": "1.0.1",
"jest-resolve": "24.9.0",
"jest-watch-typeahead": "0.4.2",
"less-loader": "^6.2.0",
"microevent": "^1.0.0",
"mini-css-extract-plugin": "0.9.0",
"optimize-css-assets-webpack-plugin": "5.0.3",
"pnp-webpack-plugin": "1.6.4",
"postcss-flexbugs-fixes": "4.1.0",
"postcss-loader": "3.0.0",
"postcss-normalize": "8.0.1",
"postcss-preset-env": "6.7.0",
"postcss-safe-parser": "4.0.1",
"react": "^16.13.1",
"react-app-polyfill": "^1.0.6",
"react-dev-utils": "^10.2.1",
"react-dom": "^16.13.1",
"react-router-dom": "^5.2.0",
"resolve": "1.15.0",
"resolve-url-loader": "3.1.1",
"semver": "6.3.0",
"style-loader": "0.23.1",
"terser-webpack-plugin": "2.3.8",
"ts-pnp": "1.1.6",
"typescript": "^4.0.2",
"underscore": "^1.10.2",
"url-loader": "2.3.0",
"webpack": "4.42.0",
"webpack-dev-server": "3.11.0",
"webpack-manifest-plugin": "2.2.0",
"wheat-common-utils": "^3.8.12",
"workbox-webpack-plugin": "4.3.1",
"xiaomai-b-components": "1.4.4"
},
"scripts": {
"start": "node scripts/start.js",
"build:dev": "cross-env DEPLOY_ENV=dev node scripts/build.js",
"build:dev1": "cross-env DEPLOY_ENV=dev node scripts/build.js",
"build:rc": "cross-env DEPLOY_ENV=rc node scripts/build.js",
"build:gray": "cross-env DEPLOY_ENV=gray node scripts/build.js",
"build:prod": "cross-env DEPLOY_ENV=prod node scripts/build.js"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"babel": {
"presets": [
"react-app"
],
"plugins": [
"jsx-control-statements"
]
},
"husky": {
"hooks": {
"pre-commit": "node hooks/pre-commit.js",
"commit-msg": "node hooks/commit-msg.js",
"pre-push": "node hooks/pre-commit.js"
}
}
}
<!--
* @Author: 吴文洁
* @Date: 2020-08-24 12:20:57
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-27 10:10:06
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
<script type="text/javascript" src="https://image.xiaomaiketang.com/xm/PhotoClip.js"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
'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';
// 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.
require('../config/env');
const path = require('path');
const chalk = require('react-dev-utils/chalk');
const fs = require('fs-extra');
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);
// 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);
}
// Generate configuration
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');
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);
})
.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);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
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(
'\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'
);
} else {
console.log(chalk.green('Compiled successfully.\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();
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';
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
);
printBuildError(err);
} else {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
}
)
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
console.log('Creating an optimized production build...');
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 (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage +=
'\nCompileError: Begins at CSS selector ' +
err['postcssNode'].selector;
}
messages = formatWebpackMessages({
errors: [errMessage],
warnings: [],
});
} else {
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;
}
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
) {
console.log(
chalk.yellow(
'\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,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}
'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';
// 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.
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 {
choosePort,
createCompiler,
prepareProxy,
prepareUrls,
} = require('react-dev-utils/WebpackDevServerUtils');
const openBrowser = require('react-dev-utils/openBrowser');
const paths = require('../config/paths');
const configFactory = require('../config/webpack.config');
const createDevServerConfig = require('../config/webpackDevServer.config');
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);
}
// Tools like Cloud9 rely on this.
const DEFAULT_PORT = parseInt(process.env.PORT, 10) || 3000;
const HOST = process.env.HOST || '0.0.0.0';
if (process.env.HOST) {
console.log(
chalk.cyan(
`Attempting to bind to HOST environment variable: ${chalk.yellow(
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://bit.ly/CRA-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');
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);
})
.then(port => {
if (port == null) {
// We have not found a port.
return;
}
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 devSocket = {
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,
config,
devSocket,
urls,
useYarn,
useTypeScript,
tscCompileOnError,
webpack,
});
// Load proxy config
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);
devServer.headers = {
'Access-Control-Allow-Origin': '*',
};
// Launch WebpackDevServer.
devServer.listen(port, HOST, err => {
if (err) {
return console.log(err);
}
if (isInteractive) {
clearConsole();
}
// We used to support resolving modules according to `NODE_PATH`.
// This now has been deprecated in favor of jsconfig/tsconfig.json
// This lets you use absolute paths in imports inside large monorepos:
if (process.env.NODE_PATH) {
console.log(
chalk.yellow(
'Setting NODE_PATH to resolve modules absolutely has been deprecated in favor of setting baseUrl in jsconfig.json (or tsconfig.json if you are using TypeScript) and will be removed in a future major release of create-react-app.'
)
);
console.log();
}
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();
});
});
if (isInteractive || process.env.CI !== 'true') {
// Gracefully exit when stdin ends
process.stdin.on('end', function() {
devServer.close();
process.exit();
});
process.stdin.resume();
}
})
.catch(err => {
if (err && err.message) {
console.log(err.message);
}
process.exit(1);
});
'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.PUBLIC_URL = '';
// 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.
require('../config/env');
const jest = require('jest');
const execSync = require('child_process').execSync;
let argv = process.argv.slice(2);
function isInGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function isInMercurialRepository() {
try {
execSync('hg --cwd . root', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
// Watch unless on CI or explicitly running all tests
if (
!process.env.CI &&
argv.indexOf('--watchAll') === -1 &&
argv.indexOf('--watchAll=false') === -1
) {
// https://github.com/facebook/create-react-app/issues/5210
const hasSourceControl = isInGitRepository() || isInMercurialRepository();
argv.push(hasSourceControl ? '--watch' : '--watchAll');
}
jest.run(argv);
/*
* @Author: 吴文洁
* @Date: 2020-08-19 18:11:13
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:50:53
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
interface Window {
[key: string]: string,
RCHistory: any,
currentUserInstInfo: {
instId: string,
teacherId?: string,
name?: string
},
Service: any
}
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-29 19:16:17
* @LastEditors: 吴文洁
* @LastEditTime: 2020-04-30 10:45:06
* @Description:
*/
declare var If: React.SFC<{ condition: boolean }>;
declare var For: React.SFC<{ each: string; index?: string; of: any[] }>;
declare var Choose: React.SFC;
declare var When: React.SFC<{ condition: boolean }>;
declare var Otherwise: React.SFC;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-10-27 20:49:46
* @LastEditors: 吴文洁
* @LastEditTime: 2020-12-21 17:44:04
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
declare module 'microevent' {
const mixin: any;
export default mixin;
}
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-24 11:46:58
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-24 11:47:25
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />
declare namespace NodeJS {
interface ProcessEnv {
readonly NODE_ENV: 'development' | 'production';
readonly PUBLIC_URL: string;
}
}
declare module '*.bmp' {
const src: string;
export default src;
}
declare module '*.gif' {
const src: string;
export default src;
}
declare module '*.jpg' {
const src: string;
export default src;
}
declare module '*.jpeg' {
const src: string;
export default src;
}
declare module '*.png' {
const src: string;
export default src;
}
declare module '*.webp' {
const src: string;
export default src;
}
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<
SVGSVGElement
> & { title?: string }>;
const src: string;
export default src;
}
declare module '*.module.css' {
const classes: { readonly [key: string]: string };
export default classes;
}
declare module '*.module.less' {
const classes: { readonly [key: string]: string };
export default classes;
}
\ No newline at end of file
import React from 'react';
import { Route } from 'react-router-dom';
import { Layout } from 'antd';
import allRoutes from '@/routes';
import { RouteConfig } from '@/routes/interface';
const { Content } = Layout;
class App extends React.Component {
render() {
return (
<div className="app">
<div className="content__body">
<Content>
{
allRoutes.map((route: RouteConfig) => {
return (
<Route
key={route.path}
component={route.component}
path={route.path}
exact={route.exact}
/>
)
})
}
</Content>
</div>
</div>
)
}
}
export default App;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-31 09:34:31
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:35:36
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosPromise } from 'axios';
import { message } from 'antd';
import { BASIC_HOST, TIME_OUT, USER_TYPE, VERSION, PROJECT } from '@/domains/basic-domain/constants';
import User from './user';
interface FetchParams {
url: string,
data: any,
options?: FetchOptions
}
interface FetchOptions {
requestType: string // 请求类型 form为表单类型 json为json类型,默认json类型
}
class Axios {
static post(
method: string,
url: string,
params: any,
options: FetchOptions = { requestType: 'json' }
): Promise<any> {
const _url = `${url}?p=w&v=v${VERSION}&userType=${USER_TYPE}&token=${User.getToken()}&uid=${User.getUid()}&tid=${User.getTid()}&aid=${User.getAid()}`;
return new Promise((resolve, reject) => {
const { NewVersion, currentUserInstInfo } = window;
const { instId } = currentUserInstInfo;
const instance: AxiosInstance = axios.create({
timeout: TIME_OUT,
responseType: 'json',
headers: {
instId,
p: 'w',
v: 'VERSION',
vn: `v${VERSION}`,
project: PROJECT,
userType: USER_TYPE,
cid: User.getCid(),
uid: User.getUid(),
tid: User.getTid(),
token: User.getToken(),
bizAccountId: User.getAid(),
xmVersion: NewVersion ? '5.0' : '4.0',
'Content-Type': options.requestType === 'json' ? 'application/json; charset=UTF-8' : 'application/x-www-form-urlencoded',
}
});
if (method !== 'GET' && options.requestType === 'form') {
instance.defaults.transformRequest = [(queryParam): string => {
let ret: string = '';
const queryKeys = Object.keys(queryParam);
queryKeys.forEach((item: string, index: number): void => {
if (index < queryKeys.length - 1) {
ret += `${encodeURIComponent(item)}=${encodeURIComponent(queryParam[item])}&`;
} else {
ret += `${encodeURIComponent(item)}=${encodeURIComponent(queryParam[item])}`;
}
});
ret.replace(/&$/, '');
return ret;
}]
}
instance.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
return config;
}, (error: Error): Promise<any> => {
return Promise.reject(error);
})
instance.interceptors.response.use((response: AxiosResponse): AxiosResponse | AxiosPromise => {
const { message: ResMessage, success, resultMsg, resultCode } = response.data;
if (success || resultCode === 0) {
return response;
}
message.error(ResMessage || resultMsg);
return Promise.reject(response.data);
}, (error): AxiosPromise => {
message.error(error.message)
return Promise.reject(error.message);
});
let config: any;
if (method === 'GET') {
config = Object.assign({ params, url: `${BASIC_HOST}${_url}`, method });
} else {
config = Object.assign({ data: params, url: `${BASIC_HOST}${_url}`, method });
}
instance(config).then((res: AxiosResponse): void => {
resolve(res.data);
}).catch((error: Error) => {
reject(error);
})
})
}
}
export default Axios;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-31 09:34:51
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:35:25
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import Axios from './axios';
class Service {
static Business(url: string, params: any, option: any) {
return Axios.post('POST', `business/${url}`, params, option);
}
static Apollo(url: string, params: any, option: any) {
return Axios.post('POST', `apollo/${url}`, params, option);
}
static Sales(url: string, params: any, option: any) {
return Axios.post('POST', `sales/${url}`, params, option);
}
static post(url: string, params: any, option: any) {
return Axios.post('POST', url, params, option);
}
}
export default Service;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-31 09:34:36
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:35:14
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import { XMStorageImplements } from '@/domains/basic-domain/interface';
const LS: Storage = window.localStorage;
class XMStorage implements XMStorageImplements {
supportLocalStorage() {
return !!LS;
}
get(key: string) {
if (this.supportLocalStorage()) {
return LS.getItem(key);
}
}
set(key: string, value: any) {
if (this.supportLocalStorage()) {
LS.setItem(key, value);
}
}
setObj(key: string, obj: any) {
if (this.supportLocalStorage()) {
LS.setItem(key, JSON.stringify(obj));
}
}
getObj(key: string) {
let value: null | string = null;
if (this.supportLocalStorage()) {
const LSItem = LS.getItem(key);
try {
if (LSItem) {
value = JSON.parse(LSItem);
}
} catch (error) {
value = LSItem;
}
}
return value;
}
remove(key: string) {
if (this.supportLocalStorage()) {
LS.removeItem(key);
}
}
clear() {
if (this.supportLocalStorage()) {
LS.clear();
}
}
}
export default new XMStorage();
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-31 09:34:25
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:54:34
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import Storage from './storage';
import { PREFIX } from '@/domains/basic-domain/constants';
class User {
getUid() {
return Storage.get(`${PREFIX}_uid`) || '1115167164014264433';
}
getAid() {
return Storage.get(`${PREFIX}_aid`) || '1298172751712686082';
}
getTid() {
return Storage.get(`${PREFIX}_tid`) || '1298172751712686082';
}
getCid() {
return Storage.get(`${PREFIX}_cid`);
}
getToken() {
return Storage.get(`${PREFIX}_token`) || 'f24733242f634815a30184dfa5edf9b6';
}
}
export default new User();
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-28 19:24:31
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:46:49
* @Description: 重写antd的样式
*/
.ant-layout-content {
height: 100vh;
padding: 16px;
background-color: #F0F2F5;
}
\ No newline at end of file
@import './normalize.less';
@import './antd-override.less';
@import './variable.less';
.page-body {
background: #fff;
padding: 16px;
margin-top: 16px;
}
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-28 18:14:52
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:36:52
* @Description: 样式格式化
*/
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
// color
@xm-color-primary: #FF7519;
// fonst-size
@xm-font-size-m: 14px;
\ No newline at end of file
<!--
* @Author: 吴文洁
* @Date: 2020-04-29 16:55:55
* @LastEditors: 吴文洁
* @LastEditTime: 2020-04-29 17:15:09
* @Description:
-->
### 全局公用组件
**本目录的引用别名是 @/components**
\ No newline at end of file
<!--
* @Author: 吴文洁
* @Date: 2020-04-29 16:57:38
* @LastEditors: 吴文洁
* @LastEditTime: 2020-04-29 17:02:39
* @Description:
-->
### 与后台的数据交互层(承担防腐重任)
**本目录的引用别名是 @/data-source**
request-apis.js和translators注意都是 复数。
translators.js 为前后端字段(or 数据结构)转换的方法集合。(防腐层)
### 注意:接口请求的所有返回数据结构,必须经过 translator 转后成与前端 domain 中的结构匹配后才能用于视图层。
<!--
* @Author: 吴文洁
* @Date: 2020-04-29 17:03:23
* @LastEditors: 吴文洁
* @LastEditTime: 2020-04-29 17:18:38
* @Description:
-->
### 本目录为“各个子域的集合”,所有领域的公共部分均放在这里
**本目录的 别名为 @/domains**
Service连接视图层和数据层
注意: Service 类中只有 static 方法。
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-12-21 17:40:39
* @LastEditors: 吴文洁
* @LastEditTime: 2020-12-21 17:43:40
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import MicroEvent from 'microevent';
class Bus {
public bind(key: string, fn: Function) {};
public unbind(key: string) {};
};
MicroEvent.mixin(Bus);
export default new Bus();
\ No newline at end of file
/*
* @Author: 陈剑宇
* @Date: 2020-05-07 14:43:01
* @LastEditTime: 2020-11-09 09:52:03
* @LastEditors: 吴文洁
* @Description:
* @FilePath: /wheat-web-demo/src/domains/basic-domain/constants.ts
*/
import { MapInterface } from '@/domains/basic-domain/interface'
// 默认是 dev 环境
const ENV: string = process.env.DEPLOY_ENV || 'dev';
const BASIC_HOST_MAP: MapInterface = {
dev: 'https://dev-heimdall.xiaomai5.com/',
dev1: 'https://dev1-heimdall.xiaomai5.com/',
rc: 'https://rc-heimdall.xiaomai5.com/',
gray: 'https://gray-heimdall.xiaomai5.com/',
prod: 'https://gateway-heimdall.xiaomai5.com/'
};
// axios headers config
export const TIME_OUT: number = 20000;
export const USER_TYPE: string = 'B';
export const PROJECT = 'xmzj-web-b';
export const VERSION = '5.4.8';
export const PREFIX = 'xiaomai';
// host
export const BASIC_HOST: string = BASIC_HOST_MAP[ENV];
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-28 18:10:07
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-31 09:36:22
* @Description: 系统interface
*/
export interface VerifyInfo {
aid: string | undefined,
tid: string | undefined,
cid: string | undefined,
uid: string | undefined,
token: string | undefined,
}
// constants.ts
export interface MapInterface {
dev: string,
dev1: string,
rc: string,
gray: string,
prod: string,
[key: string]: any,
}
export interface XMStorageImplements {
get: (key: string) => any,
set: (key: string, value: any) => void,
getObj: (key: string) => any,
setObj: (key: string, obj: any) => void,
remove: (key: string) => void,
clear: () => void,
}
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-10-27 18:53:43
* @LastEditors: 吴文洁
* @LastEditTime: 2020-12-21 17:42:22
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
import Service from '@/common/js/service';
class Upload {
static uploadBlobToOSS(Blob: any, name: string, dataType: string = 'url') {
const { instId } = window.currentUserInstInfo;
return Service.MFS('anon/mfs/webTokenWithAccessUrl', {
instId,
resourceName: name,
}).then((res) => {
const signInfo = res.result;
const { url } = res.result
return this.uploadBlobToNewOSS(Blob, name, signInfo.signatureVO || signInfo).then(() => {
return dataType === 'url' ? url : signInfo
});
})
};
static uploadBlobToNewOSS(Blob: any, name: string, signInfo: any) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
const fd = new FormData();
fd.append('OSSAccessKeyId', signInfo.accessId);
fd.append('policy', signInfo.policy);
fd.append('callback', signInfo.callback);
fd.append('Filename', name);
fd.append('expire', signInfo.expire);
fd.append('signature', signInfo.signature);
fd.append('key', signInfo.key);
fd.append('file', Blob);
fd.append('success_action_status', '200');
xhr.open('POST', signInfo.host.replace(/http:/, "https:"), true);
xhr.onload = () => {
const result = JSON.parse(xhr.responseText);
resolve(result.url);
}
xhr.send(fd);
});
};
}
export default Upload;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-08-20 09:20:43
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-21 09:02:36
* @Description:
* @Copyright: 杭州杰竞科技有限公司 版权所有
*/
// 限制字数
const getEllipsText = (text: string, limitNum: number) => {
const limitText: string = text.replace(/\n/g, ' ');
if (limitText.length > limitNum) {
return `${limitText.substr(0, limitNum)}...`;
}
return limitText;
}
export {
getEllipsText
}
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-27 20:35:34
* @LastEditors: zhangleyuan
* @LastEditTime: 2021-01-04 18:23:21
* @Description:
*/
import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter } from 'react-router-dom';
import { ConfigProvider } from 'antd';
import { createHashHistory } from 'history';
import zh_CN from 'antd/es/locale/zh_CN';
import _ from 'underscore';
import Storage from '@/common/js/storage';
import { PREFIX } from '@/domains/basic-domain/constants';
import { VerifyInfo } from '@/domains/basic-domain/interface';
import 'antd/dist/antd.less';
import '@/common/less/index.less';
import App from './App';
import '@/common/less/index.less';
const history = createHashHistory();
window.RCHistory = _.extend({}, history, {
push: (obj: any) => {
history.push(obj)
},
pushState: (obj: any) => {
history.push(obj)
},
pushStateWithStatus: (obj: any) => {
history.push(obj)
},
goBack: history.goBack,
location: history.location,
replace: (obj: any) => {
history.replace(obj)
}
});
export async function mount(props: any) {
ReactDOM.render((
<HashRouter {...history} >
<ConfigProvider locale={zh_CN}>
<App />
</ConfigProvider>
</HashRouter>
), document.getElementById('root'));
}
mount();
import React from 'react';
import { Table } from 'antd';
import Service from '@/common/js/service';
import './index.less';
class VideoCourse extends React.Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
}
render() {
const { dataSource } = this.state;
return (
<div className="video-course">
<div className="page-header">视频课</div>
</div>
)
}
}
export default VideoCourse;
.video-course {
.operate {
display: flex;
&__item {
color: #FF7519;
cursor: pointer;
&.split {
margin: 0 8px;
}
}
}
}
\ No newline at end of file
<!--
* @Author: 吴文洁
* @Date: 2020-04-29 10:18:07
* @LastEditors: 吴文洁
* @LastEditTime: 2020-04-29 10:18:23
* @Description:
-->
### 各个领域下的路由配置
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-29 10:26:32
* @LastEditors: 吴文洁
* @LastEditTime: 2020-12-21 17:44:31
* @Description: 内容线路由配置
*/
import { MenuConfig } from '@/routes/interface';
import VideoCourse from '@/modules/video-course';
const CloudClassConfig: MenuConfig = {
key: 'cloudClass',
name: '云课堂',
routes: [
{
key: 'video_course',
name: '视频课',
path: '/cloudclass/video_course',
component: VideoCourse
}
]
};
export default CloudClassConfig;
\ No newline at end of file
/*
* @Author: 吴文洁
* @Date: 2020-04-28 18:05:30
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-13 11:23:36
* @Description:
*/
import { MenuConfig, RouteConfig } from '@/routes/interface';
import CloudClass from './config/cloudClass';
// 领域路由配置
export const menuConfigs: MenuConfig[] = [ CloudClass ];
/** 所有处理后的路由的集合,用于生成Route组件 */
const allRoutes: RouteConfig[] = menuConfigs.map((config: MenuConfig) => {
return config.routes || [];
}).reduce((prev: RouteConfig[], next: RouteConfig[]) => {
return prev.concat(...next);
});
export default allRoutes;
/*
* @Author: 吴文洁
* @Date: 2020-04-28 18:10:07
* @LastEditors: 吴文洁
* @LastEditTime: 2020-08-13 10:59:08
* @Description:
*/
/** 路由配置,最终解析后转给<Route>组件 */
export interface RouteConfig {
/** 标题,用于route组件和kio的description */
name?: string;
/** 子菜单key */
key?: string;
/** 子菜单路径 */
path?: string;
component?: React.ComponentType<any>;
// 是否精确匹配
exact?: boolean;
}
/** 左侧的菜单配置 */
export interface MenuConfig {
// 菜单名称
name: string;
// 菜单key
key: string;
// 菜单对应的路由
path?: string;
// 子路由
routes?: RouteConfig[];
}
\ No newline at end of file
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
type Config = {
onSuccess?: (registration: ServiceWorkerRegistration) => void;
onUpdate?: (registration: ServiceWorkerRegistration) => void;
};
export function register(config?: Config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(
process.env.PUBLIC_URL,
window.location.href
);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl: string, config?: Config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl: string, config?: Config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, {
headers: { 'Service-Worker': 'script' }
})
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready
.then(registration => {
registration.unregister();
})
.catch(error => {
console.error(error.message);
});
}
}
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"baseUrl": "src",
"paths": {
"@/*": ["*"]
}
},
"include": [
"src"
]
}
{
"extends": [
"tslint:recommended",
"tslint-react"
],
"rules": {
"indent": [true, "spaces", 2],
"space-before-function-paren": false,
"no-angle-bracket-type-assertion": false,
"callable-types": false,
"unified-signatures": false,
"no-string-throw": false,
"ban-types": false,
"no-console": [true, "debug", "info", "log", "time", "timeEnd", "trace"],
"no-unnecessary-initializer": false,
"force-empty-line-after-jsx-annotation": true,
"jsx-alignment": false,
"jsx-no-multiline-js": false,
"jsx-wrap-multiline": false,
"jsx-no-string-ref": false,
"jsx-self-close": false,
"quotemark": [true, "single", "jsx-double"],
"member-access": false,
"arrow-parens": false,
"object-literal-sort-keys": false,
"member-ordering": [false],
"variable-name": false,
"no-var-requires": false,
"only-arrow-functions": [false],
"no-reference": false,
"trailing-comma": [false],
"prefer-const": true,
"no-namespace": [true, "allow-declarations"],
"no-empty-interface": false,
"max-line-length": [true, 200],
"react/jsx-no-undef": [2, { "allowGlobals": true }]
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment