适配staging环境

This commit is contained in:
wkj 2024-04-25 16:58:47 +08:00
parent 6d336d19c6
commit 7e72576914
14 changed files with 234 additions and 275 deletions

View File

@ -9,12 +9,8 @@ const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const UiExtractPlugin = require('ui-extract-webpack-plugin'); const UiExtractPlugin = require('ui-extract-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin');
const ForkTsCheckerWebpackPlugin = const ForkTsCheckerWebpackPlugin = require('./../../plugins/ForkTsCheckerWarningWebpackPlugin');
process.env.TSC_COMPILE_ON_ERROR === 'true' const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
? require('./../../plugins/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const BundleAnalyzerPlugin =
require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const OakWeChatMpPlugin = require('../../plugins/WechatMpPlugin'); const OakWeChatMpPlugin = require('../../plugins/WechatMpPlugin');
@ -46,8 +42,10 @@ const copyPatterns = [].concat(pkg.copyWebpack || []).map((pattern) =>
const oakRegex = /(\/*[a-zA-Z0-9_-])*\/(lib|src|es)\/|(\\*[a-zA-Z0-9_-])*\\(lib|src|es)\\/; const oakRegex = /(\/*[a-zA-Z0-9_-])*\/(lib|src|es)\/|(\\*[a-zA-Z0-9_-])*\\(lib|src|es)\\/;
module.exports = function (webpackEnv) { module.exports = function (webpackEnv) {
// staging 把mode改为none其他跟production一样
const isEnvStaging = webpackEnv === 'staging';
const isEnvDevelopment = webpackEnv === 'development'; const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production'; const isEnvProduction = webpackEnv === 'production' || isEnvStaging;
const oakFileLoader = (ext = '[ext]') => { const oakFileLoader = (ext = '[ext]') => {
return { return {
@ -91,7 +89,9 @@ module.exports = function (webpackEnv) {
target: ['web'], target: ['web'],
// Webpack noise constrained to errors and warnings // Webpack noise constrained to errors and warnings
stats: 'errors-warnings', stats: 'errors-warnings',
mode: isEnvProduction mode: isEnvStaging
? 'none'
: isEnvProduction
? 'production' ? 'production'
: isEnvDevelopment && 'development', : isEnvDevelopment && 'development',
// Stop compilation early in production // Stop compilation early in production
@ -325,9 +325,7 @@ module.exports = function (webpackEnv) {
name: 'oak-debugPanel', name: 'oak-debugPanel',
show: !isEnvProduction, show: !isEnvProduction,
}, },
split: isEnvProduction split: isEnvProduction ? true : false,
? true
: isEnvDevelopment && process.env.SPLIT === 'true',
}), }),
new webpack.DefinePlugin(env.stringified), new webpack.DefinePlugin(env.stringified),
new StylelintPlugin({ new StylelintPlugin({
@ -352,19 +350,6 @@ module.exports = function (webpackEnv) {
typescriptPath: resolve.sync('typescript', { typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules, basedir: paths.appNodeModules,
}), }),
// configOverwrite: {
// compilerOptions: {
// sourceMap: isEnvProduction
// ? shouldUseSourceMap
// : isEnvDevelopment,
// skipLibCheck: true,
// inlineSourceMap: false,
// declarationMap: false,
// noEmit: true,
// incremental: true,
// tsBuildInfoFile: paths.appTsBuildInfoFile,
// },
// },
configFile: paths.appTsConfig, configFile: paths.appTsConfig,
context: paths.appRootPath, context: paths.appRootPath,
diagnosticOptions: { diagnosticOptions: {

View File

@ -20,13 +20,9 @@ const paths = require('./paths');
const modules = require('./modules'); const modules = require('./modules');
const getClientEnvironment = require('./env'); const getClientEnvironment = require('./env');
const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin'); const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
const ForkTsCheckerWebpackPlugin = const ForkTsCheckerWebpackPlugin = require('./../../plugins/ForkTsCheckerWarningWebpackPlugin');
process.env.TSC_COMPILE_ON_ERROR === 'true'
? require('./../../plugins/ForkTsCheckerWarningWebpackPlugin')
: require('react-dev-utils/ForkTsCheckerWebpackPlugin');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin'); const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const BundleAnalyzerPlugin = const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const CompressionWebpackPlugin = require('compression-webpack-plugin'); const CompressionWebpackPlugin = require('compression-webpack-plugin');
const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash'); const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
@ -102,6 +98,8 @@ const hasJsxRuntime = (() => {
// This is the production and development configuration. // This is the production and development configuration.
// It is focused on developer experience, fast rebuilds, and a minimal bundle. // It is focused on developer experience, fast rebuilds, and a minimal bundle.
module.exports = function (webpackEnv) { module.exports = function (webpackEnv) {
// staging 把mode改为none其他跟production一样
const isEnvStaging = webpackEnv === 'staging';
const isEnvDevelopment = webpackEnv === 'development'; const isEnvDevelopment = webpackEnv === 'development';
const isEnvProduction = webpackEnv === 'production'; const isEnvProduction = webpackEnv === 'production';
@ -118,7 +116,6 @@ module.exports = function (webpackEnv) {
const shouldUseReactRefresh = env.raw.FAST_REFRESH; const shouldUseReactRefresh = env.raw.FAST_REFRESH;
// common function to get style loaders // common function to get style loaders
const getStyleLoaders = (cssOptions, preProcessor, preProcessOptions) => { const getStyleLoaders = (cssOptions, preProcessor, preProcessOptions) => {
const loaders = [ const loaders = [
@ -148,34 +145,34 @@ module.exports = function (webpackEnv) {
config: false, config: false,
plugins: !useTailwind plugins: !useTailwind
? [ ? [
'postcss-flexbugs-fixes', 'postcss-flexbugs-fixes',
[ [
'postcss-preset-env', 'postcss-preset-env',
{ {
autoprefixer: { autoprefixer: {
flexbox: 'no-2009', flexbox: 'no-2009',
}, },
stage: 3, stage: 3,
}, },
], ],
// Adds PostCSS Normalize as the reset css with default options, // Adds PostCSS Normalize as the reset css with default options,
// so that it honors browserslist config in package.json // so that it honors browserslist config in package.json
// which in turn let's users customize the target behavior as per their needs. // which in turn let's users customize the target behavior as per their needs.
'postcss-normalize', 'postcss-normalize',
] ]
: [ : [
'tailwindcss', 'tailwindcss',
'postcss-flexbugs-fixes', 'postcss-flexbugs-fixes',
[ [
'postcss-preset-env', 'postcss-preset-env',
{ {
autoprefixer: { autoprefixer: {
flexbox: 'no-2009', flexbox: 'no-2009',
}, },
stage: 3, stage: 3,
}, },
], ],
], ],
}, },
sourceMap: isEnvProduction sourceMap: isEnvProduction
? shouldUseSourceMap ? shouldUseSourceMap
@ -196,9 +193,12 @@ module.exports = function (webpackEnv) {
}, },
{ {
loader: require.resolve(preProcessor), loader: require.resolve(preProcessor),
options: Object.assign({ options: Object.assign(
sourceMap: true, {
}, preProcessOptions), sourceMap: true,
},
preProcessOptions
),
} }
); );
} }
@ -206,14 +206,17 @@ module.exports = function (webpackEnv) {
}; };
// 读取编译配置 // 读取编译配置
const compilerConfigurationFile = path.join(paths.appRootPath, 'configuration', 'compiler.js'); const compilerConfigurationFile = path.join(
const projectConfiguration = fs.existsSync(compilerConfigurationFile) && require(compilerConfigurationFile).webpack; paths.appRootPath,
'configuration',
'compiler.js'
);
const projectConfiguration =
fs.existsSync(compilerConfigurationFile) &&
require(compilerConfigurationFile).webpack;
const getOakInclude = () => { const getOakInclude = () => {
const result = [ const result = [/oak-frontend-base/, /oak-general-business/];
/oak-frontend-base/,
/oak-general-business/,
];
if (projectConfiguration && projectConfiguration.extraOakModules) { if (projectConfiguration && projectConfiguration.extraOakModules) {
result.push(...projectConfiguration.extraOakModules); result.push(...projectConfiguration.extraOakModules);
} }
@ -260,14 +263,14 @@ module.exports = function (webpackEnv) {
// Point sourcemap entries to original disk location (format as URL on Windows) // Point sourcemap entries to original disk location (format as URL on Windows)
devtoolModuleFilenameTemplate: isEnvProduction devtoolModuleFilenameTemplate: isEnvProduction
? (info) => ? (info) =>
path path
.relative(paths.appSrc, info.absoluteResourcePath) .relative(paths.appSrc, info.absoluteResourcePath)
.replace(/\\/g, '/') .replace(/\\/g, '/')
: isEnvDevelopment && : isEnvDevelopment &&
((info) => ((info) =>
path path
.resolve(info.absoluteResourcePath) .resolve(info.absoluteResourcePath)
.replace(/\\/g, '/')), .replace(/\\/g, '/')),
}, },
cache: { cache: {
type: 'filesystem', type: 'filesystem',
@ -381,14 +384,14 @@ module.exports = function (webpackEnv) {
stream: require.resolve('stream-browserify'), stream: require.resolve('stream-browserify'),
zlib: require.resolve('browserify-zlib'), zlib: require.resolve('browserify-zlib'),
querystring: require.resolve('querystring-es3'), querystring: require.resolve('querystring-es3'),
events: path.resolve(__dirname, '../../node_modules/events'), events: require.resolve('events/'),
os: false, os: false,
url: false, url: false,
path: false, path: false,
fs: false, fs: false,
net: false, net: false,
tls: false, tls: false,
} };
if ( if (
projectConfiguration && projectConfiguration &&
projectConfiguration.resolve && projectConfiguration.resolve &&
@ -569,10 +572,10 @@ module.exports = function (webpackEnv) {
plugins: [ plugins: [
isEnvDevelopment && isEnvDevelopment &&
shouldUseReactRefresh && shouldUseReactRefresh &&
require.resolve( require.resolve(
'react-refresh/babel' 'react-refresh/babel'
), ),
oakPathTsxPlugin, oakPathTsxPlugin,
oakRenderTsxPlugin, oakRenderTsxPlugin,
// oakRouterPlugin, // oakRouterPlugin,
@ -787,14 +790,14 @@ module.exports = function (webpackEnv) {
}, },
plugins: [ plugins: [
isEnvProduction && isEnvProduction &&
new CompressionWebpackPlugin({ new CompressionWebpackPlugin({
filename: '[path][base].gz', //压缩后的文件名 filename: '[path][base].gz', //压缩后的文件名
algorithm: 'gzip', //压缩格式 有gzip、brotliCompress algorithm: 'gzip', //压缩格式 有gzip、brotliCompress
test: /\.(js|css|svg)$/, test: /\.(js|css|svg)$/,
threshold: 10240, // 只处理比这个值大的资源,按字节算 threshold: 10240, // 只处理比这个值大的资源,按字节算
minRatio: 0.8, //只有压缩率比这个值小的文件才会被处理,压缩率=压缩大小/原始大小,如果压缩后和原始文件大小没有太大区别,就不用压缩 minRatio: 0.8, //只有压缩率比这个值小的文件才会被处理,压缩率=压缩大小/原始大小,如果压缩后和原始文件大小没有太大区别,就不用压缩
deleteOriginalAssets: false, //是否删除原文件,最好不删除,服务器会自动优先返回同名的.gzip资源如果找不到还可以拿原始文件 deleteOriginalAssets: false, //是否删除原文件,最好不删除,服务器会自动优先返回同名的.gzip资源如果找不到还可以拿原始文件
}), }),
// Generates an `index.html` file with the <script> injected. // Generates an `index.html` file with the <script> injected.
new HtmlWebpackPlugin( new HtmlWebpackPlugin(
Object.assign( Object.assign(
@ -805,19 +808,19 @@ module.exports = function (webpackEnv) {
}, },
isEnvProduction isEnvProduction
? { ? {
minify: { minify: {
removeComments: true, removeComments: true,
collapseWhitespace: true, collapseWhitespace: true,
removeRedundantAttributes: true, removeRedundantAttributes: true,
useShortDoctype: true, useShortDoctype: true,
removeEmptyAttributes: true, removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true, removeStyleLinkTypeAttributes: true,
keepClosingSlash: true, keepClosingSlash: true,
minifyJS: true, minifyJS: true,
minifyCSS: true, minifyCSS: true,
minifyURLs: true, minifyURLs: true,
}, },
} }
: undefined : undefined
) )
), ),
@ -825,10 +828,10 @@ module.exports = function (webpackEnv) {
// a network request. // a network request.
// https://github.com/facebook/create-react-app/issues/5358 // https://github.com/facebook/create-react-app/issues/5358
isEnvProduction && isEnvProduction &&
shouldInlineRuntimeChunk && shouldInlineRuntimeChunk &&
new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [ new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [
/runtime-.+[.]js/, /runtime-.+[.]js/,
]), ]),
// Makes some environment variables available in index.html. // Makes some environment variables available in index.html.
// The public URL is available as %PUBLIC_URL% in index.html, e.g.: // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
// <link rel="icon" href="%PUBLIC_URL%/favicon.ico"> // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
@ -847,22 +850,22 @@ module.exports = function (webpackEnv) {
// Experimental hot reloading for React . // Experimental hot reloading for React .
// https://github.com/facebook/react/tree/main/packages/react-refresh // https://github.com/facebook/react/tree/main/packages/react-refresh
isEnvDevelopment && isEnvDevelopment &&
shouldUseReactRefresh && shouldUseReactRefresh &&
new ReactRefreshWebpackPlugin({ new ReactRefreshWebpackPlugin({
overlay: false, overlay: false,
}), }),
// Watcher doesn't work well if you mistype casing in a path so we use // Watcher doesn't work well if you mistype casing in a path so we use
// a plugin that prints an error when you attempt to do this. // a plugin that prints an error when you attempt to do this.
// See https://github.com/facebook/create-react-app/issues/240 // See https://github.com/facebook/create-react-app/issues/240
isEnvDevelopment && new CaseSensitivePathsPlugin(), isEnvDevelopment && new CaseSensitivePathsPlugin(),
isEnvProduction && isEnvProduction &&
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output // Options similar to the same options in webpackOptions.output
// both options are optional // both options are optional
filename: 'static/css/[name].[contenthash:8].css', filename: 'static/css/[name].[contenthash:8].css',
chunkFilename: chunkFilename:
'static/css/[name].[contenthash:8].chunk.css', 'static/css/[name].[contenthash:8].chunk.css',
}), }),
// Generate an asset manifest file with the following content: // Generate an asset manifest file with the following content:
// - "files" key: Mapping of all asset filenames to their corresponding // - "files" key: Mapping of all asset filenames to their corresponding
// output file so that tools can pick it up without having to parse // output file so that tools can pick it up without having to parse
@ -899,136 +902,123 @@ module.exports = function (webpackEnv) {
// Generate a service worker script that will precache, and keep up to date, // Generate a service worker script that will precache, and keep up to date,
// the HTML & assets that are part of the webpack build. // the HTML & assets that are part of the webpack build.
isEnvProduction && isEnvProduction &&
fs.existsSync(swSrc) && fs.existsSync(swSrc) &&
new WorkboxWebpackPlugin.InjectManifest({ new WorkboxWebpackPlugin.InjectManifest({
swSrc, swSrc,
dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./, dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/], exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
// Bump up the default maximum size (2mb) that's precached, // Bump up the default maximum size (2mb) that's precached,
// to make lazy-loading failure scenarios less likely. // to make lazy-loading failure scenarios less likely.
// See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270 // See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024, maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}), }),
// TypeScript type checking // TypeScript type checking
useTypeScript && useTypeScript &&
new ForkTsCheckerWebpackPlugin({ new ForkTsCheckerWebpackPlugin({
async: isEnvDevelopment, async: isEnvDevelopment,
typescript: { typescript: {
typescriptPath: resolve.sync('typescript', { typescriptPath: resolve.sync('typescript', {
basedir: paths.appNodeModules, basedir: paths.appNodeModules,
}),
// configOverwrite: {
// compilerOptions: {
// sourceMap: isEnvProduction
// ? shouldUseSourceMap
// : isEnvDevelopment,
// skipLibCheck: true,
// inlineSourceMap: false,
// declarationMap: false,
// noEmit: true,
// incremental: true,
// tsBuildInfoFile: paths.appTsBuildInfoFile,
// },
// },
configFile: paths.appTsConfig,
context: paths.appRootPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
memoryLimit,
},
issue: {
// This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/app/**/*.{ts,tsx}' },
{ file: '**/app/**/*.{ts,tsx}' },
{ file: '../**/app/**/*.*.{ts,tsx}' },
{ file: '**/app/**/*.*.{ts,tsx}' },
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
{ file: '../**/src/**/*.*.{ts,tsx}' },
{ file: '**/src/**/*.*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
log: (message) => console.log(message),
error: (message) => console.error(message),
},
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve(
'react-dev-utils/eslintFormatter'
),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [
require.resolve('eslint-config-react-app/base'),
],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}), }),
configFile: paths.appTsConfig,
context: paths.appRootPath,
diagnosticOptions: {
syntactic: true,
},
mode: 'write-references',
// profile: true,
memoryLimit,
}, },
}, issue: {
}), // This one is specifically to match during CI tests,
// as micromatch doesn't match
// '../cra-template-typescript/template/src/App.tsx'
// otherwise.
include: [
{ file: '../**/app/**/*.{ts,tsx}' },
{ file: '**/app/**/*.{ts,tsx}' },
{ file: '../**/app/**/*.*.{ts,tsx}' },
{ file: '**/app/**/*.*.{ts,tsx}' },
{ file: '../**/src/**/*.{ts,tsx}' },
{ file: '**/src/**/*.{ts,tsx}' },
{ file: '../**/src/**/*.*.{ts,tsx}' },
{ file: '**/src/**/*.*.{ts,tsx}' },
],
exclude: [
{ file: '**/src/**/__tests__/**' },
{ file: '**/src/**/?(*.){spec|test}.*' },
{ file: '**/src/setupProxy.*' },
{ file: '**/src/setupTests.*' },
],
},
logger: {
log: (message) => console.log(message),
error: (message) => console.error(message),
},
}),
!disableESLintPlugin &&
new ESLintPlugin({
// Plugin options
extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
formatter: require.resolve(
'react-dev-utils/eslintFormatter'
),
eslintPath: require.resolve('eslint'),
failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
context: paths.appSrc,
cache: true,
cacheLocation: path.resolve(
paths.appNodeModules,
'.cache/.eslintcache'
),
// ESLint class options
cwd: paths.appPath,
resolvePluginsRelativeTo: __dirname,
baseConfig: {
extends: [
require.resolve('eslint-config-react-app/base'),
],
rules: {
...(!hasJsxRuntime && {
'react/react-in-jsx-scope': 'error',
}),
},
},
}),
new webpack.ProvidePlugin({ new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'], Buffer: ['buffer', 'Buffer'],
}), }),
shouldAnalyze && shouldAnalyze &&
new BundleAnalyzerPlugin({ new BundleAnalyzerPlugin({
// 可以是`server``static`或`disabled`。 // 可以是`server``static`或`disabled`。
// 在`server`模式下分析器将启动HTTP服务器来显示软件包报告。 // 在`server`模式下分析器将启动HTTP服务器来显示软件包报告。
// 在“静态”模式下会生成带有报告的单个HTML文件。 // 在“静态”模式下会生成带有报告的单个HTML文件。
// 在`disabled`模式下,你可以使用这个插件来将`generateStatsFile`设置为`true`来生成Webpack Stats JSON文件。 // 在`disabled`模式下,你可以使用这个插件来将`generateStatsFile`设置为`true`来生成Webpack Stats JSON文件。
analyzerMode: 'server', analyzerMode: 'server',
// 将在“服务器”模式下使用的主机启动HTTP服务器。 // 将在“服务器”模式下使用的主机启动HTTP服务器。
analyzerHost: '127.0.0.1', analyzerHost: '127.0.0.1',
// 将在“服务器”模式下使用的端口启动HTTP服务器。 // 将在“服务器”模式下使用的端口启动HTTP服务器。
analyzerPort: 8888, analyzerPort: 8888,
// 路径捆绑,将在`static`模式下生成的报告文件。 // 路径捆绑,将在`static`模式下生成的报告文件。
// 相对于捆绑输出目录。 // 相对于捆绑输出目录。
reportFilename: 'report.html', reportFilename: 'report.html',
// 模块大小默认显示在报告中。 // 模块大小默认显示在报告中。
// 应该是`stat``parsed`或者`gzip`中的一个。 // 应该是`stat``parsed`或者`gzip`中的一个。
// 有关更多信息,请参见“定义”一节。 // 有关更多信息,请参见“定义”一节。
defaultSizes: 'parsed', defaultSizes: 'parsed',
// 在默认浏览器中自动打开报告 // 在默认浏览器中自动打开报告
openAnalyzer: true, openAnalyzer: true,
// 如果为true则Webpack Stats JSON文件将在bundle输出目录中生成 // 如果为true则Webpack Stats JSON文件将在bundle输出目录中生成
generateStatsFile: false, generateStatsFile: false,
// 如果`generateStatsFile`为`true`将会生成Webpack Stats JSON文件的名字。 // 如果`generateStatsFile`为`true`将会生成Webpack Stats JSON文件的名字。
// 相对于捆绑输出目录。 // 相对于捆绑输出目录。
statsFilename: 'stats.json', statsFilename: 'stats.json',
// stats.toJson方法的选项。 // stats.toJson方法的选项。
// 例如,您可以使用`sourcefalse`选项排除统计文件中模块的来源。 // 例如,您可以使用`sourcefalse`选项排除统计文件中模块的来源。
// 在这里查看更多选项https //github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21 // 在这里查看更多选项https //github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
statsOptions: null, statsOptions: null,
logLevel: 'info', logLevel: 'info',
}), }),
].filter(Boolean), ].filter(Boolean),
// Turn off performance processing because we utilize // Turn off performance processing because we utilize
// our own hints via the FileSizeReporter // our own hints via the FileSizeReporter
@ -1039,7 +1029,6 @@ module.exports = function (webpackEnv) {
react: 'React', react: 'React',
'react-dom': 'ReactDOM', 'react-dom': 'ReactDOM',
'@wangeditor/editor': 'wangEditor', '@wangeditor/editor': 'wangEditor',
// '@wangeditor/basic-modules': 'WangEditorBasicModules', 这里跑起来初始化会有个BUG先不弄了
'@fingerprintjs/fingerprintjs': 'FingerprintJS', '@fingerprintjs/fingerprintjs': 'FingerprintJS',
'bn.js': 'BN', 'bn.js': 'BN',
}, },

