@umijs/preset-umi 4.0.4 → 4.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -235,12 +235,16 @@ PORT=8888 umi dev
235
235
  extraBabelPresets,
236
236
  beforeMiddlewares: [].concat([
237
237
  ...beforeMiddlewares,
238
- faviconMiddleware_1.faviconMiddleware,
239
238
  ]),
240
239
  // vite 模式使用 ./plugins/ViteHtmlPlugin.ts 处理
241
240
  afterMiddlewares: enableVite
242
241
  ? []
243
- : middlewares.concat((0, createRouteMiddleware_1.createRouteMiddleware)({ api })),
242
+ : middlewares.concat([
243
+ (0, createRouteMiddleware_1.createRouteMiddleware)({ api }),
244
+ // 放置 favicon 在 webpack middleware 之后,兼容 public 目录下有 favicon.ico 的场景
245
+ // ref: https://github.com/umijs/umi/issues/8024
246
+ faviconMiddleware_1.faviconMiddleware,
247
+ ]),
244
248
  onDevCompileDone(opts) {
245
249
  debouncedPrintMemoryUsage;
246
250
  // debouncedPrintMemoryUsage();
@@ -17,11 +17,14 @@ umi lint --stylelint-only
17
17
 
18
18
  # automatically fix, where possible
19
19
  umi lint --fix
20
+
21
+ # disable reporting on warnings
22
+ umi lint --quiet
20
23
  `,
21
24
  fn: async function () {
22
25
  // re-parse cli args to process boolean flags, for get the lint-staged args
23
26
  const args = (0, utils_1.yParser)(process.argv.slice(3), {
24
- boolean: ['fix', 'eslint-only', 'stylelint-only'],
27
+ boolean: ['quiet', 'fix', 'eslint-only', 'stylelint-only'],
25
28
  });
26
29
  try {
27
30
  require.resolve('@umijs/lint/package.json');
@@ -78,6 +78,17 @@ umi preview --port [port]
78
78
  }));
79
79
  // history fallback
80
80
  app.use(require('@umijs/bundler-webpack/compiled/connect-history-api-fallback')());
81
+ // 如果是 browser,并且配置了非 / base,访问 / 时 /index.html redirect 到 base 路径
82
+ app.use((_req, res, next) => {
83
+ var _a;
84
+ const historyType = ((_a = api.config.history) === null || _a === void 0 ? void 0 : _a.type) || 'browser';
85
+ if (historyType === 'browser' &&
86
+ api.config.base !== '/' &&
87
+ (_req.path === '/' || _req.path === '/index.html')) {
88
+ return res.redirect(api.config.base);
89
+ }
90
+ next();
91
+ });
81
92
  // https 复用用户配置
82
93
  const server = api.userConfig.https
83
94
  ? await (0, bundler_utils_1.createHttpsServer)(app, api.userConfig.https)
@@ -92,7 +103,7 @@ umi preview --port [port]
92
103
  server.listen(port, () => {
93
104
  const host = api.args.host && api.args.host !== '0.0.0.0'
94
105
  ? api.args.host
95
- : '127.0.0.1';
106
+ : 'localhost';
96
107
  utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`${protocol}//${host}:${port}`)}`);
97
108
  });
98
109
  },
