@umijs/bundler-esbuild 4.0.0-beta.9 → 4.0.0-rc.3

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.
package/dist/build.d.ts CHANGED
@@ -15,5 +15,7 @@ interface IOpts {
15
15
  extraBabelPresets?: IBabelPlugin[];
16
16
  inlineStyle?: boolean;
17
17
  }
18
- export declare function build(opts: IOpts): Promise<import("@umijs/bundler-utils/compiled/esbuild").BuildResult>;
18
+ export declare function build(opts: IOpts): Promise<import("@umijs/bundler-utils/compiled/esbuild").BuildResult & {
19
+ metafile: import("@umijs/bundler-utils/compiled/esbuild").Metafile;
20
+ }>;
19
21
  export {};
package/dist/build.js CHANGED
@@ -36,15 +36,22 @@ function build(opts) {
36
36
  outdir: outputPath,
37
37
  metafile: true,
38
38
  plugins: [
39
- (0, less_1.default)(Object.assign({ modifyVars: opts.config.theme, javascriptEnabled: true }, opts.config.lessLoader)),
39
+ (0, less_1.default)(Object.assign({ modifyVars: opts.config.theme, javascriptEnabled: true, alias: opts.config.alias,
40
+ // ref: https://github.com/umijs/umi-next/pull/214
41
+ inlineStyle: opts.inlineStyle, config: opts.config }, opts.config.lessLoader)),
40
42
  opts.config.alias && (0, alias_1.default)(addCwdPrefix(opts.config.alias, opts.cwd)),
41
43
  opts.config.externals && (0, externals_1.default)(opts.config.externals),
42
- opts.inlineStyle && (0, style_1.inlineStyle)(),
44
+ (0, style_1.style)({
45
+ inlineStyle: opts.inlineStyle,
46
+ config: opts.config,
47
+ }),
43
48
  ].filter(Boolean),
44
- define: {
49
+ define: Object.assign({
45
50
  // __dirname sham
46
- __dirname: JSON.stringify('__dirname'),
47
- 'process.env.NODE_ENV': JSON.stringify(opts.mode || 'development'),
51
+ __dirname: JSON.stringify('__dirname'), 'process.env.NODE_ENV': JSON.stringify(opts.mode || 'development') }, opts.config.define),
52
+ loader: {
53
+ '.svg': 'dataurl',
54
+ '.ttf': 'dataurl',
48
55
  },
49
56
  });
50
57
  });
package/dist/cli.js CHANGED
@@ -21,7 +21,7 @@ const build_1 = require("./build");
21
21
  const args = (0, utils_1.yParser)(process.argv.slice(2), {});
22
22
  const command = args._[0];
23
23
  const cwd = process.cwd();