View File

@ -31,14 +31,7 @@ async function build(cmd) {
(0, makeRouter_1.default)({ subdir }, mode === 'development'); (0, makeRouter_1.default)({ subdir }, mode === 'development');
// makeDependency 放到npm install之后做一次 // makeDependency 放到npm install之后做一次
// makeDep(''); // makeDep('');
//ts类型检查 waring 还是error, (0, tip_style_1.Success)(`${(0, tip_style_1.success)(`build ${target} environment:${mode} ${['development'].includes(mode) ? `devMode:${devMode}` : ''}`)}`);
//主要web受影响error级别的话 控制台和网页都报错warning级别的话 控制台报错
// development/staging/production
const errorLevel = cmd.check !== 'error';
(0, tip_style_1.Success)(`${(0, tip_style_1.success)(`build ${target} environment:${mode} ${['development'].includes(mode) ? `devMode:${devMode}` : ''} ${['mp', 'wechatMp'].includes(target) &&
['development'].includes(mode)
? `split:${!!cmd.split}`
: ''}`)}`);
if (['mp', 'wechatMp'].includes(target)) { if (['mp', 'wechatMp'].includes(target)) {
const mpFileMap = { const mpFileMap = {
production: 'build-mp.js', production: 'build-mp.js',
@ -50,11 +43,9 @@ async function build(cmd) {
`NODE_TARGET=${target}`, `NODE_TARGET=${target}`,
`OAK_DEV_MODE=${devMode}`, `OAK_DEV_MODE=${devMode}`,
`SUB_DIR_NAME=${subdir}`, `SUB_DIR_NAME=${subdir}`,
`TSC_COMPILE_ON_ERROR=${errorLevel}`,
`COMPILE_ANALYZE=${!!cmd.analyze}`, `COMPILE_ANALYZE=${!!cmd.analyze}`,
`GENERATE_SOURCEMAP=${!!cmd.sourcemap}`, `GENERATE_SOURCEMAP=${!!cmd.sourcemap}`,
`PROD=${!!cmd.prod}`, `PROD=${!!cmd.prod}`,
`SPLIT=${!!cmd.split}`,
!!cmd.memoryLimit && `MEMORY_LIMIT=${cmd.memoryLimit}`, !!cmd.memoryLimit && `MEMORY_LIMIT=${cmd.memoryLimit}`,
`node`, `node`,
cmd.memoryLimit && `--max_old_space_size=${cmd.memoryLimit}`, cmd.memoryLimit && `--max_old_space_size=${cmd.memoryLimit}`,
@ -82,7 +73,6 @@ async function build(cmd) {
`NODE_TARGET=${target}`, `NODE_TARGET=${target}`,
`OAK_DEV_MODE=${devMode}`, `OAK_DEV_MODE=${devMode}`,
`SUB_DIR_NAME=${subdir}`, `SUB_DIR_NAME=${subdir}`,
`TSC_COMPILE_ON_ERROR=${errorLevel}`,
`COMPILE_ANALYZE=${!!cmd.analyze}`, `COMPILE_ANALYZE=${!!cmd.analyze}`,
`GENERATE_SOURCEMAP=${!!cmd.sourcemap}`, `GENERATE_SOURCEMAP=${!!cmd.sourcemap}`,
`PROD=${!!cmd.prod}`, `PROD=${!!cmd.prod}`,

View File

@ -231,7 +231,7 @@ async function create(dirName, cmd) {
} }
// 获取package.json内容 // 获取package.json内容
const packageJson = (0, template_1.packageJsonContent)({ const packageJson = (0, template_1.packageJsonContent)({
name: DEFAULT_PROJECT_NAME, name: DEFAULT_PROJECT_NAME, // 后面再统一rename
version, version,
description, description,
cliName: config_1.CLI_NAME, cliName: config_1.CLI_NAME,

View File

@ -62,12 +62,10 @@ commander_1.default
.option('--sourceMap', 'sourceMap') .option('--sourceMap', 'sourceMap')
.option('--analyze', 'analyze') .option('--analyze', 'analyze')
.option('--prod', 'prod') .option('--prod', 'prod')
.option('--split', 'split')
.option('--memoryLimit <memoryLimit>', 'memoryLimit of node') .option('--memoryLimit <memoryLimit>', 'memoryLimit of node')
.option('-t, --target <target>', 'target') .option('-t, --target <target>', 'target')
.option('-m, --mode <mode>', 'mode') .option('-m, --mode <mode>', 'mode')
.option('-d, --subDir <subDirName>', 'subDirName') .option('-d, --subDir <subDirName>', 'subDirName')
.option('-c, --check <level>', 'level')
.option('-p, --port <port>', 'port') .option('-p, --port <port>', 'port')
.option('-dm, --devMode <devMode>', 'devMode') .option('-dm, --devMode <devMode>', 'devMode')
.description('build project of start on demand') .description('build project of start on demand')
@ -80,7 +78,6 @@ commander_1.default
.option('-t, --target <target>', 'target') .option('-t, --target <target>', 'target')
.option('-m, --mode <mode>', 'mode') .option('-m, --mode <mode>', 'mode')
.option('-d, --subDir <subDirName>', 'subDirName') .option('-d, --subDir <subDirName>', 'subDirName')
.option('-c, --check <level>', 'level')
.option('-p, --platform <platform>', 'platform') .option('-p, --platform <platform>', 'platform')
.description('build project of build on demand') .description('build project of build on demand')
.action(build_1.default); .action(build_1.default);

View File

@ -16,6 +16,7 @@ const sticky_1 = require("@socket.io/sticky");
const socket_io_1 = require("socket.io"); const socket_io_1 = require("socket.io");
const DATA_SUBSCRIBER_NAMESPACE = '/ds'; const DATA_SUBSCRIBER_NAMESPACE = '/ds';
const SERVER_SUBSCRIBER_NAMESPACE = process.env.OAK_SSUB_NAMESPACE || '/ssub'; const SERVER_SUBSCRIBER_NAMESPACE = process.env.OAK_SSUB_NAMESPACE || '/ssub';
const ExceptionMask = '内部不可知错误';
function concat(...paths) { function concat(...paths) {
return paths.reduce((prev, current) => { return paths.reduce((prev, current) => {
if (current.startsWith('/')) { if (current.startsWith('/')) {
@ -72,7 +73,7 @@ async function startup(path, connector, omitWatchers, omitTimers, routine) {
catch (err) { catch (err) {
console.error(err); console.error(err);
const { request } = ctx; const { request } = ctx;
const exception = err instanceof types_1.OakException ? err : new types_1.OakException('内部不可知错误'); const exception = err instanceof types_1.OakException ? err : new types_1.OakException(serverConfiguration?.internalExceptionMask || ExceptionMask);
const { body } = connector.serializeException(exception, request.headers, request.body); const { body } = connector.serializeException(exception, request.headers, request.body);
ctx.response.body = body; ctx.response.body = body;
return; return;

View File

@ -260,6 +260,11 @@ function packageJsonContent({ name, version, description, cliName, cliBinName, i
"last 1 chrome version", "last 1 chrome version",
"last 1 firefox version", "last 1 firefox version",
"last 1 safari version" "last 1 safari version"
],
"staging": [
">0.2%",
"not dead",
"not op_mini all"
] ]
}, },
"copyWebpack": [] "copyWebpack": []

View File

@ -7,7 +7,7 @@ const webpack = require('webpack');
const chalk = require('chalk'); const chalk = require('chalk');
const fs = require('fs-extra'); const fs = require('fs-extra');
const configFactory = require('../config/mp/webpack.config'); const configFactory = require('../config/mp/webpack.config');
const config = configFactory('production'); const config = configFactory('staging');
const paths = require('../config/mp/paths'); const paths = require('../config/mp/paths');
const getClientEnvironment = require('../config/mp/env'); const getClientEnvironment = require('../config/mp/env');

View File

@ -47,7 +47,7 @@ const argv = process.argv.slice(2);
const writeStatsJson = argv.indexOf('--stats') !== -1; const writeStatsJson = argv.indexOf('--stats') !== -1;
// Generate configuration // Generate configuration
const config = configFactory('production'); const config = configFactory('staging');
// We require that you explicitly set browsers and do not fall back to // We require that you explicitly set browsers and do not fall back to
// browserslist defaults. // browserslist defaults.

View File

@ -46,19 +46,11 @@ export default async function build(cmd: any) {
makeRouter({ subdir }, mode === 'development'); makeRouter({ subdir }, mode === 'development');
// makeDependency 放到npm install之后做一次 // makeDependency 放到npm install之后做一次
// makeDep(''); // makeDep('');
//ts类型检查 waring 还是error,
//主要web受影响error级别的话 控制台和网页都报错warning级别的话 控制台报错
// development/staging/production
const errorLevel = cmd.check !== 'error';
Success( Success(
`${success( `${success(
`build ${target} environment:${mode} ${ `build ${target} environment:${mode} ${
['development'].includes(mode) ? `devMode:${devMode}` : '' ['development'].includes(mode) ? `devMode:${devMode}` : ''
} ${
['mp', 'wechatMp'].includes(target) &&
['development'].includes(mode)
? `split:${!!cmd.split}`
: ''
}` }`
)}` )}`
); );
@ -75,11 +67,9 @@ export default async function build(cmd: any) {
`NODE_TARGET=${target}`, `NODE_TARGET=${target}`,
`OAK_DEV_MODE=${devMode}`, `OAK_DEV_MODE=${devMode}`,
`SUB_DIR_NAME=${subdir}`, `SUB_DIR_NAME=${subdir}`,
`TSC_COMPILE_ON_ERROR=${errorLevel}`,
`COMPILE_ANALYZE=${!!cmd.analyze}`, `COMPILE_ANALYZE=${!!cmd.analyze}`,
`GENERATE_SOURCEMAP=${!!cmd.sourcemap}`, `GENERATE_SOURCEMAP=${!!cmd.sourcemap}`,
`PROD=${!!cmd.prod}`, `PROD=${!!cmd.prod}`,
`SPLIT=${!!cmd.split}`,
!!cmd.memoryLimit && `MEMORY_LIMIT=${cmd.memoryLimit}`, !!cmd.memoryLimit && `MEMORY_LIMIT=${cmd.memoryLimit}`,
`node`, `node`,
cmd.memoryLimit && `--max_old_space_size=${cmd.memoryLimit}`, cmd.memoryLimit && `--max_old_space_size=${cmd.memoryLimit}`,
@ -109,7 +99,6 @@ export default async function build(cmd: any) {
`NODE_TARGET=${target}`, `NODE_TARGET=${target}`,
`OAK_DEV_MODE=${devMode}`, `OAK_DEV_MODE=${devMode}`,
`SUB_DIR_NAME=${subdir}`, `SUB_DIR_NAME=${subdir}`,
`TSC_COMPILE_ON_ERROR=${errorLevel}`,
`COMPILE_ANALYZE=${!!cmd.analyze}`, `COMPILE_ANALYZE=${!!cmd.analyze}`,
`GENERATE_SOURCEMAP=${!!cmd.sourcemap}`, `GENERATE_SOURCEMAP=${!!cmd.sourcemap}`,
`PROD=${!!cmd.prod}`, `PROD=${!!cmd.prod}`,

View File

@ -71,12 +71,10 @@ program
.option('--sourceMap', 'sourceMap') .option('--sourceMap', 'sourceMap')
.option('--analyze', 'analyze') .option('--analyze', 'analyze')
.option('--prod', 'prod') .option('--prod', 'prod')
.option('--split', 'split')
.option('--memoryLimit <memoryLimit>', 'memoryLimit of node') .option('--memoryLimit <memoryLimit>', 'memoryLimit of node')
.option('-t, --target <target>', 'target') .option('-t, --target <target>', 'target')
.option('-m, --mode <mode>', 'mode') .option('-m, --mode <mode>', 'mode')
.option('-d, --subDir <subDirName>', 'subDirName') .option('-d, --subDir <subDirName>', 'subDirName')
.option('-c, --check <level>', 'level')
.option('-p, --port <port>', 'port') .option('-p, --port <port>', 'port')
.option('-dm, --devMode <devMode>', 'devMode') .option('-dm, --devMode <devMode>', 'devMode')
.description('build project of start on demand') .description('build project of start on demand')
@ -89,7 +87,6 @@ program
.option('-t, --target <target>', 'target') .option('-t, --target <target>', 'target')
.option('-m, --mode <mode>', 'mode') .option('-m, --mode <mode>', 'mode')
.option('-d, --subDir <subDirName>', 'subDirName') .option('-d, --subDir <subDirName>', 'subDirName')
.option('-c, --check <level>', 'level')
.option('-p, --platform <platform>', 'platform') .option('-p, --platform <platform>', 'platform')
.description('build project of build on demand') .description('build project of build on demand')
.action(build); .action(build);

View File

@ -13,10 +13,11 @@ import { SyncContext } from 'oak-domain/lib/store/SyncRowStore';
import { createAdapter } from "@socket.io/cluster-adapter"; import { createAdapter } from "@socket.io/cluster-adapter";
import { setupWorker } from "@socket.io/sticky"; import { setupWorker } from "@socket.io/sticky";
import { Server, ServerOptions } from "socket.io"; import { Server, ServerOptions } from "socket.io";
import { AccessConfiguration, ServerConfiguration } from 'oak-domain/lib/types/Configuration'; import { ServerConfiguration } from 'oak-domain/lib/types/Configuration';
const DATA_SUBSCRIBER_NAMESPACE = '/ds'; const DATA_SUBSCRIBER_NAMESPACE = '/ds';
const SERVER_SUBSCRIBER_NAMESPACE = process.env.OAK_SSUB_NAMESPACE || '/ssub'; const SERVER_SUBSCRIBER_NAMESPACE = process.env.OAK_SSUB_NAMESPACE || '/ssub';
const ExceptionMask = '内部不可知错误';
function concat(...paths: string[]) { function concat(...paths: string[]) {
return paths.reduce( return paths.reduce(
@ -88,7 +89,7 @@ export async function startup<ED extends EntityDict & BaseEntityDict, FrontCxt e
catch (err) { catch (err) {
console.error(err); console.error(err);
const { request } = ctx; const { request } = ctx;
const exception = err instanceof OakException ? err : new OakException('内部不可知错误'); const exception = err instanceof OakException ? err : new OakException(serverConfiguration?.internalExceptionMask || ExceptionMask);
const { body } = connector.serializeException(exception, request.headers, request.body); const { body } = connector.serializeException(exception, request.headers, request.body);
ctx.response.body = body; ctx.response.body = body;
return; return;

View File

@ -278,6 +278,11 @@ export function packageJsonContent({
"last 1 chrome version", "last 1 chrome version",
"last 1 firefox version", "last 1 firefox version",
"last 1 safari version" "last 1 safari version"
],
"staging": [
">0.2%",
"not dead",
"not op_mini all"
] ]
}, },
"copyWebpack": [] "copyWebpack": []

View File

@ -119,7 +119,7 @@
var tip = document.createElement('div'); var tip = document.createElement('div');
var closeBtn = document.createElement('img'); var closeBtn = document.createElement('img');
var contentHTML = var contentHTML =
'您当前使用的浏览器可能会出现界面显示异常或功能无法正常使用等问题,建议下载使用最新的 360 极速浏览器并切换到极速模式。'; '您当前使用的浏览器可能会出现界面显示异常或功能无法正常使用等问题,建议下载使用谷歌火狐edge等新版本浏览器。';
var handleClickClose = function (event) { var handleClickClose = function (event) {
document.body.removeChild(tip); document.body.removeChild(tip);
}; };