@@ -48,7 +48,6 @@ exports.default = (api) => {
48
48
  return false;
49
49
  const config = api.userConfig.apiRoute;
50
50
  if (!config) {
51
- utils_1.logger.warn('Directory ./src/api exists, but config.apiRoute is not set. API route feature will not be enabled!');
52
51
  return false;
53
52
  }
54
53
  if (!config.platform) {
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" />
2
+ /// <reference types="node" />
2
3
  import type { IncomingMessage } from 'http';
3
4
  import type { IRoute } from '../../types';
4
5
  declare class UmiApiRequest {
@@ -22,4 +23,10 @@ declare class UmiApiRequest {
22
23
  get pathName(): string | undefined;
23
24
  readBody(): Promise<void>;
24
25
  }
26
+ export declare function parseMultipart(body: Buffer, boundary: string): {
27
+ [key: string]: any;
28
+ };
29
+ export declare function parseUrlEncoded(body: string): {
30
+ [key: string]: any;
31
+ };
25
32
  export default UmiApiRequest;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseUrlEncoded = exports.parseMultipart = void 0;
3
4
  const utils_1 = require("./utils");
4
5
  class UmiApiRequest {
5
6
  constructor(req, apiRoutes) {
@@ -61,21 +62,33 @@ class UmiApiRequest {
61
62
  return Promise.resolve();
62
63
  }
63
64
  return new Promise((resolve, reject) => {
64
- let body = '';
65
+ let body = [];
65
66
  this._req.on('data', (chunk) => {
66
- body += chunk;
67
+ body.push(chunk);
67
68
  });
68
69
  this._req.on('end', () => {
69
- // TODO: handle other content types
70
- switch (this._req.headers['content-type']) {
70
+ var _a, _b;
71
+ const bodyBuffer = Buffer.concat(body);
72
+ switch ((_a = this._req.headers['content-type']) === null || _a === void 0 ? void 0 : _a.split(';')[0]) {
71
73
  case 'application/json':
72
74
  try {
73
- this._body = JSON.parse(body);
75
+ this._body = JSON.parse(bodyBuffer.toString());
74
76
  }
75
77
  catch (e) {
76
78
  this._body = body;
77
79
  }
78
80
  break;
81
+ case 'multipart/form-data':
82
+ const boundary = (_b = this.headers['content-type']) === null || _b === void 0 ? void 0 : _b.split('boundary=')[1];
83
+ if (!boundary) {
84
+ this._body = body;
85
+ break;
86
+ }
87
+ this._body = parseMultipart(bodyBuffer, boundary);
88
+ break;
89
+ case 'application/x-www-form-urlencoded':
90
+ this._body = parseUrlEncoded(bodyBuffer.toString());
91
+ break;
79
92
  default:
80
93
  this._body = body;
81
94
  break;
@@ -86,4 +99,46 @@ class UmiApiRequest {
86
99
  });
87
100
  }
88
101
  }
102
+ function parseMultipart(body, boundary) {
103
+ const hexBoundary = Buffer.from(`--${boundary}`, 'utf-8').toString('hex');
104
+ return body
105
+ .toString('hex')
106
+ .split(hexBoundary)
107
+ .reduce((acc, cur) => {
108
+ var _a, _b;
109
+ const [hexMeta, hexValue] = cur.split(Buffer.from('\r\n\r\n').toString('hex'));
110
+ const meta = Buffer.from(hexMeta, 'hex').toString('utf-8');
111
+ const name = (_a = meta.split('name="')[1]) === null || _a === void 0 ? void 0 : _a.split('"')[0];
112
+ // if this part doesn't have name, skip it
113
+ if (!name)
114
+ return acc;
115
+ // if there is filename, this field is file, save as buffer
116
+ const fileName = (_b = meta.split('filename="')[1]) === null || _b === void 0 ? void 0 : _b.split('"')[0];
117
+ if (fileName) {
118
+ const fileBufferBeforeTrim = Buffer.from(hexValue, 'hex');
119
+ const fileBuffer = fileBufferBeforeTrim.slice(0, fileBufferBeforeTrim.byteLength - 2);
120
+ const contentType = meta.split('Content-Type: ')[1];
121
+ acc[name] = {
122
+ fileName,
123
+ data: fileBuffer,
124
+ contentType,
125
+ };
126
+ return acc;
127
+ }
128
+ // if there is no filename, this field is string, save as string
129
+ const valueBufferBeforeTrim = Buffer.from(hexValue, 'hex');
130
+ const valueBuffer = valueBufferBeforeTrim.slice(0, valueBufferBeforeTrim.byteLength - 2);
131
+ acc[name] = valueBuffer.toString('utf-8');
132
+ return acc;
133
+ }, {});
134
+ }
135
+ exports.parseMultipart = parseMultipart;
136
+ function parseUrlEncoded(body) {
137
+ return body.split('&').reduce((acc, cur) => {
138
+ const [key, value] = cur.split('=');
139
+ acc[key] = decodeURI(value);
140
+ return acc;
141
+ }, {});
142
+ }
143
+ exports.parseUrlEncoded = parseUrlEncoded;
89
144
  exports.default = UmiApiRequest;
@@ -6,6 +6,7 @@ declare class UmiApiResponse {
6
6
  status(statusCode: number): this;
7
7
  header(key: string, value: string): this;
8
8
  setCookie(key: string, value: string): this;
9
+ end(data: any): this;
9
10
  text(data: string): this;
10
11
  html(data: string): this;
11
12
  json(data: any): this;
@@ -16,6 +16,10 @@ class UmiApiResponse {
16
16
  this._res.setHeader('Set-Cookie', `${key}=${value}; path=/`);
17
17
  return this;
18
18
  }
19
+ end(data) {
20
+ this._res.end(data);
21
+ return this;
22
+ }
19
23
  text(data) {
20
24
  this._res.setHeader('Content-Type', 'text/plain; charset=utf-8');
21
25
  this._res.end(data);
@@ -0,0 +1,3 @@
1
+ import { IApi } from '../../types';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const utils_1 = require("@umijs/utils");
4
+ const path_1 = require("path");
5
+ exports.default = (api) => {
6
+ api.describe({
7
+ key: 'clickToComponent',
8
+ config: {
9
+ schema(joi) {
10
+ return joi.object({
11
+ editor: joi.string(),
12
+ });
13
+ },
14
+ },
15
+ enableBy: api.EnableBy.config,
16
+ });
17
+ const pkgPath = (0, path_1.dirname)(require.resolve('click-to-react-component'));
18
+ api.modifyConfig((memo) => {
19
+ memo.alias['click-to-react-component'] = pkgPath;
20
+ return memo;
21
+ });
22
+ api.modifyAppData((memo) => {
23
+ memo.clickToComponent = {
24
+ pkgPath,
25
+ version: '1.0.8',
26
+ };
27
+ return memo;
28
+ });
29
+ api.onGenerateFiles({
30
+ name: 'clickToComponent',
31
+ fn: () => {
32
+ api.writeTmpFile({
33
+ path: 'runtime.tsx',
34
+ content: `
35
+ import { ClickToComponent } from 'click-to-react-component';
36
+ import React from 'react';
37
+ export function rootContainer(container, opts) {
38
+ return React.createElement(
39
+ (props) => {
40
+ return (
41
+ <>
42
+ <ClickToComponent editor="${api.config.clickToComponent.editor || 'vscode'}"/>
43
+ {props.children}
44
+ </>
45
+ );
46
+ },
47
+ opts,
48
+ container,
49
+ );
50
+ }
51
+ `,
52
+ });
53
+ },
54
+ });
55
+ api.addRuntimePlugin(() => [
56
+ (0, utils_1.winPath)((0, path_1.join)(api.paths.absTmpPath, 'plugin-clickToComponent/runtime.tsx')),
57
+ ]);
58
+ };
@@ -29,6 +29,7 @@ function getMockData(opts) {
29
29
  const mockFile = `${opts.cwd}/${file}`;
30
30
  let m;
31
31
  try {
32
+ delete require.cache[mockFile];
32
33
  m = require(mockFile);
33
34
  }
34
35
  catch (e) {
@@ -52,9 +53,6 @@ function getMockData(opts) {
52
53
  }
53
54
  return memo;
54
55
  }, {});
55
- for (const file of utils_1.register.getFiles()) {
56
- delete require.cache[file];
57
- }
58
56
  utils_1.register.restore();
59
57
  return ret;
60
58
  }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.cssLoader = exports.getClassNames = exports.hashString = exports.ensureLastSlash = void 0;
4
- const bundler_webpack_1 = require("@umijs/bundler-webpack");
4
+ const parcelCSS_1 = require("@umijs/bundler-webpack/dist/parcelCSS");
5
5
  const utils_1 = require("@umijs/utils");
6
6
  const fs_1 = require("fs");
7
7
  const path_1 = require("path");
@@ -18,7 +18,7 @@ exports.hashString = hashString;
18
18
  function getClassNames(code, filename) {
19
19
  // why use Parcel CSS?
20
20
  // ref: https://github.com/indooorsman/esbuild-css-modules-plugin
21
- const { exports } = bundler_webpack_1.parcelCSS.transform({
21
+ const { exports } = parcelCSS_1.parcelCSS.transform({
22
22
  filename,
23
23
  code,
24
24
  minify: false,
@@ -10,3 +10,12 @@ export declare function getRouteComponents(opts: {
10
10
  prefix: string;
11
11
  api: IApi;
12
12
  }): Promise<string>;
13
+ /**
14
+ *
15
+ * transform component into webpack chunkName
16
+ * @export
17
+ * @param {string} component component path
18
+ * @param {string} [cwd] current root path
19
+ * @return {*} {string}
20
+ */
21
+ export declare function componentToChunkName(component: string, cwd?: string): string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRouteComponents = exports.getRoutes = exports.getApiRoutes = void 0;
3
+ exports.componentToChunkName = exports.getRouteComponents = exports.getRoutes = exports.getApiRoutes = void 0;
4
4
  const core_1 = require("@umijs/core");
5
5
  const utils_1 = require("@umijs/utils");
6
6
  const fs_1 = require("fs");
@@ -190,11 +190,43 @@ async function getRouteComponents(opts) {
190
190
  const path = (0, path_1.isAbsolute)(route.file) || route.file.startsWith('@/')
191
191
  ? route.file
192
192
  : `${opts.prefix}${route.file}`;
193
+ const webpackChunkName = componentToChunkName(path, opts.api.cwd);
193
194
  return useSuspense
194
- ? `'${key}': React.lazy(() => import(/* webpackChunkName: "${key.replace(/[\/-]/g, '_')}" */'${(0, utils_1.winPath)(path)}')),`
195
- : `'${key}': () => import(/* webpackChunkName: "${key.replace(/[\/-]/g, '_')}" */'${(0, utils_1.winPath)(path)}'),`;
195
+ ? `'${key}': React.lazy(() => import(/* webpackChunkName: "${webpackChunkName}" */'${(0, utils_1.winPath)(path)}')),`
196
+ : `'${key}': () => import(/* webpackChunkName: "${webpackChunkName}" */'${(0, utils_1.winPath)(path)}'),`;
196
197
  })
197
198
  .join('\n');
198
199
  return `{\n${imports}\n}`;
199
200
  }
200
201
  exports.getRouteComponents = getRouteComponents;
202
+ function lastSlash(str) {
203
+ return str[str.length - 1] === '/' ? str : `${str}/`;
204
+ }
205
+ /**
206
+ *
207
+ * transform component into webpack chunkName
208
+ * @export
209
+ * @param {string} component component path
210
+ * @param {string} [cwd] current root path
211
+ * @return {*} {string}
212
+ */
213
+ function componentToChunkName(component, cwd) {
214
+ return typeof component === 'string'
215
+ ? component
216
+ .replace(new RegExp(`^${utils_1.lodash.escapeRegExp(lastSlash((0, utils_1.winPath)(cwd || '/')))}`), '')
217
+ .replace(/^.(\/|\\)/, '')
218
+ .replace(/(\/|\\)/g, '__')
219
+ .replace(/\.jsx?$/, '')
220
+ .replace(/\.tsx?$/, '')
221
+ .replace(/\.vue?$/, '')
222
+ .replace(/^src__/, '')
223
+ .replace(/\.\.__/g, '')
224
+ // 约定式路由的 [ 会导致 webpack 的 code splitting 失败
225
+ // ref: https://github.com/umijs/umi/issues/4155
226
+ .replace(/[\[\]]/g, '')
227
+ // 插件层的文件也可能是路由组件,比如 plugin-layout 插件
228
+ .replace(/^.umi-production__/, 't__')
229
+ .replace(/^pages__/, 'p__')
230
+ : '';
231
+ }
232
+ exports.componentToChunkName = componentToChunkName;
@@ -128,6 +128,14 @@ declare module '*.gif' {
128
128
  export default src
129
129
  }
130
130
  declare module '*.svg' {
131
+ ${api.config.svgr
132
+ ? `
133
+ import * as React from 'react';
134
+ export const ReactComponent: React.FunctionComponent<React.SVGProps<
135
+ SVGSVGElement
136
+ > & { title?: string }>;
137
+ `.trimStart()
138
+ : ''}
131
139
  const src: string
132
140
  export default src
133
141
  }
package/dist/index.js CHANGED
@@ -28,6 +28,7 @@ exports.default = () => {
28
28
  require.resolve('./features/vite/vite'),
29
29
  require.resolve('./features/apiRoute/apiRoute'),
30
30
  require.resolve('./features/monorepo/redirect'),
31
+ require.resolve('./features/clickToComponent/clickToComponent'),
31
32
  // commands
32
33
  require.resolve('./commands/build'),
33
34
  require.resolve('./commands/config/config'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/preset-umi",
3
- "version": "4.0.4",
3
+ "version": "4.0.7",
4
4
  "description": "@umijs/preset-umi",
5
5
  "homepage": "https://github.com/umijs/umi/tree/master/packages/preset-umi#readme",
6
6
  "bugs": "https://github.com/umijs/umi/issues",
@@ -26,15 +26,16 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@types/multer": "1.4.7",
29
- "@umijs/ast": "4.0.4",
30
- "@umijs/babel-preset-umi": "4.0.4",
31
- "@umijs/bundler-utils": "4.0.4",
32
- "@umijs/bundler-vite": "4.0.4",
33
- "@umijs/bundler-webpack": "4.0.4",
34
- "@umijs/core": "4.0.4",
35
- "@umijs/renderer-react": "4.0.4",
36
- "@umijs/server": "4.0.4",
37
- "@umijs/utils": "4.0.4",
29
+ "@umijs/ast": "4.0.7",
30
+ "@umijs/babel-preset-umi": "4.0.7",
31
+ "@umijs/bundler-utils": "4.0.7",
32
+ "@umijs/bundler-vite": "4.0.7",
33
+ "@umijs/bundler-webpack": "4.0.7",
34
+ "@umijs/core": "4.0.7",
35
+ "@umijs/renderer-react": "4.0.7",
36
+ "@umijs/server": "4.0.7",
37
+ "@umijs/utils": "4.0.7",
38
+ "click-to-react-component": "^1.0.8",
38
39
  "core-js": "3.22.4",
39
40
  "current-script-polyfill": "1.0.0",
40
41
  "enhanced-resolve": "5.9.3",
@@ -7,7 +7,7 @@ export function createHistory(opts: any) {
7
7
  if (opts.type === 'hash') {
8
8
  h = createHashHistory();
9
9
  } else if (opts.type === 'memory') {
10
- h = createMemoryHistory();
10
+ h = createMemoryHistory(opts);
11
11
  } else {
12
12
  h = createBrowserHistory();
13
13
  }
package/templates/umi.tpl CHANGED
@@ -51,8 +51,9 @@ async function render() {
51
51
  publicPath,
52
52
  runtimePublicPath,
53
53
  history: createHistory({
54
- type: '{{{ historyType }}}',
54
+ type: contextOpts.historyType || '{{{ historyType }}}',
55
55
  basename,
56
+ ...contextOpts.historyOpts,
56
57
  }),
57
58
  basename,
58
59
  };