24
- const entry = tryPaths([
24
+ const entry = (0, utils_1.tryPaths)([
25
25
  (0, path_1.join)(cwd, 'src/index.tsx'),
26
26
  (0, path_1.join)(cwd, 'src/index.ts'),
27
27
  (0, path_1.join)(cwd, 'index.tsx'),
@@ -61,12 +61,6 @@ else {
61
61
  function error(msg) {
62
62
  console.error(utils_1.chalk.red(msg));
63
63
  }
64
- function tryPaths(paths) {
65
- for (const path of paths) {
66
- if ((0, fs_1.existsSync)(path))
67
- return path;
68
- }
69
- }
70
64
  function getEntryKey(path) {
71
65
  return (0, path_1.basename)(path, (0, path_1.extname)(path));
72
66
  }
@@ -1,4 +1,10 @@
1
1
  /// <reference types="less" />
2
2
  import { Plugin } from '@umijs/bundler-utils/compiled/esbuild';
3
- declare const _default: (options?: Less.Options) => Plugin;
3
+ import { IConfig } from '../types';
4
+ export declare const aliasLessImportPath: (filePath: string, alias: Record<string, string>, importer: string) => Promise<string | null>;
5
+ declare const _default: (options?: Less.Options & {
6
+ alias?: Record<string, string>;
7
+ inlineStyle?: boolean;
8
+ config?: IConfig;
9
+ }) => Plugin;
4
10
  export default _default;
@@ -8,26 +8,152 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
11
22
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
23
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
24
  };
14
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.aliasLessImportPath = void 0;
27
+ const enhanced_resolve_1 = __importDefault(require("enhanced-resolve"));
15
28
  const fs_1 = require("fs");
16
29
  const less_1 = __importDefault(require("less"));
30
+ const less_plugin_aliases_1 = __importDefault(require("less-plugin-aliases"));
17
31
  const path_1 = __importDefault(require("path"));
32
+ const postcssProcess_1 = require("../utils/postcssProcess");
33
+ const sortByAffix_1 = require("../utils/sortByAffix");
34
+ const resolver = enhanced_resolve_1.default.create({
35
+ mainFields: ['module', 'browser', 'main'],
36
+ extensions: [
37
+ '.json',
38
+ '.js',
39
+ '.jsx',
40
+ '.ts',
41
+ '.tsx',
42
+ '.cjs',
43
+ '.mjs',
44
+ '.less',
45
+ '.css',
46
+ ],
47
+ // TODO: support exports
48
+ exportsFields: [],
49
+ });
50
+ function resolve(context, path) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ return new Promise((resolve, reject) => {
53
+ resolver(context, path, (err, result) => err ? reject(err) : resolve(result));
54
+ });
55
+ });
56
+ }
57
+ const aliasLessImports = (ctx, alias, importer) => __awaiter(void 0, void 0, void 0, function* () {
58
+ const importRegex = /@import(?:\s+\((.*)\))?\s+['"](.*)['"]/;
59
+ const globalImportRegex = /@import(?:\s+\((.*)\))?\s+['"](.*)['"]/g;
60
+ const match = ctx.match(globalImportRegex) || [];
61
+ for (const el of match) {
62
+ const [imp, _, filePath] = el.match(importRegex) || [];
63
+ let aliaPath = yield (0, exports.aliasLessImportPath)(filePath, alias, importer);
64
+ if (aliaPath) {
65
+ ctx = ctx.replace(imp, el.replace(filePath, aliaPath));
66
+ }
67
+ }
68
+ return ctx;
69
+ });
70
+ const aliasLessImportPath = (filePath, alias, importer) => __awaiter(void 0, void 0, void 0, function* () {
71
+ // ~ 写法在 esbuild 中无实际意义
72
+ let aliaPath = filePath.startsWith('~')
73
+ ? filePath.replace('~', '')
74
+ : filePath;
75
+ const keys = (0, sortByAffix_1.sortByAffix)({ arr: Object.keys(alias), affix: '$' });
76
+ for (const key of keys) {
77
+ const pathSegments = aliaPath.split('/');
78
+ if (pathSegments[0] === key) {
79
+ pathSegments[0] = alias[key];
80
+ aliaPath = pathSegments.join('/');
81
+ aliaPath = path_1.default.extname(aliaPath) ? aliaPath : `${aliaPath}.less`;
82
+ return yield resolve(importer, aliaPath);
83
+ }
84
+ }
85
+ return null;
86
+ });
87
+ exports.aliasLessImportPath = aliasLessImportPath;
18
88
  exports.default = (options = {}) => {
89
+ const { alias, inlineStyle, config } = options, lessOptions = __rest(options, ["alias", "inlineStyle", "config"]);
19
90
  return {
20
91
  name: 'less',
21
- setup({ onLoad }) {
22
- onLoad({ filter: /\.less$/, namespace: 'file' }, (args) => __awaiter(this, void 0, void 0, function* () {
23
- const content = yield fs_1.promises.readFile(args.path, 'utf-8');
92
+ setup({ onResolve, onLoad }) {
93
+ onResolve({ filter: /\.less$/, namespace: 'file' }, (args) => __awaiter(this, void 0, void 0, function* () {
94
+ let filePath = args.path;
95
+ let isMatchedAlias = false;
96
+ // first match alias
97
+ if (!!alias) {
98
+ const aliasMatchPath = yield (0, exports.aliasLessImportPath)(filePath, alias, args.path);
99
+ if (aliasMatchPath) {
100
+ isMatchedAlias = true;
101
+ filePath = aliasMatchPath;
102
+ }
103
+ }
104
+ // if alias not matched, identify whether import from deps (node_modules)
105
+ if (!isMatchedAlias) {
106
+ const isImportFromDeps = !path_1.default.isAbsolute(filePath) && !filePath.startsWith('.');
107
+ if (isImportFromDeps) {
108
+ filePath = yield resolve(process.cwd(), filePath);
109
+ }
110
+ else {
111
+ filePath = path_1.default.resolve(process.cwd(), path_1.default.relative(process.cwd(), args.resolveDir), args.path);
112
+ }
113
+ }
114
+ return {
115
+ path: filePath,
116
+ namespace: inlineStyle ? 'less-file' : 'file',
117
+ };
118
+ }));
119
+ if (inlineStyle) {
120
+ onResolve({ filter: /\.less$/, namespace: 'less-file' }, (args) => {
121
+ return { path: args.path, namespace: 'less-content' };
122
+ });
123
+ onResolve({ filter: /^__style_helper__$/, namespace: 'less-file' }, (args) => ({
124
+ path: args.path,
125
+ namespace: 'style-helper',
126
+ sideEffects: false,
127
+ }));
128
+ onLoad({ filter: /.*/, namespace: 'less-file' }, (args) => __awaiter(this, void 0, void 0, function* () {
129
+ return ({
130
+ contents: `
131
+ import { injectStyle } from "__style_helper__"
132
+ import css from ${JSON.stringify(args.path)}
133
+ injectStyle(css)
134
+ export default{}
135
+ `,
136
+ });
137
+ }));
138
+ }
139
+ onLoad({ filter: /\.less$/, namespace: inlineStyle ? 'less-content' : 'file' }, (args) => __awaiter(this, void 0, void 0, function* () {
140
+ let content = yield fs_1.promises.readFile(args.path, 'utf-8');
141
+ if (!!alias) {
142
+ content = yield aliasLessImports(content, alias, args.path);
143
+ }
24
144
  const dir = path_1.default.dirname(args.path);
25
145
  const filename = path_1.default.basename(args.path);
26
146
  try {
27
- const result = yield less_1.default.render(content, Object.assign(Object.assign({ filename, rootpath: dir }, options), { paths: [...(options.paths || []), dir] }));
147
+ const result = yield less_1.default.render(content, Object.assign(Object.assign({ plugins: [
148
+ new less_plugin_aliases_1.default({
149
+ prefix: '~',
150
+ aliases: alias || {},
151
+ }),
152
+ ], filename, rootpath: dir }, lessOptions), { paths: [...(lessOptions.paths || []), dir] }));
153
+ const postcssrResult = yield (0, postcssProcess_1.postcssProcess)(config, result.css, args.path);
28
154
  return {
29
- contents: result.css,
30
- loader: 'css',
155
+ contents: postcssrResult.css,
156
+ loader: inlineStyle ? 'text' : 'css',
31
157
  resolveDir: dir,
32
158
  };
33
159
  }
@@ -1,4 +1,5 @@
1
1
  import { Charset, Plugin } from '@umijs/bundler-utils/compiled/esbuild';
2
+ import { IConfig } from '../types';
2
3
  export interface StylePluginOptions {
3
4
  /**
4
5
  * whether to minify the css code.
@@ -10,5 +11,7 @@ export interface StylePluginOptions {
10
11
  * @default 'utf8'
11
12
  */
12
13
  charset?: Charset;
14
+ inlineStyle?: boolean;
15
+ config?: IConfig;
13
16
  }
14
- export declare function inlineStyle({ minify, charset, }?: StylePluginOptions): Plugin;
17
+ export declare function style({ minify, charset, inlineStyle, config, }?: StylePluginOptions): Plugin;
@@ -12,13 +12,15 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.inlineStyle = void 0;
15
+ exports.style = void 0;
16
16
  // ref: https://github.com/hyrious/esbuild-plugin-style/blob/main/index.ts
17
17
  const esbuild_1 = __importDefault(require("@umijs/bundler-utils/compiled/esbuild"));
18
+ const utils_1 = require("@umijs/utils");
18
19
  const fs_1 = __importDefault(require("fs"));
19
20
  const path_1 = __importDefault(require("path"));
21
+ const postcssProcess_1 = require("../utils/postcssProcess");
20
22
  // https://github.com/evanw/esbuild/issues/20#issuecomment-802269745
21
- function inlineStyle({ minify = true, charset = 'utf8', } = {}) {
23
+ function style({ minify = true, charset = 'utf8', inlineStyle, config, } = {}) {
22
24
  return {
23
25
  name: 'style',
24
26
  setup({ onResolve, onLoad }) {
@@ -29,55 +31,97 @@ function inlineStyle({ minify = true, charset = 'utf8', } = {}) {
29
31
  write: false,
30
32
  charset,
31
33
  minify,
34
+ loader: {
35
+ '.svg': 'dataurl',
36
+ // file ?
37
+ '.ttf': 'dataurl',
38
+ },
32
39
  };
33
40
  onResolve({ filter: /\.css$/, namespace: 'file' }, (args) => {
34
- const absPath = path_1.default.join(args.resolveDir, args.path);
35
- const relPath = path_1.default.relative(cwd, absPath);
36
- const resolved = fs_1.default.existsSync(absPath) ? relPath : args.path;
37
- return { path: resolved, namespace: 'style-stub' };
41
+ const absPath = path_1.default.resolve(cwd, path_1.default.relative(cwd, args.resolveDir), args.path);
42
+ // 通过 resolve 往上找,依赖不一定在 node_modules,可能被提到根目录,并且没有 link
43
+ const resolved = fs_1.default.existsSync(absPath)
44
+ ? absPath
45
+ : utils_1.resolve.sync(`${args.path}`, {
46
+ basedir: args.resolveDir,
47
+ });
48
+ return { path: resolved, namespace: inlineStyle ? 'style-stub' : '' };
38
49
  });
39
- onResolve({ filter: /\.css$/, namespace: 'style-stub' }, (args) => {
40
- return { path: args.path, namespace: 'style-content' };
41
- });
42
- onResolve({ filter: /^__style_helper__$/, namespace: 'style-stub' }, (args) => ({
43
- path: args.path,
44
- namespace: 'style-helper',
45
- sideEffects: false,
46
- }));
47
- onLoad({ filter: /.*/, namespace: 'style-helper' }, () => __awaiter(this, void 0, void 0, function* () {
48
- return ({
49
- contents: `
50
- export function injectStyle(text) {
51
- if (typeof document !== 'undefined') {
52
- var style = document.createElement('style')
53
- var node = document.createTextNode(text)
54
- style.appendChild(node)
55
- document.head.appendChild(style)
56
- }
57
- }
58
- `,
59
- });
60
- }));
61
- onLoad({ filter: /.*/, namespace: 'style-stub' }, (args) => __awaiter(this, void 0, void 0, function* () {
62
- return ({
63
- contents: `
64
- import { injectStyle } from "__style_helper__"
65
- import css from ${JSON.stringify(args.path)}
66
- injectStyle(css)
67
- `,
50
+ if (inlineStyle) {
51
+ onResolve({ filter: /\.css$/, namespace: 'style-stub' }, (args) => {
52
+ return { path: args.path, namespace: 'style-content' };
68
53
  });
69
- }));
70
- onLoad({ filter: /.*/, namespace: 'style-content' }, (args) => __awaiter(this, void 0, void 0, function* () {
54
+ onResolve({ filter: /^__style_helper__$/, namespace: 'style-stub' }, (args) => ({
55
+ path: args.path,
56
+ namespace: 'style-helper',
57
+ sideEffects: false,
58
+ }));
59
+ onLoad({ filter: /.*/, namespace: 'style-helper' }, () => __awaiter(this, void 0, void 0, function* () {
60
+ return ({
61
+ contents: `
62
+ export function injectStyle(text) {
63
+ if (typeof document !== 'undefined') {
64
+ var style = document.createElement('style')
65
+ var node = document.createTextNode(text)
66
+ style.appendChild(node)
67
+ document.head.appendChild(style)
68
+ }
69
+ }
70
+ `,
71
+ });
72
+ }));
73
+ onLoad({ filter: /.*/, namespace: 'style-stub' }, (args) => __awaiter(this, void 0, void 0, function* () {
74
+ return ({
75
+ contents: `
76
+ import { injectStyle } from "__style_helper__"
77
+ import css from ${JSON.stringify(args.path)}
78
+ injectStyle(css)
79
+ `,
80
+ });
81
+ }));
82
+ }
83
+ onLoad({
84
+ filter: inlineStyle ? /.*/ : /\.css$/,
85
+ namespace: inlineStyle ? 'style-content' : 'file',
86
+ }, (args) => __awaiter(this, void 0, void 0, function* () {
71
87
  const options = Object.assign({ entryPoints: [args.path] }, opt);
72
88
  const { errors, warnings, outputFiles } = yield esbuild_1.default.build(options);
73
- return {
74
- errors,
75
- warnings,
76
- contents: outputFiles[0].text,
77
- loader: 'text',
78
- };
89
+ if (errors.length > 0) {
90
+ return {
91
+ errors,
92
+ warnings,
93
+ contents: outputFiles[0].text,
94
+ loader: 'text',
95
+ };
96
+ }
97
+ const dir = path_1.default.dirname(args.path);
98
+ try {
99
+ const result = yield (0, postcssProcess_1.postcssProcess)(config, outputFiles[0].text, args.path);
100
+ return {
101
+ errors,
102
+ warnings,
103
+ contents: result.css,
104
+ loader: inlineStyle ? 'text' : 'css',
105
+ };
106
+ }
107
+ catch (error) {
108
+ return {
109
+ errors: [
110
+ {
111
+ text: error.message,
112
+ location: {
113
+ namespace: 'file',
114
+ file: error.filename,
115
+ line: error.line,
116
+ column: error.column,
117
+ },
118
+ },
119
+ ],
120
+ resolveDir: dir,
121
+ };
122
+ }
79
123
  }));
80
124
  },
81
125
  };
82
126
  }
83
- exports.inlineStyle = inlineStyle;
127
+ exports.style = style;
@@ -0,0 +1 @@
1
+ export declare function getBrowserlist(targets: Record<string, string | boolean>): string | true | string[];
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getBrowserlist = void 0;
4
+ // refer: https://github.com/umijs/umi-next/blob/867e0c196296efbbdb95203cca35db2fa639808b/packages/bundler-webpack/src/utils/browsersList.ts#L5
5
+ function getBrowserlist(targets) {
6
+ return (targets.browsers ||
7
+ Object.keys(targets).map((key) => {
8
+ return `${key} >= ${targets[key] === true ? '0' : targets[key]}`;
9
+ }));
10
+ }
11
+ exports.getBrowserlist = getBrowserlist;
@@ -0,0 +1,2 @@
1
+ import { IConfig } from '../types';
2
+ export declare function postcssProcess(config: IConfig, css: string, path: string): Promise<import("postcss").Result>;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.postcssProcess = void 0;
16
+ const postcss_1 = __importDefault(require("postcss"));
17
+ const getBrowserlist_1 = require("./getBrowserlist");
18
+ function postcssProcess(config, css, path) {
19
+ return __awaiter(this, void 0, void 0, function* () {
20
+ return yield (0, postcss_1.default)([
21
+ require('postcss-flexbugs-fixes'),
22
+ require('postcss-preset-env')({
23
+ browsers: (0, getBrowserlist_1.getBrowserlist)((config === null || config === void 0 ? void 0 : config.targets) || {}),
24
+ autoprefixer: Object.assign({ flexbox: 'no-2009' }, config === null || config === void 0 ? void 0 : config.autoprefixer),
25
+ stage: 3,
26
+ }),
27
+ ].concat((config === null || config === void 0 ? void 0 : config.extraPostCSSPlugins) || [])).process(css, {
28
+ from: path,
29
+ to: path,
30
+ });
31
+ });
32
+ }
33
+ exports.postcssProcess = postcssProcess;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/bundler-esbuild",
3
- "version": "4.0.0-beta.9",
3
+ "version": "4.0.0-rc.3",
4
4
  "description": "@umijs/bundler-esbuild",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/bundler-esbuild#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -23,12 +23,17 @@
23
23
  "dev": "pnpm build -- --watch"
24
24
  },
25
25
  "dependencies": {
26
- "@umijs/bundler-utils": "4.0.0-beta.9",
27
- "@umijs/utils": "4.0.0-beta.9",
28
- "enhanced-resolve": "5.8.3",
29
- "less": "4.1.2"
26
+ "@umijs/bundler-utils": "4.0.0-rc.3",
27
+ "@umijs/utils": "4.0.0-rc.3",
28
+ "enhanced-resolve": "5.9.0",
29
+ "less": "4.1.2",
30
+ "less-plugin-aliases": "^1.0.3",
31
+ "postcss": "^8.4.6",
32
+ "postcss-flexbugs-fixes": "5.0.2",
33
+ "postcss-preset-env": "7.4.1"
30
34
  },
31
35
  "devDependencies": {
36
+ "@alitajs/postcss-plugin-px2rem": "^0.0.1",
32
37
  "@types/less": "^3.0.3"
33
38
  },
34
39
  "publishConfig": {