更新
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
# @dcloudio/vite-plugin-uni
|
||||
|
||||
## Install
|
||||
|
||||
```shell
|
||||
npm i @dcloudio/vite-plugin-uni
|
||||
```
|
||||
|
||||
## Useage
|
||||
|
||||
```ts
|
||||
import { defineConfig } from "vite";
|
||||
import uni from "@dcloudio/vite-plugin-uni";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [uni()],
|
||||
});
|
||||
```
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import { type BuildOptions, type ServerOptions } from 'vite';
|
||||
import type { CliOptions } from '.';
|
||||
export declare function runDev(options: CliOptions & ServerOptions): Promise<undefined>;
|
||||
export declare function runBuild(options: CliOptions & BuildOptions): Promise<void>;
|
||||
export declare const stopProfiler: (log: (message: string) => void) => void | Promise<void>;
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.stopProfiler = exports.runBuild = exports.runDev = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const picocolors_1 = __importDefault(require("picocolors"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const vite_1 = require("vite");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const build_1 = require("./build");
|
||||
const server_1 = require("./server");
|
||||
const utils_1 = require("./utils");
|
||||
const easycom_1 = require("../utils/easycom");
|
||||
const uvue_1 = require("./uvue");
|
||||
const configResolved_1 = require("../configResolved");
|
||||
async function runDev(options) {
|
||||
(0, shared_1.extend)(options, {
|
||||
watch: {},
|
||||
});
|
||||
if (process.env.UNI_MINIMIZE === 'true') {
|
||||
;
|
||||
options.minify = true;
|
||||
}
|
||||
(0, utils_1.initEnv)('dev', options);
|
||||
if (process.env.UNI_APP_X === 'true' &&
|
||||
process.env.UNI_UTS_PLATFORM === 'app-android') {
|
||||
return (0, uvue_1.runUVueAndroidDev)(options);
|
||||
}
|
||||
const createLogger = await Promise.resolve().then(() => __importStar(require('vite'))).then(({ createLogger }) => createLogger);
|
||||
try {
|
||||
if (options.platform === 'h5') {
|
||||
const server = await (options.ssr
|
||||
? (0, server_1.createSSRServer)(options)
|
||||
: (0, server_1.createServer)(options));
|
||||
(0, easycom_1.initEasycom)(server.watcher);
|
||||
}
|
||||
else {
|
||||
const watcher = (await (0, build_1.build)(options));
|
||||
(0, easycom_1.initEasycom)();
|
||||
let isFirstStart = true;
|
||||
let isFirstEnd = true;
|
||||
watcher.on('event', async (event) => {
|
||||
if (event.code === 'BUNDLE_START') {
|
||||
if (isFirstStart) {
|
||||
isFirstStart = false;
|
||||
return;
|
||||
}
|
||||
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.start']);
|
||||
}
|
||||
else if (event.code === 'BUNDLE_END') {
|
||||
event.result.close();
|
||||
if (isFirstEnd) {
|
||||
// 首次全量同步
|
||||
if (options.platform === 'app' ||
|
||||
options.platform === 'app-harmony') {
|
||||
process.env.UNI_APP_CHANGED_FILES = '';
|
||||
}
|
||||
if (options.platform === 'app') {
|
||||
process.env.UNI_APP_CHANGED_PAGES = '';
|
||||
process.env.UNI_APP_UTS_CHANGED_FILES = '';
|
||||
}
|
||||
isFirstEnd = false;
|
||||
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
|
||||
(0, utils_1.showRunPrompt)(options.platform);
|
||||
(0, utils_1.printStartupDuration)(createLogger(options.logLevel), false);
|
||||
if (process.env.UNI_UTS_ERRORS) {
|
||||
console.error(process.env.UNI_UTS_ERRORS);
|
||||
}
|
||||
if (process.env.UNI_UTS_TIPS) {
|
||||
console.warn(process.env.UNI_UTS_TIPS);
|
||||
}
|
||||
await (0, exports.stopProfiler)((message) => createLogger(options.logLevel).info(message));
|
||||
return;
|
||||
}
|
||||
if (options.platform === 'app') {
|
||||
const files = process.env.UNI_APP_CHANGED_FILES;
|
||||
const pages = process.env.UNI_APP_CHANGED_PAGES;
|
||||
const dex = process.env.UNI_APP_UTS_CHANGED_FILES;
|
||||
const changedFiles = pages || files;
|
||||
process.env.UNI_APP_CHANGED_PAGES = '';
|
||||
process.env.UNI_APP_CHANGED_FILES = '';
|
||||
process.env.UNI_APP_UTS_CHANGED_FILES = '';
|
||||
if ((changedFiles &&
|
||||
!changedFiles.includes(uni_cli_shared_1.APP_CONFIG_SERVICE) &&
|
||||
!changedFiles.includes(uni_cli_shared_1.APP_SERVICE_FILENAME)) ||
|
||||
dex) {
|
||||
if (pages) {
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.pages'].replace('{pages}', changedFiles));
|
||||
}
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', JSON.stringify(JSON.parse(changedFiles || JSON.stringify([])).concat(JSON.parse(dex || JSON.stringify([]))))));
|
||||
}
|
||||
}
|
||||
else if (options.platform === 'app-harmony') {
|
||||
const files = process.env.UNI_APP_CHANGED_FILES;
|
||||
if (files) {
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', files));
|
||||
}
|
||||
}
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
|
||||
}
|
||||
else if (event.code === 'END') {
|
||||
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
|
||||
setTimeout(() => {
|
||||
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['build.failed']);
|
||||
process.exit(0);
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if (options.platform === 'h5') {
|
||||
console.error(`error when starting dev server:\n${e.stack || e}`);
|
||||
}
|
||||
else {
|
||||
console.error(`error during build:\n${e.stack || e}`);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
exports.runDev = runDev;
|
||||
async function runBuild(options) {
|
||||
(0, utils_1.initEnv)('build', options);
|
||||
if (process.env.UNI_APP_X === 'true' &&
|
||||
process.env.UNI_UTS_PLATFORM === 'app-android') {
|
||||
return (0, uvue_1.runUVueAndroidBuild)(options);
|
||||
}
|
||||
try {
|
||||
await (options.ssr && options.platform === 'h5'
|
||||
? (0, build_1.buildSSR)(options)
|
||||
: (0, build_1.build)(options));
|
||||
await (0, exports.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
|
||||
console.log(uni_cli_shared_1.M['build.done']);
|
||||
if (options.platform !== 'h5') {
|
||||
(0, utils_1.showRunPrompt)(options.platform);
|
||||
}
|
||||
// 开发者可能用了三方插件,三方插件有可能阻止退出,导致HBuilderX打包状态识别不正确
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)() ||
|
||||
/* 需要排查为什么ext-api编译时没有自动结束 */ process.env
|
||||
.UNI_COMPILE_TARGET === 'ext-api') {
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
(0, configResolved_1.initLogger)({
|
||||
logger: (0, vite_1.createLogger)(options.logLevel),
|
||||
}).error(e.message || e);
|
||||
}
|
||||
else {
|
||||
console.error(e.message || e);
|
||||
}
|
||||
console.error(`Build failed with errors.`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
exports.runBuild = runBuild;
|
||||
let profileSession = global.__vite_profile_session;
|
||||
let profileCount = 0;
|
||||
const stopProfiler = (log) => {
|
||||
if (!profileSession)
|
||||
return;
|
||||
return new Promise((res, rej) => {
|
||||
profileSession.post('Profiler.stop', (err, result) => {
|
||||
// Write profile to disk, upload, etc.
|
||||
if (!err) {
|
||||
const outPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, `./profile-${profileCount++}.cpuprofile`);
|
||||
fs_1.default.writeFileSync(outPath, JSON.stringify(result.profile));
|
||||
log(picocolors_1.default.yellow(`CPU profile written to ${picocolors_1.default.white(picocolors_1.default.dim(outPath))}`));
|
||||
profileSession = undefined;
|
||||
res();
|
||||
}
|
||||
else {
|
||||
rej(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
exports.stopProfiler = stopProfiler;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import type { BuildOptions, InlineConfig } from 'vite';
|
||||
import type { CliOptions } from '.';
|
||||
import type { RollupWatcher } from 'rollup';
|
||||
export declare function buildByVite(inlineConfig: InlineConfig): Promise<import("rollup").RollupOutput | import("rollup").RollupOutput[] | RollupWatcher>;
|
||||
export declare function build(options: CliOptions): Promise<RollupWatcher | void>;
|
||||
export declare function buildSSR(options: CliOptions): Promise<void>;
|
||||
export declare function initBuildOptions(options: CliOptions, build: BuildOptions): InlineConfig;
|
||||
export declare function buildApp(options: CliOptions): Promise<RollupWatcher | void>;
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.buildApp = exports.initBuildOptions = exports.buildSSR = exports.build = exports.buildByVite = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const utils_1 = require("./utils");
|
||||
async function buildByVite(inlineConfig) {
|
||||
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ build }) => build(inlineConfig));
|
||||
}
|
||||
exports.buildByVite = buildByVite;
|
||||
async function build(options) {
|
||||
if (process.env.UNI_APP_X !== 'true' && options.platform === 'app') {
|
||||
return buildApp(options);
|
||||
}
|
||||
return buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, (0, utils_1.cleanOptions)(options))));
|
||||
}
|
||||
exports.build = build;
|
||||
async function buildSSR(options) {
|
||||
const outputDir = process.env.UNI_OUTPUT_DIR;
|
||||
const ssrClientDir = path_1.default.resolve(outputDir, 'client');
|
||||
process.env.UNI_OUTPUT_DIR = ssrClientDir;
|
||||
const ssrBuildClientOptions = (0, utils_1.cleanOptions)(options);
|
||||
ssrBuildClientOptions.ssrManifest = 'ssr-manifest.json';
|
||||
ssrBuildClientOptions.outDir = process.env.UNI_OUTPUT_DIR;
|
||||
process.env.UNI_SSR_CLIENT = 'true';
|
||||
await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, ssrBuildClientOptions)));
|
||||
const ssrServerDir = path_1.default.resolve(outputDir, 'server');
|
||||
process.env.UNI_OUTPUT_DIR = ssrServerDir;
|
||||
const ssrBuildServerOptions = (0, utils_1.cleanOptions)(options);
|
||||
ssrBuildServerOptions.ssr = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'entry-server.js');
|
||||
// 强制 cjs 输出
|
||||
ssrBuildServerOptions.rollupOptions = {
|
||||
output: {
|
||||
format: 'cjs',
|
||||
},
|
||||
};
|
||||
ssrBuildServerOptions.outDir = process.env.UNI_OUTPUT_DIR;
|
||||
process.env.UNI_SSR_CLIENT = '';
|
||||
process.env.UNI_SSR_SERVER = 'true';
|
||||
await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, ssrBuildServerOptions)));
|
||||
// copy ssr-manfiest.json to server
|
||||
const assets = ['ssr-manifest.json', 'index.html'];
|
||||
assets.forEach((asset) => {
|
||||
const ssrManifestFile = path_1.default.join(ssrClientDir, asset);
|
||||
if (fs_extra_1.default.existsSync(ssrManifestFile)) {
|
||||
fs_extra_1.default.copyFileSync(ssrManifestFile, path_1.default.join(ssrServerDir, asset));
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.buildSSR = buildSSR;
|
||||
function initBuildOptions(options, build) {
|
||||
return {
|
||||
root: process.env.VITE_ROOT_DIR,
|
||||
configFile: options.config,
|
||||
base: options.base,
|
||||
logLevel: options.logLevel,
|
||||
clearScreen: options.clearScreen,
|
||||
mode: options.mode,
|
||||
build,
|
||||
};
|
||||
}
|
||||
exports.initBuildOptions = initBuildOptions;
|
||||
function buildManifestJson() {
|
||||
const platform = 'app';
|
||||
const inputDir = process.env.UNI_INPUT_DIR;
|
||||
const outputDir = process.env.UNI_OUTPUT_DIR;
|
||||
const pkg = require(path_1.default.resolve(__dirname, '../../package.json'));
|
||||
process.env.UNI_COMPILER_VERSION =
|
||||
process.env.UNI_COMPILER_VERSION ||
|
||||
pkg['uni-app']?.['compilerVersion'] ||
|
||||
'';
|
||||
const manifestJson = (0, uni_cli_shared_1.normalizeAppManifestJson)((0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir), (0, uni_cli_shared_1.parsePagesJsonOnce)(inputDir, platform));
|
||||
fs_extra_1.default.outputFileSync(path_1.default.resolve(outputDir, 'manifest.json'), JSON.stringify(manifestJson, null, 2));
|
||||
}
|
||||
async function buildApp(options) {
|
||||
if (options.manifest) {
|
||||
return buildManifestJson();
|
||||
}
|
||||
let appWatcher;
|
||||
if (options.watch) {
|
||||
appWatcher = new AppWatcher();
|
||||
}
|
||||
if (process.env.UNI_RENDERER === 'native') {
|
||||
// 纯原生渲染时,main.js + App.vue 需要跟页面分开,独立编译(因为需要包含 Vuex 等共享内容)
|
||||
process.env.UNI_COMPILER = 'nvue';
|
||||
process.env.UNI_RENDERER_NATIVE = 'appService';
|
||||
const nvueAppBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvueAppService: true, nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
|
||||
if (appWatcher) {
|
||||
appWatcher.setFirstWatcher(nvueAppBuilder);
|
||||
}
|
||||
process.env.UNI_RENDERER_NATIVE = 'pages';
|
||||
const nvueBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
|
||||
if (appWatcher) {
|
||||
appWatcher.setSecondWatcher(nvueBuilder);
|
||||
return appWatcher;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 指定为 vue 方便 App 插件初始化 vue 所需插件列表
|
||||
process.env.UNI_COMPILER = 'vue';
|
||||
const vueBuilder = await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, (0, utils_1.cleanOptions)(options))));
|
||||
if (!(0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
// 不需要 nvue 编译器
|
||||
return vueBuilder;
|
||||
}
|
||||
if (appWatcher) {
|
||||
appWatcher.setFirstWatcher(vueBuilder);
|
||||
}
|
||||
// 临时指定为 nvue 方便 App 插件初始化 nvue 所需插件列表
|
||||
process.env.UNI_COMPILER = 'nvue';
|
||||
const nvueBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
|
||||
// 还原为 vue
|
||||
process.env.UNI_COMPILER = 'vue';
|
||||
if (appWatcher) {
|
||||
appWatcher.setSecondWatcher(nvueBuilder);
|
||||
return appWatcher;
|
||||
}
|
||||
}
|
||||
exports.buildApp = buildApp;
|
||||
class AppWatcher {
|
||||
constructor() {
|
||||
this._firstStart = false;
|
||||
this._firstEnd = false;
|
||||
this._secondStart = false;
|
||||
this._secondEnd = false;
|
||||
}
|
||||
on(_event, callback) {
|
||||
this._callback = callback;
|
||||
}
|
||||
setFirstWatcher(firstWatcher) {
|
||||
firstWatcher.on('event', (event) => {
|
||||
if (event.code === 'BUNDLE_START') {
|
||||
this._bundleFirstStart(event);
|
||||
}
|
||||
else if (event.code === 'BUNDLE_END') {
|
||||
this._bundleFirstEnd(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
setSecondWatcher(secondWatcher) {
|
||||
secondWatcher.on('event', (event) => {
|
||||
if (event.code === 'BUNDLE_START') {
|
||||
this._bundleSecondStart(event);
|
||||
}
|
||||
else if (event.code === 'BUNDLE_END') {
|
||||
this._bundleSecondEnd(event);
|
||||
}
|
||||
});
|
||||
}
|
||||
_bundleFirstStart(event) {
|
||||
this._firstStart = true;
|
||||
this._bundleStart(event);
|
||||
}
|
||||
_bundleFirstEnd(event) {
|
||||
this._firstEnd = true;
|
||||
this._bundleEnd(event);
|
||||
}
|
||||
_bundleSecondStart(event) {
|
||||
this._secondStart = true;
|
||||
this._bundleStart(event);
|
||||
}
|
||||
_bundleSecondEnd(event) {
|
||||
this._secondEnd = true;
|
||||
this._bundleEnd(event);
|
||||
}
|
||||
_bundleStart(event) {
|
||||
if (this._firstStart && this._secondStart) {
|
||||
this._callback(event);
|
||||
}
|
||||
}
|
||||
_bundleEnd(event) {
|
||||
if (this._firstEnd && this._secondEnd) {
|
||||
this._callback(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import type { LogLevel } from 'vite';
|
||||
export interface CliOptions {
|
||||
'--'?: string[];
|
||||
c?: boolean | string;
|
||||
config?: string;
|
||||
platform?: string;
|
||||
p?: string;
|
||||
ssr?: boolean;
|
||||
base?: string;
|
||||
debug?: boolean | string;
|
||||
d?: boolean | string;
|
||||
filter?: string;
|
||||
f?: string;
|
||||
logLevel?: LogLevel;
|
||||
l?: LogLevel;
|
||||
m?: string;
|
||||
mode?: string;
|
||||
clearScreen?: boolean;
|
||||
autoHost?: string;
|
||||
autoPort?: number;
|
||||
devtools?: boolean;
|
||||
devtoolsHost?: string;
|
||||
devtoolsPort?: number;
|
||||
subpackage?: string;
|
||||
plugin?: string;
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const cac_1 = require("cac");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const utils_1 = require("./utils");
|
||||
const action_1 = require("./action");
|
||||
(0, uni_cli_shared_1.fixBinaryPath)();
|
||||
const cli = (0, cac_1.cac)('uni');
|
||||
cli
|
||||
.option('-c, --config <file>', `[string] use specified config file`)
|
||||
.option('-p, --platform [platform]', '[string] ' + utils_1.PLATFORMS.join(' | '), {
|
||||
default: 'h5',
|
||||
})
|
||||
.option('--base <path>', `[string] public base path (default: /)`)
|
||||
.option('-ssr', '[boolean] server-side rendering', {
|
||||
default: false,
|
||||
})
|
||||
.option('-l, --logLevel <level>', `[string] silent | error | warn | all`)
|
||||
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
|
||||
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
|
||||
.option('-f, --filter <filter>', `[string] filter debug logs`)
|
||||
.option('-m, --mode <mode>', `[string] set env mode`)
|
||||
.option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` +
|
||||
`or specify minifier to use (default: terser)`)
|
||||
.option('--autoHost [autoHost]', `[string] specify automator hostname`)
|
||||
.option('--autoPort [autoPort]', `[number] specify automator port`)
|
||||
.option('--devtools', `[boolean] enable devtools`)
|
||||
.option('--devtoolsHost [devtoolsHost]', `[string] specify devtools hostname`)
|
||||
.option('--devtoolsPort [devtoolsPort]', `[number] specify devtools port`)
|
||||
.option('--subpackage [subpackage]', `[string] specify subpackage to build`)
|
||||
.option('--plugin [plugin]', `[string] specify plugin to build`);
|
||||
cli
|
||||
.command('')
|
||||
.alias('dev')
|
||||
.option('--host [host]', `[string] specify hostname`)
|
||||
.option('--port <port>', `[number] specify port`)
|
||||
.option('--https', `[boolean] use TLS + HTTP/2`)
|
||||
.option('--open [path]', `[boolean | string] open browser on startup`)
|
||||
.option('--cors', `[boolean] enable CORS`)
|
||||
.option('--strictPort', `[boolean] exit if specified port is already in use`)
|
||||
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
|
||||
.action(action_1.runDev);
|
||||
cli
|
||||
.command('build')
|
||||
.option('--outDir <dir>', `[string] output directory (default: dist)`)
|
||||
.option('--assetsInlineLimit <number>', `[number] static asset base64 inline threshold in bytes (default: 4096)`)
|
||||
.option('--sourcemap', `[boolean] output source maps for build (default: false)`)
|
||||
.option('--manifest', `[boolean] emit build manifest json`)
|
||||
.option('--ssrManifest', `[boolean] emit ssr manifest json`)
|
||||
.option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`, {
|
||||
default: true,
|
||||
})
|
||||
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
|
||||
.action(action_1.runBuild);
|
||||
cli.help();
|
||||
cli.version(require('../../package.json').version);
|
||||
cli.parse();
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function initNVueEnv(): void;
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initNVueEnv = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function initNVueEnv() {
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
return;
|
||||
}
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
|
||||
if ((0, uni_cli_shared_1.getAppRenderer)(manifestJson) === 'native') {
|
||||
process.env.UNI_RENDERER = 'native';
|
||||
}
|
||||
const nvueCompiler = (0, uni_cli_shared_1.getNVueCompiler)(manifestJson);
|
||||
if (nvueCompiler === 'uni-app') {
|
||||
process.env.UNI_NVUE_COMPILER = 'uni-app';
|
||||
}
|
||||
else if (nvueCompiler === 'vue') {
|
||||
process.env.UNI_NVUE_COMPILER = 'vue';
|
||||
}
|
||||
if ((0, uni_cli_shared_1.getNVueStyleCompiler)(manifestJson) === 'uni-app') {
|
||||
process.env.UNI_NVUE_STYLE_COMPILER = 'uni-app';
|
||||
}
|
||||
if ((0, uni_cli_shared_1.getAppCodeSpliting)(manifestJson)) {
|
||||
process.env.UNI_APP_CODE_SPLITING = 'true';
|
||||
}
|
||||
}
|
||||
exports.initNVueEnv = initNVueEnv;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import type { ServerOptions, ViteDevServer } from 'vite';
|
||||
import type { CliOptions } from '.';
|
||||
export declare function createServer(options: CliOptions & ServerOptions): Promise<ViteDevServer>;
|
||||
export declare function createSSRServer(options: CliOptions & ServerOptions): Promise<ViteDevServer>;
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createSSRServer = exports.createServer = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const os_1 = __importDefault(require("os"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const picocolors_1 = __importDefault(require("picocolors"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const utils_1 = require("./utils");
|
||||
function createLogger(level, options) {
|
||||
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ createLogger }) => createLogger(level, options));
|
||||
}
|
||||
function createViteServer(inlineConfig) {
|
||||
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ createServer }) => createServer(inlineConfig));
|
||||
}
|
||||
async function createServer(options) {
|
||||
const server = await createViteServer((0, utils_1.addConfigFile)({
|
||||
root: process.env.VITE_ROOT_DIR,
|
||||
configFile: options.config,
|
||||
base: options.base,
|
||||
mode: options.mode,
|
||||
logLevel: options.logLevel || 'info',
|
||||
clearScreen: options.clearScreen,
|
||||
server: (0, utils_1.cleanOptions)(options),
|
||||
}));
|
||||
await server.listen();
|
||||
const logger = server.config.logger;
|
||||
logger.info(picocolors_1.default.cyan(`\n vite v${require('vite/package.json').version}`) +
|
||||
picocolors_1.default.green(` dev server running at:\n`), {
|
||||
clear: !server.config.logger.hasWarned,
|
||||
});
|
||||
server.printUrls();
|
||||
// printUrls 会在 nextTick 中输出
|
||||
process.nextTick(() => (0, utils_1.printStartupDuration)(logger));
|
||||
return server;
|
||||
}
|
||||
exports.createServer = createServer;
|
||||
async function createSSRServer(options) {
|
||||
// 延迟加载
|
||||
const app = (await Promise.resolve().then(() => __importStar(require('express')))).default();
|
||||
/**
|
||||
* @type {import('vite').ViteDevServer}
|
||||
*/
|
||||
const vite = await createViteServer((0, utils_1.addConfigFile)({
|
||||
// custom: don't include HTML middlewares
|
||||
appType: 'custom',
|
||||
root: process.env.VITE_ROOT_DIR,
|
||||
configFile: options.config,
|
||||
base: options.base,
|
||||
mode: options.mode,
|
||||
logLevel: options.logLevel || 'info',
|
||||
clearScreen: options.clearScreen,
|
||||
server: {
|
||||
middlewareMode: true,
|
||||
watch: {
|
||||
// During tests we edit the files too fast and sometimes chokidar
|
||||
// misses change events, so enforce polling for consistency
|
||||
usePolling: true,
|
||||
interval: 100,
|
||||
},
|
||||
},
|
||||
}));
|
||||
// use vite's connect instance as middleware
|
||||
app.use(vite.middlewares);
|
||||
app.use('*', async (req, res) => {
|
||||
try {
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJson)(process.env.UNI_INPUT_DIR);
|
||||
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
|
||||
const base = (h5 && h5.router && h5.router.base) || '';
|
||||
const url = req.originalUrl.replace(base, '');
|
||||
const template = await vite.transformIndexHtml(url, fs_1.default.readFileSync(path_1.default.resolve(process.env.VITE_ROOT_DIR, 'index.html'), 'utf-8'));
|
||||
const render = (await vite.ssrLoadModule(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'entry-server.js'))).render;
|
||||
const { title, headMeta, preloadLinks, appHtml, appContext } = await render(url);
|
||||
const icon = template.includes('rel="icon"')
|
||||
? ''
|
||||
: '<link rel="icon" href="data:," />\n';
|
||||
const html = template
|
||||
.replace(/<title>(.*?)<\/title>/, `${icon}<title>${title}</title>`)
|
||||
.replace(`<!--head-meta-->`, headMeta)
|
||||
.replace(`<!--preload-links-->`, preloadLinks)
|
||||
.replace(`<!--app-html-->`, appHtml)
|
||||
.replace(`<!--app-context-->`, appContext);
|
||||
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
|
||||
}
|
||||
catch (e) {
|
||||
vite && vite.ssrFixStacktrace(e);
|
||||
res.status(500).end(e.stack);
|
||||
}
|
||||
});
|
||||
const logger = await createLogger(options.logLevel);
|
||||
const serverOptions = vite.config.server || {};
|
||||
let port = options.port || serverOptions.port || 5173;
|
||||
let hostname;
|
||||
if (options.host === 'localhost') {
|
||||
// Use a secure default
|
||||
hostname = '127.0.0.1';
|
||||
}
|
||||
else if (options.host === undefined || options.host === true) {
|
||||
// probably passed --host in the CLI, without arguments
|
||||
hostname = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
|
||||
}
|
||||
else {
|
||||
hostname = options.host;
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const onSuccess = () => {
|
||||
printHttpServerUrls(server, vite.config);
|
||||
process.nextTick(() => (0, utils_1.printStartupDuration)(logger));
|
||||
resolve(vite);
|
||||
};
|
||||
const onError = (e) => {
|
||||
if (e.code === 'EADDRINUSE') {
|
||||
if (options.strictPort) {
|
||||
server.off('error', onError);
|
||||
reject(new Error(`Port ${port} is already in use`));
|
||||
}
|
||||
else {
|
||||
logger.info(`Port ${port} is in use, trying another one...`);
|
||||
server = app.listen(++port, hostname, onSuccess).on('error', onError);
|
||||
}
|
||||
}
|
||||
else {
|
||||
server.off('error', onError);
|
||||
reject(e);
|
||||
}
|
||||
};
|
||||
let server = app.listen(port, hostname, onSuccess).on('error', onError);
|
||||
});
|
||||
}
|
||||
exports.createSSRServer = createSSRServer;
|
||||
function printHttpServerUrls(server, config) {
|
||||
printCommonServerUrls(server, config.server, config);
|
||||
}
|
||||
function printCommonServerUrls(server, options, config) {
|
||||
const address = server.address();
|
||||
const isAddressInfo = (x) => x?.address;
|
||||
if (isAddressInfo(address)) {
|
||||
const hostname = resolveHostname(options.host);
|
||||
const protocol = options.https ? 'https' : 'http';
|
||||
printServerUrls(hostname, protocol, address.port, config.base, config.logger.info);
|
||||
}
|
||||
}
|
||||
function printServerUrls(hostname, protocol, port, base, info) {
|
||||
if (hostname.host === '127.0.0.1') {
|
||||
const url = `${protocol}://${hostname.name}:${picocolors_1.default.bold(port)}${base}`;
|
||||
info(` - Local: ${picocolors_1.default.cyan(url)}`);
|
||||
if (hostname.name !== '127.0.0.1') {
|
||||
info(` - Network: ${picocolors_1.default.dim('use `--host` to expose')}`);
|
||||
}
|
||||
}
|
||||
else {
|
||||
Object.values(os_1.default.networkInterfaces())
|
||||
.flatMap((nInterface) => nInterface ?? [])
|
||||
.filter((detail) => detail &&
|
||||
detail.address &&
|
||||
// Node < v18
|
||||
((typeof detail.family === 'string' && detail.family === 'IPv4') ||
|
||||
// Node >= v18
|
||||
// @ts-expect-error
|
||||
(typeof detail.family === 'number' && detail.family === 4)))
|
||||
.map((detail) => {
|
||||
const type = detail.address.includes('127.0.0.1')
|
||||
? ' - Local: '
|
||||
: ' * Network: ';
|
||||
const host = detail.address.replace('127.0.0.1', hostname.name);
|
||||
const url = `${protocol}://${host}:${picocolors_1.default.bold(port)}${base}`;
|
||||
return `${type} ${picocolors_1.default.cyan(url)}`;
|
||||
})
|
||||
.sort((msg1) => {
|
||||
return msg1.indexOf('- Local') > -1 ? -1 : 1;
|
||||
})
|
||||
.forEach((msg, index, arr) => {
|
||||
if (arr.length - 1 === index) {
|
||||
info(msg.replace('* Network', '- Network'));
|
||||
}
|
||||
else {
|
||||
info(msg);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
function resolveHostname(optionsHost) {
|
||||
let host;
|
||||
if (optionsHost === undefined || optionsHost === false) {
|
||||
// Use a secure default
|
||||
host = '127.0.0.1';
|
||||
}
|
||||
else if (optionsHost === true) {
|
||||
// If passed --host in the CLI without arguments
|
||||
host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
|
||||
}
|
||||
else {
|
||||
host = optionsHost;
|
||||
}
|
||||
// Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
|
||||
const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
|
||||
host === '0.0.0.0' ||
|
||||
host === '::' ||
|
||||
host === undefined
|
||||
? 'localhost'
|
||||
: host;
|
||||
return { host, name };
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import type { InlineConfig, Logger } from 'vite';
|
||||
import type { CliOptions } from '.';
|
||||
export declare const PLATFORMS: string[];
|
||||
export type PLATFORM = 'app' | 'mp-alipay' | 'mp-baidu' | 'mp-kuaishou' | 'mp-lark' | 'mp-qq' | 'mp-toutiao' | 'mp-weixin' | 'mp-xhs' | 'quickapp-webview' | 'quickapp-webview-huawei' | 'quickapp-webview-union';
|
||||
export declare function addConfigFile(inlineConfig: InlineConfig): InlineConfig;
|
||||
export declare function initEnv(type: 'unknown' | 'dev' | 'build', options: CliOptions): void;
|
||||
export declare function cleanOptions(options: CliOptions): {
|
||||
'--'?: string[] | undefined;
|
||||
c?: string | boolean | undefined;
|
||||
config?: string | undefined;
|
||||
platform?: string | undefined;
|
||||
p?: string | undefined;
|
||||
ssr?: boolean | undefined;
|
||||
base?: string | undefined;
|
||||
debug?: string | boolean | undefined;
|
||||
d?: string | boolean | undefined;
|
||||
filter?: string | undefined;
|
||||
f?: string | undefined;
|
||||
logLevel?: import("vite").LogLevel | undefined;
|
||||
l?: import("vite").LogLevel | undefined;
|
||||
m?: string | undefined;
|
||||
mode?: string | undefined;
|
||||
clearScreen?: boolean | undefined;
|
||||
autoHost?: string | undefined;
|
||||
autoPort?: number | undefined;
|
||||
devtools?: boolean | undefined;
|
||||
devtoolsHost?: string | undefined;
|
||||
devtoolsPort?: number | undefined;
|
||||
subpackage?: string | undefined;
|
||||
plugin?: string | undefined;
|
||||
};
|
||||
export declare function printStartupDuration(logger: Logger, whitespace?: boolean): void;
|
||||
export declare function showRunPrompt(platform: PLATFORM): void;
|
||||
+377
@@ -0,0 +1,377 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.showRunPrompt = exports.printStartupDuration = exports.cleanOptions = exports.initEnv = exports.addConfigFile = exports.PLATFORMS = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const os_1 = __importDefault(require("os"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const picocolors_1 = __importDefault(require("picocolors"));
|
||||
const perf_hooks_1 = require("perf_hooks");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const nvue_1 = require("./nvue");
|
||||
const uvue_1 = require("./uvue");
|
||||
// uni -p
|
||||
exports.PLATFORMS = [
|
||||
'app',
|
||||
'h5',
|
||||
'mp-alipay',
|
||||
'mp-baidu',
|
||||
'mp-kuaishou',
|
||||
'mp-lark',
|
||||
'mp-qq',
|
||||
'mp-toutiao',
|
||||
'mp-weixin',
|
||||
'mp-xhs',
|
||||
'quickapp-webview',
|
||||
'quickapp-webview-huawei',
|
||||
'quickapp-webview-union',
|
||||
];
|
||||
function resolveConfigFile() {
|
||||
const extname = ['.js', '.ts', '.mjs', '.mts'].find((ext) => {
|
||||
return fs_1.default.existsSync(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'vite.config' + ext));
|
||||
});
|
||||
if (extname) {
|
||||
return path_1.default.resolve(process.env.UNI_INPUT_DIR, 'vite.config' + extname);
|
||||
}
|
||||
return path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'vite.config.js');
|
||||
}
|
||||
function addConfigFile(inlineConfig) {
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
inlineConfig.configFile = resolveConfigFile();
|
||||
}
|
||||
return inlineConfig;
|
||||
}
|
||||
exports.addConfigFile = addConfigFile;
|
||||
let initialized = false;
|
||||
function initEnv(type, options) {
|
||||
if (initialized) {
|
||||
return;
|
||||
}
|
||||
initialized = true;
|
||||
if (options.platform === 'mp-360') {
|
||||
console.error(uni_cli_shared_1.M['mp.360.unsupported']);
|
||||
process.exit(0);
|
||||
}
|
||||
if (options.platform === 'web') {
|
||||
options.platform = 'h5';
|
||||
}
|
||||
if (options.plugin) {
|
||||
process.env.UNI_MP_PLUGIN = options.plugin;
|
||||
}
|
||||
// TODO 需要识别 mode
|
||||
if (type === 'dev') {
|
||||
process.env.NODE_ENV = 'development';
|
||||
}
|
||||
else if (type === 'build') {
|
||||
if (options.watch) {
|
||||
process.env.NODE_ENV = 'development';
|
||||
}
|
||||
else {
|
||||
if (!(0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
if (!process.env.NODE_ENV) {
|
||||
process.env.NODE_ENV = 'production';
|
||||
}
|
||||
}
|
||||
else {
|
||||
process.env.NODE_ENV = 'production';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!options.mode) {
|
||||
options.mode = process.env.NODE_ENV;
|
||||
}
|
||||
// vite 会修改 NODE_ENV,存储在 UNI_NODE_ENV 中,稍后校正 NODE_ENV
|
||||
process.env.UNI_NODE_ENV = process.env.VITE_USER_NODE_ENV =
|
||||
process.env.NODE_ENV;
|
||||
process.env.UNI_CLI_CONTEXT = (0, uni_cli_shared_1.isInHBuilderX)()
|
||||
? path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, 'uniapp-cli-vite')
|
||||
: process.cwd();
|
||||
// TODO 待优化
|
||||
initUTSPlatform(options);
|
||||
if (options.platform === 'quickapp-webview-huawei' ||
|
||||
options.platform === 'quickapp-webview-union') {
|
||||
process.env.UNI_SUB_PLATFORM = options.platform;
|
||||
options.platform = 'quickapp-webview';
|
||||
}
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
process.env.VITE_ROOT_DIR =
|
||||
process.env.VITE_ROOT_DIR || process.env.UNI_INPUT_DIR || process.cwd();
|
||||
}
|
||||
else {
|
||||
process.env.VITE_ROOT_DIR = process.env.VITE_ROOT_DIR || process.cwd();
|
||||
}
|
||||
process.env.UNI_INPUT_DIR =
|
||||
process.env.UNI_INPUT_DIR || path_1.default.resolve(process.cwd(), 'src');
|
||||
initCustomScripts(options);
|
||||
process.env.UNI_PLATFORM = options.platform;
|
||||
// 需要提前初始化
|
||||
(0, uvue_1.initUVueEnv)();
|
||||
if (process.env.UNI_PLATFORM === 'app-harmony') {
|
||||
if (process.env.UNI_APP_HARMONY_PROJECT_PATH) {
|
||||
// 先通过原始outputDir设置,因为下边会修改原始的outputDir到鸿蒙项目里,而这些临时目录不应该影响到鸿蒙项目
|
||||
process.env.UNI_APP_X_TSC_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.tsc');
|
||||
process.env.UNI_APP_X_UVUE_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.uvue');
|
||||
const baseOutDir = path_1.default.basename(process.env.UNI_OUTPUT_DIR);
|
||||
process.env.UNI_APP_X_CACHE_DIR =
|
||||
process.env.UNI_APP_X_CACHE_DIR ||
|
||||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + baseOutDir);
|
||||
process.env.UNI_APP_X_TSC_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, `tsc`);
|
||||
// 指定了鸿蒙项目根目录
|
||||
process.env.UNI_OUTPUT_DIR = path_1.default.resolve(process.env.UNI_APP_HARMONY_PROJECT_PATH, `entry/src/main/resources/resfile/apps/HBuilder/www`);
|
||||
}
|
||||
}
|
||||
const hasOutputDir = !!process.env.UNI_OUTPUT_DIR;
|
||||
if (hasOutputDir) {
|
||||
;
|
||||
options.outDir = process.env.UNI_OUTPUT_DIR;
|
||||
}
|
||||
else {
|
||||
if (!options.outDir) {
|
||||
;
|
||||
options.outDir = path_1.default.resolve(process.cwd(), 'dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', (0, uni_cli_shared_1.getPlatformDir)());
|
||||
}
|
||||
process.env.UNI_OUTPUT_DIR = options.outDir;
|
||||
}
|
||||
// 编译为插件、分包时,需提前计算缓存目录位置
|
||||
process.env.UNI_APP_X_CACHE_DIR =
|
||||
process.env.UNI_APP_X_CACHE_DIR ||
|
||||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + path_1.default.basename(process.env.UNI_OUTPUT_DIR));
|
||||
// 兼容 HBuilderX 旧参数
|
||||
if (process.env.UNI_SUBPACKGE) {
|
||||
options.subpackage = process.env.UNI_SUBPACKGE;
|
||||
}
|
||||
if (options.subpackage) {
|
||||
process.env.UNI_SUBPACKAGE = options.subpackage;
|
||||
if (!hasOutputDir) {
|
||||
// 未指定,则自动补充
|
||||
process.env.UNI_OUTPUT_DIR = options.outDir =
|
||||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, options.subpackage);
|
||||
}
|
||||
}
|
||||
if (options.plugin) {
|
||||
if (!hasOutputDir) {
|
||||
// 未指定,则自动补充
|
||||
process.env.UNI_OUTPUT_DIR = options.outDir =
|
||||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, options.plugin);
|
||||
}
|
||||
}
|
||||
const baseOutDir = path_1.default.basename(process.env.UNI_OUTPUT_DIR);
|
||||
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
process.env.HX_DEPENDENCIES_DIR =
|
||||
process.env.HX_DEPENDENCIES_DIR ||
|
||||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../hx/' + baseOutDir);
|
||||
}
|
||||
process.env.UNI_MODULES_ENCRYPT_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, '.encrypt', process.env.NODE_ENV === 'development' ? 'dev' : 'build', process.env.UNI_UTS_PLATFORM);
|
||||
// 默认开启 tsc
|
||||
process.env.UNI_APP_X_TSC = 'true';
|
||||
try {
|
||||
// 部分模式下缺少manifest.json,比如内部编译ext-api时
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
|
||||
// 留个开关
|
||||
if (manifestJson['app']?.['utsCompilerVersion'] === 'v1' ||
|
||||
manifestJson['app-plus']?.['utsCompilerVersion'] === 'v1') {
|
||||
process.env.UNI_APP_X_TSC = 'false';
|
||||
}
|
||||
}
|
||||
catch (e) { }
|
||||
if (!process.env.UNI_APP_X_TSC_DIR) {
|
||||
process.env.UNI_APP_X_TSC_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.tsc');
|
||||
}
|
||||
if (!process.env.UNI_APP_X_UVUE_DIR) {
|
||||
process.env.UNI_APP_X_UVUE_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.uvue');
|
||||
}
|
||||
if (!process.env.UNI_APP_X_TSC_CACHE_DIR) {
|
||||
process.env.UNI_APP_X_TSC_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, `tsc`);
|
||||
}
|
||||
initAutomator(options);
|
||||
initDevtools(options);
|
||||
if (process.env.UNI_PLATFORM === 'app') {
|
||||
(0, nvue_1.initNVueEnv)();
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
console.log(uni_cli_shared_1.M['dev.performance'] +
|
||||
(process.env.UNI_PLATFORM.startsWith('mp-')
|
||||
? uni_cli_shared_1.M['dev.performance.mp']
|
||||
: '') +
|
||||
(process.env.UNI_PLATFORM === 'web' || process.env.UNI_PLATFORM === 'h5'
|
||||
? uni_cli_shared_1.M['dev.performance.web']
|
||||
: ''));
|
||||
}
|
||||
if (options.sourcemap &&
|
||||
process.env.NODE_ENV === 'production') {
|
||||
process.env.SOURCEMAP = 'true';
|
||||
}
|
||||
(0, uni_cli_shared_1.initModulePaths)();
|
||||
const pkg = require('../../package.json');
|
||||
process.env.UNI_COMPILER_VERSION =
|
||||
process.env.UNI_COMPILER_VERSION ||
|
||||
pkg['uni-app']?.['compilerVersion'] ||
|
||||
'';
|
||||
process.env.UNI_COMPILER_VERSION_TYPE = pkg.version.includes('alpha')
|
||||
? 'a'
|
||||
: 'r';
|
||||
(0, uni_cli_shared_1.initPreContext)(process.env.UNI_PLATFORM, process.env.UNI_CUSTOM_CONTEXT, process.env.UNI_UTS_PLATFORM, process.env.UNI_APP_X === 'true');
|
||||
if (process.env.UNI_PLATFORM === 'app' ||
|
||||
process.env.UNI_PLATFORM === 'web' ||
|
||||
process.env.UNI_PLATFORM === 'h5' ||
|
||||
process.env.UNI_PLATFORM === 'app-harmony') {
|
||||
console.log(uni_cli_shared_1.M['app.compiler.version'].replace('{version}', process.env.UNI_COMPILER_VERSION +
|
||||
`(${process.env.UNI_APP_X === 'true' ? 'uni-app x' : 'vue3'})`));
|
||||
}
|
||||
console.log(uni_cli_shared_1.M['compiling']);
|
||||
}
|
||||
exports.initEnv = initEnv;
|
||||
function initUTSPlatform(options) {
|
||||
if (options.platform === 'app-android') {
|
||||
process.env.UNI_UTS_PLATFORM = 'app-android';
|
||||
options.platform = 'app';
|
||||
}
|
||||
else if (options.platform === 'app-ios') {
|
||||
process.env.UNI_UTS_PLATFORM = 'app-ios';
|
||||
options.platform = 'app';
|
||||
}
|
||||
else {
|
||||
// 运行时,可能传入了 UNI_APP_PLATFORM = 'android'|'ios'
|
||||
if (process.env.UNI_APP_PLATFORM === 'android') {
|
||||
process.env.UNI_UTS_PLATFORM = 'app-android';
|
||||
}
|
||||
if (process.env.UNI_APP_PLATFORM === 'ios') {
|
||||
process.env.UNI_UTS_PLATFORM = 'app-ios';
|
||||
}
|
||||
if (options.platform === 'app-plus') {
|
||||
options.platform = 'app';
|
||||
}
|
||||
if (options.platform === 'app') {
|
||||
// app 平台未指定 UTS_PLATFORM 时,设置未 app,一般是发行模式
|
||||
if (!process.env.UNI_UTS_PLATFORM) {
|
||||
process.env.UNI_UTS_PLATFORM = 'app';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (options.platform === 'h5') {
|
||||
process.env.UNI_UTS_PLATFORM = 'web';
|
||||
}
|
||||
// 非 app 平台,自动补充 UNI_UTS_PLATFORM
|
||||
// app 平台,必须主动传入
|
||||
if (options.platform !== 'app') {
|
||||
if (!process.env.UNI_UTS_PLATFORM) {
|
||||
process.env.UNI_UTS_PLATFORM = options.platform;
|
||||
}
|
||||
}
|
||||
process.env.UNI_UTS_TARGET_LANGUAGE = 'javascript';
|
||||
if (process.env.UNI_UTS_PLATFORM === 'app-android') {
|
||||
process.env.UNI_UTS_TARGET_LANGUAGE = 'kotlin';
|
||||
}
|
||||
else if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
|
||||
process.env.UNI_UTS_TARGET_LANGUAGE = 'swift';
|
||||
}
|
||||
else if (process.env.UNI_UTS_PLATFORM === 'app-harmony') {
|
||||
process.env.UNI_UTS_TARGET_LANGUAGE = 'arkts';
|
||||
}
|
||||
}
|
||||
function initDevtools({ devtools, devtoolsHost, devtoolsPort }) {
|
||||
if (!devtools) {
|
||||
return;
|
||||
}
|
||||
process.env.__VUE_PROD_DEVTOOLS__ = 'true';
|
||||
if (devtoolsHost) {
|
||||
process.env.__VUE_DEVTOOLS_HOST__ = devtoolsHost;
|
||||
}
|
||||
if (devtoolsPort) {
|
||||
process.env.__VUE_DEVTOOLS_PORT__ = devtoolsPort + '';
|
||||
}
|
||||
}
|
||||
function initAutomator({ autoHost, autoPort }) {
|
||||
const hasAutoHostOrPort = autoHost || autoPort || process.env.UNI_AUTOMATOR_HOST;
|
||||
// 发行分包,插件也不需要自动化测试
|
||||
if (!hasAutoHostOrPort ||
|
||||
process.env.UNI_SUBPACKAGE ||
|
||||
process.env.UNI_MP_PLUGIN) {
|
||||
return;
|
||||
}
|
||||
process.env.UNI_AUTOMATOR_WS_ENDPOINT =
|
||||
'ws://' +
|
||||
(autoHost || process.env.UNI_AUTOMATOR_HOST || resolveHostname()) +
|
||||
':' +
|
||||
(autoPort || process.env.UNI_AUTOMATOR_PORT);
|
||||
}
|
||||
function resolveHostname() {
|
||||
const interfaces = os_1.default.networkInterfaces();
|
||||
const keys = Object.keys(interfaces);
|
||||
for (const key of keys) {
|
||||
const interfaceInfos = interfaces[key];
|
||||
if (!interfaceInfos) {
|
||||
continue;
|
||||
}
|
||||
for (const info of interfaceInfos) {
|
||||
if ((info.family === 'IPv4' ||
|
||||
/* Node >= v18 */ info.family === 4) &&
|
||||
!info.address.includes('127.0.0.1')) {
|
||||
return info.address;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 'localhost';
|
||||
}
|
||||
function cleanOptions(options) {
|
||||
const ret = { ...options };
|
||||
delete ret['--'];
|
||||
delete ret.c;
|
||||
delete ret.config;
|
||||
delete ret.platform;
|
||||
delete ret.p;
|
||||
delete ret.ssr;
|
||||
delete ret.base;
|
||||
delete ret.debug;
|
||||
delete ret.d;
|
||||
delete ret.filter;
|
||||
delete ret.f;
|
||||
delete ret.logLevel;
|
||||
delete ret.l;
|
||||
delete ret.clearScreen;
|
||||
delete ret.m;
|
||||
delete ret.mode;
|
||||
delete ret.autoHost;
|
||||
delete ret.autoPort;
|
||||
return ret;
|
||||
}
|
||||
exports.cleanOptions = cleanOptions;
|
||||
function printStartupDuration(logger, whitespace = true) {
|
||||
if (global.__vite_start_time) {
|
||||
const startupDuration = perf_hooks_1.performance.now() - global.__vite_start_time;
|
||||
logger.info(`${whitespace ? `\n ` : ''}${picocolors_1.default.cyan(`ready in ${Math.ceil(startupDuration)}ms.`)}\n`);
|
||||
}
|
||||
}
|
||||
exports.printStartupDuration = printStartupDuration;
|
||||
function initCustomScripts(options) {
|
||||
const custom = (0, uni_cli_shared_1.parseScripts)(process.env.UNI_SCRIPT || options.platform, // process.env.UNI_SCRIPT 是 HBuilderX 传递的
|
||||
path_1.default.join(process.env.VITE_ROOT_DIR, 'package.json'));
|
||||
if (!custom) {
|
||||
return;
|
||||
}
|
||||
options.platform = custom.platform;
|
||||
process.env.UNI_CUSTOM_SCRIPT = custom.name;
|
||||
process.env.UNI_CUSTOM_DEFINE = JSON.stringify(custom.define);
|
||||
process.env.UNI_CUSTOM_CONTEXT = JSON.stringify(custom.context);
|
||||
}
|
||||
function showRunPrompt(platform) {
|
||||
if (!(0, uni_cli_shared_1.runByHBuilderX)()) {
|
||||
const devtools = getPlatformDevtools(getOriginalPlatform(platform));
|
||||
const outputDir = path_1.default.relative(process.env.UNI_CLI_CONTEXT, process.env.UNI_OUTPUT_DIR);
|
||||
(0, uni_cli_shared_1.output)('log', `${uni_cli_shared_1.M['prompt.run.message']
|
||||
.replace('{devtools}', uni_cli_shared_1.M[devtools])
|
||||
.replace('{outputDir}', picocolors_1.default.cyan(outputDir))}`);
|
||||
}
|
||||
}
|
||||
exports.showRunPrompt = showRunPrompt;
|
||||
function getOriginalPlatform(platform) {
|
||||
if (platform.startsWith('quickapp-webview') && process.env.UNI_SUB_PLATFORM) {
|
||||
return process.env.UNI_SUB_PLATFORM;
|
||||
}
|
||||
return platform;
|
||||
}
|
||||
function getPlatformDevtools(platform) {
|
||||
return `prompt.run.devtools.${platform}`;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import { type BuildOptions, type ServerOptions } from 'vite';
|
||||
import type { RollupWatcher } from 'rollup';
|
||||
import type { CliOptions } from '.';
|
||||
export declare function initUVueEnv(): void;
|
||||
export declare function runUVueAndroidDev(options: CliOptions & ServerOptions): Promise<undefined>;
|
||||
export declare function runUVueAndroidBuild(options: CliOptions & BuildOptions): Promise<void>;
|
||||
/**
|
||||
* 目前的简易实现逻辑
|
||||
* node层:
|
||||
* 1. 监听项目,生成资源到临时目录 .uts/android
|
||||
* 2. uvue 文件,做解析,拆分生成 render.kt, css.kt, uts.uvue
|
||||
* 3. static 文件,copy 到最终目录
|
||||
* 4. uvue、vue、uts 文件发生变化,调用 uts 编译器
|
||||
* @param options
|
||||
*/
|
||||
export declare function buildUVue(options: CliOptions): Promise<RollupWatcher | void>;
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.buildUVue = exports.runUVueAndroidBuild = exports.runUVueAndroidDev = exports.initUVueEnv = void 0;
|
||||
const vite_1 = require("vite");
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const build_1 = require("./build");
|
||||
const utils_1 = require("./utils");
|
||||
const easycom_1 = require("../utils/easycom");
|
||||
const action_1 = require("./action");
|
||||
function initUVueEnv() {
|
||||
// 直接指定了
|
||||
if (process.env.UNI_APP_X === 'false') {
|
||||
return;
|
||||
}
|
||||
// 没有手动指定时,才需要动态读取 manifest.json
|
||||
if (process.env.UNI_APP_X !== 'true') {
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
|
||||
if (!(0, shared_1.hasOwn)(manifestJson, 'uni-app-x')) {
|
||||
return;
|
||||
}
|
||||
process.env.UNI_APP_X = 'true';
|
||||
if (manifestJson['uni-app-x']?.singleThread === false) {
|
||||
process.env.UNI_APP_X_SINGLE_THREAD = 'false';
|
||||
}
|
||||
}
|
||||
if (process.env.UNI_PLATFORM === 'app') {
|
||||
process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE = 'native';
|
||||
// 如果是app-ios,目前强制使用js引擎
|
||||
if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
|
||||
process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE = 'js';
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.initUVueEnv = initUVueEnv;
|
||||
async function runUVueAndroidDev(options) {
|
||||
if (options.platform !== 'app') {
|
||||
(0, uni_cli_shared_1.output)('error', uni_cli_shared_1.M['uvue.unsupported'].replace('{platform}', options.platform));
|
||||
return process.exit(0);
|
||||
}
|
||||
(0, easycom_1.initEasycom)();
|
||||
const watcher = (await buildUVue(options));
|
||||
let isFirstStart = true;
|
||||
let isFirstEnd = true;
|
||||
watcher.on('event', async (event) => {
|
||||
if (event.code === 'BUNDLE_START') {
|
||||
if (isFirstStart) {
|
||||
isFirstStart = false;
|
||||
return;
|
||||
}
|
||||
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.start']);
|
||||
// 重置一下,uts编译报错会导致下一次开始差量编译紧接着上一次的差量编译,导致无法正常输出
|
||||
(0, uni_cli_shared_1.resetOutput)('log');
|
||||
}
|
||||
else if (event.code === 'BUNDLE_END') {
|
||||
event.result.close();
|
||||
const dex = process.env.UNI_APP_UTS_CHANGED_FILES;
|
||||
process.env.UNI_APP_UTS_CHANGED_FILES = '';
|
||||
if (isFirstEnd) {
|
||||
// 首次全量同步
|
||||
isFirstEnd = false;
|
||||
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
|
||||
(0, utils_1.printStartupDuration)((0, vite_1.createLogger)(options.logLevel), false);
|
||||
await (0, action_1.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
|
||||
return;
|
||||
}
|
||||
if (dex) {
|
||||
const files = JSON.parse(dex);
|
||||
if (!files.length) {
|
||||
// 本次无变动
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['uvue.dev.watching.end.empty']);
|
||||
}
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', JSON.stringify(files)));
|
||||
}
|
||||
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
|
||||
}
|
||||
});
|
||||
}
|
||||
exports.runUVueAndroidDev = runUVueAndroidDev;
|
||||
async function runUVueAndroidBuild(options) {
|
||||
try {
|
||||
(0, uni_cli_shared_1.initEasycomsOnce)(process.env.UNI_INPUT_DIR, {
|
||||
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
|
||||
platform: process.env.UNI_PLATFORM,
|
||||
isX: true,
|
||||
});
|
||||
await buildUVue(options);
|
||||
await (0, action_1.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
|
||||
console.log(uni_cli_shared_1.M['build.done']);
|
||||
// 开发者可能用了三方插件,三方插件有可能阻止退出,导致HBuilderX打包状态识别不正确
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
process.exit(0);
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e.message || e);
|
||||
console.error(`Build failed with errors.`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
exports.runUVueAndroidBuild = runUVueAndroidBuild;
|
||||
/**
|
||||
* 目前的简易实现逻辑
|
||||
* node层:
|
||||
* 1. 监听项目,生成资源到临时目录 .uts/android
|
||||
* 2. uvue 文件,做解析,拆分生成 render.kt, css.kt, uts.uvue
|
||||
* 3. static 文件,copy 到最终目录
|
||||
* 4. uvue、vue、uts 文件发生变化,调用 uts 编译器
|
||||
* @param options
|
||||
*/
|
||||
async function buildUVue(options) {
|
||||
return (0, build_1.buildByVite)((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvueAppService: true, uvue: true }, (0, build_1.initBuildOptions)(options, (0, utils_1.cleanOptions)(options)))));
|
||||
}
|
||||
exports.buildUVue = buildUVue;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { UserConfig } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createBuild(options: VitePluginUniResolvedOptions, config: UserConfig): UserConfig['build'];
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createBuild = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const shared_1 = require("@vue/shared");
|
||||
function createBuild(options, config) {
|
||||
(0, uni_cli_shared_1.initEasycomsOnce)(options.inputDir, {
|
||||
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
|
||||
platform: process.env.UNI_PLATFORM,
|
||||
isX: process.env.UNI_APP_X === 'true',
|
||||
});
|
||||
const rollupOutputOption = config.build?.rollupOptions?.output;
|
||||
const sourcemap = process.env.SOURCEMAP === 'true' ? 'hidden' : config.build?.sourcemap;
|
||||
return {
|
||||
sourcemap,
|
||||
cssTarget: uni_cli_shared_1.cssTarget,
|
||||
chunkSizeWarningLimit: 100000000,
|
||||
minify: config.build && (0, shared_1.hasOwn)(config.build, 'minify')
|
||||
? config.build.minify
|
||||
: process.env.NODE_ENV === 'production'
|
||||
? 'terser'
|
||||
: false,
|
||||
rollupOptions: {
|
||||
onwarn(warning, warn) {
|
||||
if (warning.code === 'EMPTY_BUNDLE') {
|
||||
// 忽略空包警告,通常是条件编译之类导致的
|
||||
// Generated an empty chunk:
|
||||
return;
|
||||
}
|
||||
if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {
|
||||
const { message } = warning;
|
||||
// ignore
|
||||
if (message.includes('"vue"') ||
|
||||
message.includes('"resolveComponent"') ||
|
||||
message.includes('"@dcloudio/uni-h5"')) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
warn(warning);
|
||||
},
|
||||
output: {
|
||||
sourcemapExcludeSources: !(0, shared_1.isArray)(rollupOutputOption) &&
|
||||
rollupOutputOption?.sourcemapExcludeSources === false
|
||||
? false
|
||||
: process.env.SOURCEMAP === 'true',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.createBuild = createBuild;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { UserConfig } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createCss(options: VitePluginUniResolvedOptions, config: UserConfig): UserConfig['css'];
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createCss = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function resolveAdditionalData(inputDir, config) {
|
||||
const uniScssFile = path_1.default.resolve(inputDir, 'uni.scss');
|
||||
const userAdditionalData = config.css?.preprocessorOptions?.scss?.additionalData || '';
|
||||
if (!fs_extra_1.default.existsSync(uniScssFile)) {
|
||||
return userAdditionalData;
|
||||
}
|
||||
let content = fs_extra_1.default.readFileSync(uniScssFile, 'utf8');
|
||||
if (content.includes('#endif')) {
|
||||
content = (0, uni_cli_shared_1.preCss)(content, uniScssFile);
|
||||
}
|
||||
return content + '\n' + userAdditionalData;
|
||||
}
|
||||
function createCss(options, config) {
|
||||
return {
|
||||
preprocessorOptions: {
|
||||
scss: {
|
||||
charset: false,
|
||||
additionalData: resolveAdditionalData(options.inputDir, config),
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.createCss = createCss;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { UserConfig } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createDefine(_: VitePluginUniResolvedOptions): UserConfig['define'];
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createDefine = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function createDefine(_) {
|
||||
return (0, shared_1.extend)({
|
||||
__VUE_I18N_FULL_INSTALL__: true,
|
||||
__VUE_I18N_LEGACY_API__: true,
|
||||
__VUE_I18N_PROD_DEVTOOLS__: false,
|
||||
__INTLIFY_PROD_DEVTOOLS__: false,
|
||||
}, (0, uni_cli_shared_1.initDefine)());
|
||||
}
|
||||
exports.createDefine = createDefine;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createConfig(options: VitePluginUniResolvedOptions, _uniPlugins: Plugin[]): Plugin['config'];
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createConfig = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const css_1 = require("./css");
|
||||
const resolve_1 = require("./resolve");
|
||||
const build_1 = require("./build");
|
||||
const optimizeDeps_1 = require("./optimizeDeps");
|
||||
const define_1 = require("./define");
|
||||
function createConfig(options, _uniPlugins) {
|
||||
return (config, env) => {
|
||||
options.command = env.command;
|
||||
let base = config.base;
|
||||
if (!base) {
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(options.inputDir);
|
||||
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
|
||||
base = (h5 && h5.router && h5.router.base) || '';
|
||||
}
|
||||
if (!base) {
|
||||
base = '/';
|
||||
}
|
||||
options.base = base;
|
||||
const pluginConfig = {
|
||||
base: process.env.UNI_H5_BASE || base,
|
||||
root: process.env.VITE_ROOT_DIR,
|
||||
// TODO 临时设置为__static__,屏蔽警告:https://github.com/vitejs/vite/blob/824d042535033a5c3d7006978c0d05c201cd1c25/packages/vite/src/node/server/middlewares/transform.ts#L125
|
||||
publicDir: config.publicDir || '__static__',
|
||||
define: (0, define_1.createDefine)(options),
|
||||
resolve: (0, resolve_1.createResolve)(options, config),
|
||||
logLevel: config.logLevel || 'warn', // 默认使用 warn 等级,因为 info 等级vite:report 会输出文件列表等信息
|
||||
optimizeDeps: (0, optimizeDeps_1.createOptimizeDeps)(options),
|
||||
build: (0, build_1.createBuild)(options, config),
|
||||
css: (0, css_1.createCss)(options, config),
|
||||
esbuild: {
|
||||
include: /\.(tsx?|jsx|uts)$/,
|
||||
exclude: /\.js$/,
|
||||
loader: 'ts',
|
||||
},
|
||||
};
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
pluginConfig.cacheDir = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../../cache/.vite');
|
||||
}
|
||||
return pluginConfig;
|
||||
};
|
||||
}
|
||||
exports.createConfig = createConfig;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { UserConfig } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createOptimizeDeps(_options: VitePluginUniResolvedOptions): UserConfig['optimizeDeps'];
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createOptimizeDeps = void 0;
|
||||
function createOptimizeDeps(_options) {
|
||||
return {
|
||||
exclude: [
|
||||
'vue',
|
||||
'vuex',
|
||||
'vue-i18n',
|
||||
'vue-router',
|
||||
'@dcloudio/uni-app',
|
||||
'@dcloudio/uni-components',
|
||||
'@dcloudio/uni-i18n',
|
||||
'@dcloudio/uni-shared',
|
||||
'@dcloudio/uni-stacktracey',
|
||||
'pinia',
|
||||
],
|
||||
};
|
||||
}
|
||||
exports.createOptimizeDeps = createOptimizeDeps;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
import type { ResolverFunction, UserConfig } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare const customResolver: ResolverFunction;
|
||||
export declare function createResolve(options: VitePluginUniResolvedOptions, _config: UserConfig): UserConfig['resolve'];
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createResolve = exports.customResolver = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function resolveUTSModuleProxyFile(id, importer) {
|
||||
const file = (0, uni_cli_shared_1.resolveUTSAppModule)(process.env.UNI_UTS_PLATFORM, id, importer);
|
||||
if (file) {
|
||||
// app-js 会返回完整路径,不需要 uts-proxy
|
||||
if (file.endsWith('.uts')) {
|
||||
return file;
|
||||
}
|
||||
return file + '?uts-proxy';
|
||||
}
|
||||
}
|
||||
const customResolver = (updatedId, importer) => {
|
||||
updatedId = updatedId.split('?')[0];
|
||||
const utsImporter = importer
|
||||
? path_1.default.dirname(importer)
|
||||
: process.env.UNI_INPUT_DIR;
|
||||
const utsModuleFile = process.env.UNI_PLATFORM === 'app' ||
|
||||
process.env.UNI_PLATFORM === 'app-harmony'
|
||||
? resolveUTSModuleProxyFile(updatedId, utsImporter)
|
||||
: (0, uni_cli_shared_1.resolveUTSModule)(updatedId, utsImporter);
|
||||
if (utsModuleFile) {
|
||||
return uni_cli_shared_1.isWindows ? (0, uni_cli_shared_1.normalizePath)(utsModuleFile) : utsModuleFile;
|
||||
}
|
||||
const resolveId = (0, uni_cli_shared_1.resolveEncryptUniModule)((0, uni_cli_shared_1.normalizePath)(updatedId), process.env.UNI_UTS_PLATFORM, process.env.UNI_APP_X === 'true');
|
||||
if (resolveId) {
|
||||
return resolveId;
|
||||
}
|
||||
if (uni_cli_shared_1.isWindows) {
|
||||
return (0, uni_cli_shared_1.normalizePath)((0, uni_cli_shared_1.requireResolve)(updatedId, importer || process.env.UNI_INPUT_DIR));
|
||||
}
|
||||
return (0, uni_cli_shared_1.requireResolve)(updatedId, importer || process.env.UNI_INPUT_DIR);
|
||||
};
|
||||
exports.customResolver = customResolver;
|
||||
function createResolve(options, _config) {
|
||||
const alias = [];
|
||||
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
// 加密组件内部使用的 vue export helper,需要重新映射回来
|
||||
alias.push({
|
||||
find: 'plugin-vue:export-helper',
|
||||
replacement: '\0plugin-vue:export-helper',
|
||||
});
|
||||
}
|
||||
return {
|
||||
// 必须使用alias解析,插件定制的resolveId,不会被应用到css等预处理器中
|
||||
alias: [
|
||||
// because @rollup/plugin-alias' type doesn't allow function
|
||||
// replacement, but its implementation does work with function values.
|
||||
{
|
||||
find: /^(~@|@)\/(.*)/,
|
||||
replacement(_str, _$1, $2) {
|
||||
return (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(options.inputDir, $2));
|
||||
},
|
||||
customResolver: exports.customResolver,
|
||||
},
|
||||
...alias,
|
||||
],
|
||||
extensions: process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.uni_app_x_extensions : uni_cli_shared_1.extensions,
|
||||
preserveSymlinks: true,
|
||||
};
|
||||
}
|
||||
exports.createResolve = createResolve;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
export declare function initEnv(config: ResolvedConfig): void;
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initEnv = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function initEnv(config) {
|
||||
if (!process.env.UNI_PLATFORM) {
|
||||
process.env.UNI_PLATFORM = 'h5';
|
||||
}
|
||||
if (!process.env.UNI_CLI_CONTEXT) {
|
||||
process.env.UNI_CLI_CONTEXT = process.cwd();
|
||||
}
|
||||
if (!process.env.UNI_INPUT_DIR) {
|
||||
process.env.UNI_INPUT_DIR = path_1.default.resolve(config.root, 'src');
|
||||
}
|
||||
if (!process.env.UNI_OUTPUT_DIR) {
|
||||
process.env.UNI_OUTPUT_DIR = path_1.default.resolve(config.root, config.build.outDir);
|
||||
}
|
||||
process.env.VUE_APP_DARK_MODE =
|
||||
(0, uni_cli_shared_1.getPlatformManifestJsonOnce)().darkmode || false;
|
||||
process.env.BROWSERSLIST_CONFIG = [
|
||||
path_1.default.resolve(process.env.UNI_INPUT_DIR, '.browserslistrc'),
|
||||
path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'package.json'),
|
||||
path_1.default.resolve(process.cwd(), 'package.json'),
|
||||
].find((file) => fs_1.default.existsSync(file));
|
||||
}
|
||||
exports.initEnv = initEnv;
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import type { Logger, Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function createConfigResolved(options: VitePluginUniResolvedOptions): Plugin['configResolved'];
|
||||
export declare function initLogger({ logger, nvue, }: {
|
||||
logger: Logger;
|
||||
nvue?: boolean;
|
||||
}): Logger;
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initLogger = exports.createConfigResolved = void 0;
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const env_1 = require("./env");
|
||||
const options_1 = require("./options");
|
||||
const plugins_1 = require("./plugins");
|
||||
const resolve_1 = require("../config/resolve");
|
||||
function createConfigResolved(options) {
|
||||
return (config) => {
|
||||
// 如果是混合编译且是 nvue 时,部分逻辑无需执行
|
||||
if (!(0, uni_cli_shared_1.isInHybridNVue)(config)) {
|
||||
(0, env_1.initEnv)(config);
|
||||
}
|
||||
initLogger(config);
|
||||
(0, options_1.initOptions)(options, config);
|
||||
(0, plugins_1.initPlugins)(config, options);
|
||||
if (!(0, uni_cli_shared_1.isInHybridNVue)(config)) {
|
||||
initCheckUpdate();
|
||||
}
|
||||
if (uni_cli_shared_1.isWindows) {
|
||||
// TODO 等 https://github.com/vitejs/vite/issues/3331 修复后,可以移除下列代码
|
||||
// 2.8.0 已修复,但为了兼容旧版本,先不移除
|
||||
const item = config.resolve.alias.find((item) => !(0, shared_1.isString)(item.find) ? item.find.test('@/') : false);
|
||||
if (item) {
|
||||
item.customResolver = resolve_1.customResolver;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.createConfigResolved = createConfigResolved;
|
||||
function initCheckUpdate() {
|
||||
(0, uni_cli_shared_1.checkUpdate)({
|
||||
inputDir: process.env.UNI_INPUT_DIR,
|
||||
compilerVersion: process.env.UNI_COMPILER_VERSION,
|
||||
versionType: process.env.UNI_COMPILER_VERSION_TYPE,
|
||||
});
|
||||
}
|
||||
function initLogger({ logger, nvue, }) {
|
||||
const { info, warn, error } = logger;
|
||||
logger.info = (msg, opts) => {
|
||||
msg = (0, uni_cli_shared_1.formatInfoMsg)(msg, (0, shared_1.extend)(opts || {}, { nvue }));
|
||||
if (msg) {
|
||||
return info(msg, opts);
|
||||
}
|
||||
};
|
||||
logger.warn = (msg, opts) => {
|
||||
msg = (0, uni_cli_shared_1.formatWarnMsg)(msg, opts);
|
||||
if (msg) {
|
||||
return warn(msg, opts);
|
||||
}
|
||||
};
|
||||
logger.error = (msg, opts) => {
|
||||
msg = (0, uni_cli_shared_1.formatErrMsg)(msg, opts);
|
||||
if (msg) {
|
||||
return error(msg, opts);
|
||||
}
|
||||
};
|
||||
return logger;
|
||||
}
|
||||
exports.initLogger = initLogger;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
export declare function initOptions(options: VitePluginUniResolvedOptions, config: ResolvedConfig): void;
|
||||
Generated
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initOptions = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function resolveBase() {
|
||||
const manifest = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
|
||||
const webManifest = (0, uni_cli_shared_1.getPlatformManifestJson)(manifest, 'h5');
|
||||
return (webManifest && webManifest.router && webManifest.router.base) || '/';
|
||||
}
|
||||
function initOptions(options, config) {
|
||||
options.base = resolveBase();
|
||||
options.outputDir = process.env.UNI_OUTPUT_DIR;
|
||||
options.assetsDir = config.build.assetsDir;
|
||||
}
|
||||
exports.initOptions = initOptions;
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import type { ResolvedConfig } from 'vite';
|
||||
import type { FilterPattern } from '@rollup/pluginutils';
|
||||
import type { VitePluginUniResolvedOptions } from '../..';
|
||||
export interface UniPluginFilterOptions extends VitePluginUniResolvedOptions {
|
||||
include?: FilterPattern;
|
||||
exclude?: FilterPattern;
|
||||
}
|
||||
export declare function initPlugins(config: ResolvedConfig, options: VitePluginUniResolvedOptions): void;
|
||||
Generated
Vendored
+50
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initPlugins = void 0;
|
||||
// import debug from 'debug'
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const json_1 = require("./json");
|
||||
const preCss_1 = require("./preCss");
|
||||
const static_1 = require("./static");
|
||||
const preVue_1 = require("./preVue");
|
||||
const ssr_1 = require("./ssr");
|
||||
const resolveId_1 = require("./resolveId");
|
||||
const UNI_H5_RE = /@dcloudio\/uni-h5/;
|
||||
function initPlugins(config, options) {
|
||||
const uniPrePluginOptions = {
|
||||
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE, UNI_H5_RE],
|
||||
};
|
||||
const uniPreCssPluginOptions = {
|
||||
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE],
|
||||
};
|
||||
const plugins = config.plugins;
|
||||
addPlugin(plugins, (0, resolveId_1.uniResolveIdPlugin)(options), 'vite:resolve', 'pre');
|
||||
addPlugin(plugins, (0, uni_cli_shared_1.uniPrePlugin)(config, (0, shared_1.extend)(uniPrePluginOptions, options)), 0, 'pre');
|
||||
addPlugin(plugins, (0, preCss_1.uniPreCssPlugin)(config, (0, shared_1.extend)(uniPreCssPluginOptions, options)), 'vite:css');
|
||||
addPlugin(plugins, (0, preVue_1.uniPreVuePlugin)(), 'vite:vue', 'pre');
|
||||
addPlugin(plugins, (0, ssr_1.uniSSRPlugin)(config, (0, shared_1.extend)({ exclude: [...uni_cli_shared_1.COMMON_EXCLUDE, /\/@dcloudio\/uni-app/] }, options)), process.env.UNI_APP_X === 'true' ? 'uts' : 'vite:vue');
|
||||
addPlugin(plugins, (0, json_1.uniJsonPlugin)(options), 'vite:json', 'pre');
|
||||
addPlugin(plugins, (0, static_1.uniStaticPlugin)(options, config), 'vite:asset', 'pre');
|
||||
if (process.env.UNI_HBUILDERX_PLUGINS && (0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
try {
|
||||
const { V } = (0, uni_cli_shared_1.requireUniHelpers)();
|
||||
addPlugin(plugins, V({
|
||||
dir: process.env.UNI_INPUT_DIR,
|
||||
cacheDir: process.env.UNI_MODULES_ENCRYPT_CACHE_DIR,
|
||||
}), 0, 'pre');
|
||||
}
|
||||
catch (e) { }
|
||||
}
|
||||
// if (process.env.DEBUG) {
|
||||
// debugPlugin(plugins.length)
|
||||
// debugPlugin(plugins.map((p) => (p as Plugin).name))
|
||||
// }
|
||||
}
|
||||
exports.initPlugins = initPlugins;
|
||||
function addPlugin(plugins, plugin, index, type = 'post') {
|
||||
if ((0, shared_1.isString)(index)) {
|
||||
index = plugins.findIndex((plugin) => plugin.name === index);
|
||||
}
|
||||
return plugins.splice(index + (type === 'pre' ? 0 : 1), 0, plugin);
|
||||
}
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '../..';
|
||||
export declare function uniJsonPlugin(options: VitePluginUniResolvedOptions): Plugin;
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniJsonPlugin = void 0;
|
||||
const jsonc_parser_1 = require("jsonc-parser");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const jsonExtRE = /\.json($|\?)(?!commonjs-proxy)/;
|
||||
const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/;
|
||||
function uniJsonPlugin(options) {
|
||||
return {
|
||||
name: 'uni:json',
|
||||
transform(code, id) {
|
||||
if (!jsonExtRE.test(id))
|
||||
return null;
|
||||
if (SPECIAL_QUERY_RE.test(id))
|
||||
return null;
|
||||
if (id.endsWith('.json.js'))
|
||||
return null;
|
||||
// preprocess
|
||||
if (code.includes('#endif')) {
|
||||
code = (0, uni_cli_shared_1.preJs)(code, id);
|
||||
}
|
||||
let jsonObj = (0, jsonc_parser_1.parse)(code);
|
||||
if ((0, uni_cli_shared_1.isUniAppLocaleFile)(id)) {
|
||||
jsonObj = jsonObj.common || {};
|
||||
}
|
||||
return {
|
||||
code: JSON.stringify(jsonObj),
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniJsonPlugin = uniJsonPlugin;
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import type { UniPluginFilterOptions } from '.';
|
||||
/**
|
||||
* preprocess css
|
||||
* @param options
|
||||
*/
|
||||
export declare function uniPreCssPlugin(config: ResolvedConfig, options: UniPluginFilterOptions): Plugin;
|
||||
Generated
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniPreCssPlugin = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const debugPre = (0, debug_1.default)('uni:pre-css');
|
||||
// const debugPreTry = debug('uni:pre-css-try')
|
||||
const cssLangs = `\\.(css|less|sass|scss|styl|stylus|postcss)($|\\?)`;
|
||||
const cssLangRE = new RegExp(cssLangs);
|
||||
/**
|
||||
* preprocess css
|
||||
* @param options
|
||||
*/
|
||||
function uniPreCssPlugin(config, options) {
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
const isNVue = config.nvue;
|
||||
const preJsFile = isNVue ? uni_cli_shared_1.preNVueJs : uni_cli_shared_1.preJs;
|
||||
return {
|
||||
name: 'uni:pre-css',
|
||||
transform(code, id) {
|
||||
if (!cssLangRE.test(id)) {
|
||||
return;
|
||||
}
|
||||
if (!filter(id)) {
|
||||
return;
|
||||
}
|
||||
// debugPreTry(id)
|
||||
if (!code.includes('#endif')) {
|
||||
return;
|
||||
}
|
||||
debugPre(id);
|
||||
return {
|
||||
code: preJsFile(code, id),
|
||||
map: (0, uni_cli_shared_1.withSourcemap)(config) ? this.getCombinedSourcemap() : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniPreCssPlugin = uniPreCssPlugin;
|
||||
Generated
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
import type { Plugin } from 'vite';
|
||||
export declare function uniPreVuePlugin(): Plugin;
|
||||
Generated
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniPreVuePlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function uniPreVuePlugin() {
|
||||
let isNVue = false;
|
||||
return {
|
||||
name: 'uni:pre-vue',
|
||||
config(config) {
|
||||
isNVue = config.nvue;
|
||||
},
|
||||
async transform(code, id) {
|
||||
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
|
||||
if (query.vue) {
|
||||
return;
|
||||
}
|
||||
if (!(process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.X_EXTNAME_VUE : uni_cli_shared_1.EXTNAME_VUE).includes(path_1.default.extname(filename))) {
|
||||
return;
|
||||
}
|
||||
// 清空当前页面已缓存的 filter 信息
|
||||
(0, uni_cli_shared_1.clearMiniProgramTemplateFilter)((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(id, process.env.UNI_INPUT_DIR)));
|
||||
return {
|
||||
code: (0, uni_cli_shared_1.parseVueCode)(code, isNVue).code, // 暂不提供sourcemap,意义不大
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniPreVuePlugin = uniPreVuePlugin;
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '../..';
|
||||
declare const BUILT_IN_MODULES: {
|
||||
'vue-router': string;
|
||||
vuex: string;
|
||||
'vue-i18n': string;
|
||||
'@dcloudio/uni-app': string;
|
||||
'@dcloudio/uni-cloud': string;
|
||||
'@dcloudio/uni-i18n': string;
|
||||
'@dcloudio/uni-shared': string;
|
||||
'@dcloudio/uni-stacktracey': string;
|
||||
'@vue/shared': string;
|
||||
pinia: string;
|
||||
};
|
||||
export type BuiltInModulesKey = keyof typeof BUILT_IN_MODULES;
|
||||
export declare function uniResolveIdPlugin(options: VitePluginUniResolvedOptions): Plugin;
|
||||
export {};
|
||||
Generated
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniResolveIdPlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
// const debugResolve = debug('uni:resolve-id')
|
||||
const BUILT_IN_MODULES = {
|
||||
'vue-router': 'dist/vue-router.esm-bundler.js',
|
||||
vuex: 'dist/vuex.esm-bundler.js',
|
||||
'vue-i18n': 'dist/vue-i18n.esm-bundler.js',
|
||||
'@dcloudio/uni-app': 'dist/uni-app.es.js',
|
||||
'@dcloudio/uni-cloud': 'dist/uni-cloud.es.js',
|
||||
'@dcloudio/uni-i18n': 'dist/uni-i18n.es.js',
|
||||
'@dcloudio/uni-shared': 'dist/uni-shared.es.js',
|
||||
'@dcloudio/uni-stacktracey': 'dist/uni-stacktracey.es.js',
|
||||
'@vue/shared': 'dist/shared.esm-bundler.js',
|
||||
pinia: 'dist/pinia.mjs',
|
||||
};
|
||||
function uniResolveIdPlugin(options) {
|
||||
const resolveCache = {};
|
||||
return {
|
||||
name: 'uni:resolve-id',
|
||||
resolveId(id, importer) {
|
||||
const cache = resolveCache[id];
|
||||
if (cache) {
|
||||
// debugResolve('cache', id, cache)
|
||||
return cache;
|
||||
}
|
||||
if (BUILT_IN_MODULES[id]) {
|
||||
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.join(id, BUILT_IN_MODULES[id])));
|
||||
}
|
||||
if (process.env.UNI_PLATFORM !== 'app') {
|
||||
return (0, uni_cli_shared_1.resolveUTSModule)(id, importer ? path_1.default.dirname(importer) : process.env.UNI_INPUT_DIR);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniResolveIdPlugin = uniResolveIdPlugin;
|
||||
Generated
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import type { UniPluginFilterOptions } from '.';
|
||||
export declare function uniSSRPlugin(config: ResolvedConfig, options: UniPluginFilterOptions): Plugin;
|
||||
Generated
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniSSRPlugin = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const crypto_1 = __importDefault(require("crypto"));
|
||||
const estree_walker_1 = require("estree-walker");
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const magic_string_1 = __importDefault(require("magic-string"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const debugSSR = (0, debug_1.default)('uni:ssr');
|
||||
const KEYED_FUNC_RE = /(ssrRef|shallowSsrRef)/;
|
||||
function uniSSRPlugin(config, options) {
|
||||
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
|
||||
return {
|
||||
name: 'uni:ssr:ref',
|
||||
transform(code, id) {
|
||||
if (!filter(id))
|
||||
return null;
|
||||
if (!KEYED_FUNC_RE.test(code)) {
|
||||
return;
|
||||
}
|
||||
debugSSR('try', id);
|
||||
const ast = this.parse(code);
|
||||
const s = new magic_string_1.default(code);
|
||||
(0, estree_walker_1.walk)(ast, {
|
||||
enter(node) {
|
||||
if (!(0, uni_cli_shared_1.isCallExpression)(node)) {
|
||||
return;
|
||||
}
|
||||
const { callee, arguments: args } = node;
|
||||
if (args.length !== 1) {
|
||||
return;
|
||||
}
|
||||
const name = (0, uni_cli_shared_1.isIdentifier)(callee)
|
||||
? callee.name
|
||||
: (0, uni_cli_shared_1.isMemberExpression)(callee) && (0, uni_cli_shared_1.isIdentifier)(callee.property)
|
||||
? callee.property.name
|
||||
: '';
|
||||
if (name !== 'ssrRef' && name !== 'shallowSsrRef') {
|
||||
return;
|
||||
}
|
||||
const { end } = node;
|
||||
const key = id + '-' + node.end;
|
||||
debugSSR(key, name);
|
||||
s.appendLeft(end - 1, ", '" + createKey(`${id}-${end}`) + "'");
|
||||
},
|
||||
});
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: (0, uni_cli_shared_1.withSourcemap)(config) ? s.generateMap().toString() : null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniSSRPlugin = uniSSRPlugin;
|
||||
function createKey(source) {
|
||||
const hash = crypto_1.default.createHash('md5');
|
||||
hash.update(source);
|
||||
return hash.digest('base64').toString();
|
||||
}
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import type { Plugin, ResolvedConfig } from 'vite';
|
||||
import type { UniPluginFilterOptions } from '.';
|
||||
/**
|
||||
* 提供static等目录静态资源加载
|
||||
* @param _options
|
||||
* @param config
|
||||
* @returns
|
||||
*/
|
||||
export declare function uniStaticPlugin(_options: UniPluginFilterOptions, config: ResolvedConfig): Plugin;
|
||||
Generated
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniStaticPlugin = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const utils_1 = require("../../utils");
|
||||
const debugStatic = (0, debug_1.default)('uni:static');
|
||||
/**
|
||||
* 提供static等目录静态资源加载
|
||||
* @param _options
|
||||
* @param config
|
||||
* @returns
|
||||
*/
|
||||
function uniStaticPlugin(_options, config) {
|
||||
const filter = (0, utils_1.createPublicFileFilter)();
|
||||
return {
|
||||
name: 'uni:static',
|
||||
resolveId(id) {
|
||||
if (!config.assetsInclude((0, uni_cli_shared_1.cleanUrl)(id))) {
|
||||
return;
|
||||
}
|
||||
const publicFile = filter(id);
|
||||
if (publicFile) {
|
||||
debugStatic(id);
|
||||
return id;
|
||||
}
|
||||
},
|
||||
async load(id) {
|
||||
if (!config.assetsInclude((0, uni_cli_shared_1.cleanUrl)(id))) {
|
||||
return;
|
||||
}
|
||||
if (filter(id)) {
|
||||
return `export default ${JSON.stringify(fileToUrl(id, config))}`;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniStaticPlugin = uniStaticPlugin;
|
||||
function fileToUrl(id, config) {
|
||||
return config.base + id.slice(1);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';
|
||||
import type { Options as VueOptions } from '@vitejs/plugin-vue';
|
||||
import type ViteLegacyPlugin from '@vitejs/plugin-legacy';
|
||||
import type { VueJSXPluginOptions } from '@vue/babel-plugin-jsx';
|
||||
import { type AutoImportOptions, type CopyOptions } from '@dcloudio/uni-cli-shared';
|
||||
export type ViteLegacyOptions = Parameters<typeof ViteLegacyPlugin>[0];
|
||||
export interface VitePluginUniOptions {
|
||||
uvue?: boolean;
|
||||
vueOptions?: VueOptions;
|
||||
vueJsxOptions?: (VueJSXPluginOptions & {
|
||||
babelPlugins?: any[];
|
||||
}) | boolean;
|
||||
viteLegacyOptions?: ViteLegacyOptions | false;
|
||||
autoImportOptions?: AutoImportOptions;
|
||||
}
|
||||
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
|
||||
base: string;
|
||||
command: ResolvedConfig['command'];
|
||||
platform: UniApp.PLATFORM;
|
||||
inputDir: string;
|
||||
outputDir: string;
|
||||
assetsDir: string;
|
||||
devServer?: ViteDevServer;
|
||||
copyOptions?: Required<CopyOptions>;
|
||||
}
|
||||
export { runDev, runBuild } from './cli/action';
|
||||
export default function uniPlugin(rawOptions?: VitePluginUniOptions): Plugin[];
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.runBuild = exports.runDev = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const vite_1 = __importDefault(require("unplugin-auto-import/vite"));
|
||||
const plugin_vue_jsx_1 = __importDefault(require("@vitejs/plugin-vue-jsx"));
|
||||
const plugin_legacy_1 = __importDefault(require("@vitejs/plugin-legacy"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const config_1 = require("./config");
|
||||
const configResolved_1 = require("./configResolved");
|
||||
const copy_1 = require("./plugins/copy");
|
||||
const move_1 = require("./plugins/move");
|
||||
const utils_1 = require("./utils");
|
||||
const vue_1 = require("./vue");
|
||||
const utils_2 = require("./cli/utils");
|
||||
const plugins_1 = require("./uvue/plugins");
|
||||
// const debugUni = debug('uni:plugin')
|
||||
(0, uni_cli_shared_1.initModuleAlias)();
|
||||
var action_1 = require("./cli/action");
|
||||
Object.defineProperty(exports, "runDev", { enumerable: true, get: function () { return action_1.runDev; } });
|
||||
Object.defineProperty(exports, "runBuild", { enumerable: true, get: function () { return action_1.runBuild; } });
|
||||
let isFirst = true;
|
||||
function uniPlugin(rawOptions = {}) {
|
||||
// 重写readFileSync,拦截.scss 等文件读取,实现条件编译,
|
||||
(0, uni_cli_shared_1.rewriteScssReadFileSync)();
|
||||
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
(0, uni_cli_shared_1.rewriteExistsSyncHasRootFile)();
|
||||
}
|
||||
// 三方插件(如vitest)可能提供了自己的入口命令,需要补充 env 初始化逻辑
|
||||
(0, utils_2.initEnv)('unknown', { platform: process.env.UNI_PLATFORM || 'h5' });
|
||||
const options = {
|
||||
...rawOptions,
|
||||
base: '/',
|
||||
assetsDir: 'assets',
|
||||
inputDir: '',
|
||||
outputDir: '',
|
||||
command: 'serve',
|
||||
platform: 'h5',
|
||||
};
|
||||
options.platform = process.env.UNI_PLATFORM || 'h5';
|
||||
options.inputDir = process.env.UNI_INPUT_DIR;
|
||||
const plugins = process.env.UNI_APP_X === 'true' &&
|
||||
process.env.UNI_UTS_PLATFORM === 'app-android'
|
||||
? createUVueAndroidPlugins(options)
|
||||
: createPlugins(options);
|
||||
// x 提供 auto import(非android、android自行处理)
|
||||
if (process.env.UNI_APP_X === 'true' &&
|
||||
process.env.UNI_UTS_PLATFORM !== 'app-android') {
|
||||
plugins.unshift((0, vite_1.default)((0, uni_cli_shared_1.initAutoImportOptions)(process.env.UNI_UTS_PLATFORM, options.autoImportOptions || {})));
|
||||
}
|
||||
plugins.unshift((0, uni_cli_shared_1.uniJsonPlugin)());
|
||||
return plugins;
|
||||
}
|
||||
exports.default = uniPlugin;
|
||||
function createPlugins(options) {
|
||||
const plugins = [];
|
||||
// 框架 ext-api 不需要 inject 本地 ext-api
|
||||
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
|
||||
// uni x 需要插入到指定位置,此插件执行太早,又会引发 vue 文件的不支持,该插件是解析ast的,所以必须是合法的js或ts代码
|
||||
if (process.env.UNI_APP_X === 'true' &&
|
||||
// iOS 暂不使用该机制
|
||||
process.env.UNI_UTS_PLATFORM !== 'app-ios' &&
|
||||
// harmony 同 iOS
|
||||
process.env.UNI_UTS_PLATFORM !== 'app-harmony') {
|
||||
plugins.push((0, uni_cli_shared_1.uniUTSExtApiReplace)());
|
||||
}
|
||||
else {
|
||||
const injects = (0, uni_cli_shared_1.parseUniExtApisOnce)(true, process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE);
|
||||
if (Object.keys(injects).length) {
|
||||
plugins.push((0, uni_cli_shared_1.uniViteInjectPlugin)('uni:ext-api-inject', injects));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 仅限 h5
|
||||
if (options.viteLegacyOptions && options.platform === 'h5') {
|
||||
plugins.push(...(0, plugin_legacy_1.default)((0, vue_1.initPluginViteLegacyOptions)(options)));
|
||||
}
|
||||
const uniPlugins = (0, utils_1.initExtraPlugins)(process.env.UNI_CLI_CONTEXT || process.cwd(), process.env.UNI_PLATFORM || 'h5', options);
|
||||
// debugUni(uniPlugins)
|
||||
const uniPluginOptions = (0, utils_1.initPluginUniOptions)(uniPlugins);
|
||||
options.copyOptions = uniPluginOptions.copyOptions;
|
||||
if (options.vueJsxOptions) {
|
||||
plugins.push((0, plugin_vue_jsx_1.default)((0, vue_1.initPluginVueJsxOptions)(options, uniPluginOptions.compilerOptions, uniPluginOptions.jsxOptions)));
|
||||
}
|
||||
plugins.push({
|
||||
name: 'uni',
|
||||
config: (0, config_1.createConfig)(options, uniPlugins),
|
||||
configResolved: (0, configResolved_1.createConfigResolved)(options),
|
||||
});
|
||||
plugins.push(...uniPlugins);
|
||||
// plugins.push(...initFixedEsbuildInitTSConfck(process.env.UNI_INPUT_DIR))
|
||||
// 执行 build 命令时,vite 强制了 NODE_ENV
|
||||
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/build.ts#L405
|
||||
// const config = await resolveConfig(inlineConfig, 'build', 'production')
|
||||
// 在 @vitejs/plugin-vue 之前校正回来
|
||||
if (process.env.UNI_NODE_ENV &&
|
||||
process.env.UNI_NODE_ENV !== process.env.NODE_ENV) {
|
||||
process.env.NODE_ENV = process.env.UNI_NODE_ENV;
|
||||
}
|
||||
plugins.unshift((0, vue_1.createPluginVueInstance)((0, vue_1.initPluginVueOptions)(options, uniPlugins, uniPluginOptions)));
|
||||
let addCopyPlugin = false;
|
||||
if (options.platform !== 'app') {
|
||||
addCopyPlugin = true;
|
||||
}
|
||||
else {
|
||||
// 仅在 vue 或 纯原生 App.vue 编译时做 copy
|
||||
if (process.env.UNI_COMPILER !== 'nvue' ||
|
||||
(process.env.UNI_RENDERER === 'native' &&
|
||||
process.env.UNI_RENDERER_NATIVE === 'appService')) {
|
||||
addCopyPlugin = true;
|
||||
}
|
||||
else if (process.env.UNI_APP_X === 'true') {
|
||||
// app-ios
|
||||
addCopyPlugin = true;
|
||||
}
|
||||
}
|
||||
if (!(0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
addCopyPlugin = false;
|
||||
}
|
||||
if (addCopyPlugin) {
|
||||
plugins.push((0, copy_1.uniCopyPlugin)({
|
||||
outputDir: process.env.UNI_OUTPUT_DIR,
|
||||
copyOptions: options.copyOptions,
|
||||
}));
|
||||
}
|
||||
if (process.env.SOURCEMAP === 'true') {
|
||||
// 清空之前的 sourcemap 目录
|
||||
const sourceMapPath = (0, uni_cli_shared_1.resolveSourceMapPath)();
|
||||
if (isFirst) {
|
||||
// 避免重复清空
|
||||
isFirst = false;
|
||||
if (fs_1.default.existsSync(sourceMapPath)) {
|
||||
(0, uni_cli_shared_1.emptyDir)(sourceMapPath);
|
||||
}
|
||||
plugins.push((0, move_1.uniMovePlugin)({
|
||||
apply: 'build',
|
||||
enforce: 'post',
|
||||
cwd: process.env.UNI_OUTPUT_DIR,
|
||||
pattern: '**/*.js.map',
|
||||
dest: sourceMapPath,
|
||||
}));
|
||||
}
|
||||
}
|
||||
(0, utils_1.rewriteCompilerSfcParse)();
|
||||
return plugins;
|
||||
}
|
||||
function createUVueAndroidPlugins(options) {
|
||||
const plugins = [];
|
||||
options.uvue = true;
|
||||
const uniPlugins = (0, utils_1.initExtraPlugins)(process.env.UNI_CLI_CONTEXT || process.cwd(), process.env.UNI_PLATFORM || 'h5', options);
|
||||
// debugUni(uniPlugins)
|
||||
const uniPluginOptions = (0, utils_1.initPluginUniOptions)(uniPlugins);
|
||||
options.copyOptions = uniPluginOptions.copyOptions;
|
||||
plugins.push((0, plugins_1.uniUVuePlugin)(options));
|
||||
plugins.push(...uniPlugins);
|
||||
// plugins.push(...initFixedEsbuildInitTSConfck(process.env.UNI_INPUT_DIR))
|
||||
// 执行 build 命令时,vite 强制了 NODE_ENV
|
||||
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/build.ts#L405
|
||||
// const config = await resolveConfig(inlineConfig, 'build', 'production')
|
||||
// 在 @vitejs/plugin-vue 之前校正回来
|
||||
if (process.env.UNI_NODE_ENV &&
|
||||
process.env.UNI_NODE_ENV !== process.env.NODE_ENV) {
|
||||
process.env.NODE_ENV = process.env.UNI_NODE_ENV;
|
||||
}
|
||||
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
|
||||
plugins.push((0, copy_1.uniCopyPlugin)({
|
||||
outputDir: process.env.UNI_OUTPUT_DIR,
|
||||
copyOptions: options.copyOptions,
|
||||
}));
|
||||
}
|
||||
return plugins;
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function uniCopyPlugin({ outputDir, copyOptions, }: Pick<VitePluginUniResolvedOptions, 'outputDir' | 'copyOptions'>): Plugin;
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniCopyPlugin = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const debugCopy = (0, debug_1.default)('uni:copy');
|
||||
function uniCopyPlugin({ outputDir, copyOptions, }) {
|
||||
const staticDir = uni_cli_shared_1.PUBLIC_DIR + '/**/*';
|
||||
const uniModulesStaticDir = 'uni_modules/*/' + uni_cli_shared_1.PUBLIC_DIR + '/**/*';
|
||||
const assets = [staticDir, uniModulesStaticDir];
|
||||
const subpackages = (0, uni_cli_shared_1.parseSubpackagesRootOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
|
||||
subpackages.forEach((root) => {
|
||||
assets.push((0, uni_cli_shared_1.normalizePath)(path_1.default.join(root, staticDir)));
|
||||
assets.push((0, uni_cli_shared_1.normalizePath)(path_1.default.join(root, uniModulesStaticDir)));
|
||||
});
|
||||
copyOptions.assets.forEach((asset) => {
|
||||
assets.push(asset);
|
||||
});
|
||||
const inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
|
||||
const platform = process.env.UNI_PLATFORM;
|
||||
const utsPlatform = process.env.UNI_UTS_PLATFORM;
|
||||
// 非当前平台 static 目录
|
||||
const ignorePlatformStaticDirs = (0, uni_cli_shared_1.getPlatforms)()
|
||||
.filter((p) => {
|
||||
if (platform === 'app') {
|
||||
if (process.env.UNI_APP_X === 'true') {
|
||||
if (p === 'app-android' || p === 'app-ios' || p === 'app-harmony') {
|
||||
return p !== utsPlatform;
|
||||
}
|
||||
return p !== 'app';
|
||||
}
|
||||
return p !== 'app' && p !== 'app-plus';
|
||||
}
|
||||
else if (platform === 'h5' || platform === 'web') {
|
||||
return p !== 'h5' && p !== 'web';
|
||||
}
|
||||
else if (platform.startsWith('app-')) {
|
||||
return p !== 'app' && p !== platform;
|
||||
}
|
||||
return p !== platform;
|
||||
})
|
||||
// 在最后增加 / 是为了避免误判以 platform 开头的目录,比如 app-test
|
||||
.map((p) => '/' + uni_cli_shared_1.PUBLIC_DIR + '/' + p + '/');
|
||||
const targets = [
|
||||
{
|
||||
src: assets,
|
||||
dest: outputDir,
|
||||
watchOptions: {
|
||||
readyTimeout: getReadyTimeout(),
|
||||
ignored(path) {
|
||||
const normalizedPath = (0, uni_cli_shared_1.normalizePath)(path);
|
||||
if (ignorePlatformStaticDirs.find((dir) =>
|
||||
// dir都是以 / 结尾,所以这里也要以 / 结尾
|
||||
(normalizedPath + '/').includes(dir))) {
|
||||
return fs_1.default.statSync(normalizedPath).isDirectory();
|
||||
}
|
||||
// 应该是软链
|
||||
if (!normalizedPath.startsWith(inputDir)) {
|
||||
// 目前仅简单处理static
|
||||
if (normalizedPath.includes('/static/')) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
targets.push(...copyOptions.targets);
|
||||
debugCopy(targets);
|
||||
checkIgnoreStatic(ignorePlatformStaticDirs.map((dir) => dir.substring(1).split('/')));
|
||||
return (0, uni_cli_shared_1.uniViteCopyPlugin)({
|
||||
targets,
|
||||
});
|
||||
}
|
||||
exports.uniCopyPlugin = uniCopyPlugin;
|
||||
let isIgnoreChecked = false;
|
||||
function checkIgnoreStatic(ignoreStatic) {
|
||||
if (isIgnoreChecked) {
|
||||
return;
|
||||
}
|
||||
isIgnoreChecked = true;
|
||||
const existIgnore = new Set();
|
||||
ignoreStatic.forEach((ignore) => {
|
||||
const dir = path_1.default.resolve(process.env.UNI_INPUT_DIR, ...ignore);
|
||||
if (fs_1.default.existsSync(dir)) {
|
||||
existIgnore.add(ignore.join('/'));
|
||||
}
|
||||
});
|
||||
if (existIgnore.size) {
|
||||
console.log('已忽略静态资源目录:' +
|
||||
[...existIgnore].join('、') +
|
||||
'。详见:https://uniapp.dcloud.net.cn/tutorial/platform.html#static');
|
||||
}
|
||||
}
|
||||
function getReadyTimeout() {
|
||||
// chokidar 在部分 windows 上 ready 会触发较早,导致文件还没被全部 copy 过去
|
||||
if (!uni_cli_shared_1.isWindows) {
|
||||
return 1000;
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return 1000;
|
||||
}
|
||||
// 仅在生产环境使用
|
||||
return 4000;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import type { Plugin } from 'vite';
|
||||
interface UniMovePluginOptions {
|
||||
apply: Plugin['apply'];
|
||||
enforce: Plugin['enforce'];
|
||||
/**
|
||||
* 原始根目录
|
||||
*/
|
||||
cwd: string;
|
||||
/**
|
||||
* glob pattern 如:**\/*.js.mp)
|
||||
*/
|
||||
pattern: string;
|
||||
/**
|
||||
* 目标目录
|
||||
*/
|
||||
dest: string;
|
||||
}
|
||||
export declare function uniMovePlugin({ apply, enforce, cwd, pattern, dest, }: UniMovePluginOptions): Plugin;
|
||||
export {};
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniMovePlugin = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const fast_glob_1 = __importDefault(require("fast-glob"));
|
||||
function uniMovePlugin({ apply, enforce, cwd, pattern, dest, }) {
|
||||
return {
|
||||
name: 'uni:move',
|
||||
apply,
|
||||
enforce,
|
||||
async writeBundle() {
|
||||
await Promise.all(fast_glob_1.default
|
||||
.sync(pattern, {
|
||||
cwd,
|
||||
})
|
||||
.map((filename) => {
|
||||
return fs_extra_1.default.move(path_1.default.resolve(cwd, filename), path_1.default.resolve(dest, filename), {
|
||||
overwrite: true,
|
||||
});
|
||||
}));
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniMovePlugin = uniMovePlugin;
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { FSWatcher } from 'chokidar';
|
||||
export declare const initEasycom: (watcher?: FSWatcher) => void;
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initEasycom = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const uni_shared_1 = require("@dcloudio/uni-shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const debugEasycom = (0, debug_1.default)('uni:easycom');
|
||||
const initEasycom = (watcher) => {
|
||||
const { filter, refresh, easyComOptions } = (0, uni_cli_shared_1.initEasycomsOnce)(process.env.UNI_INPUT_DIR, {
|
||||
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
|
||||
platform: process.env.UNI_PLATFORM,
|
||||
isX: process.env.UNI_APP_X === 'true',
|
||||
});
|
||||
if (!watcher) {
|
||||
// build 模式,手动初始化 watcher
|
||||
const dirs = easyComOptions.dirs.concat([
|
||||
(0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR + '/uni_modules'),
|
||||
]);
|
||||
debugEasycom('initWatch', dirs);
|
||||
watcher = uni_cli_shared_1.chokidar.watch(dirs, {
|
||||
ignored: ['**/node_modules/**', '**/.git/**'],
|
||||
ignoreInitial: true,
|
||||
ignorePermissionErrors: true,
|
||||
disableGlobbing: true,
|
||||
});
|
||||
}
|
||||
const refreshEasycom = (0, uni_shared_1.debounce)(refresh, 100, { setTimeout, clearTimeout });
|
||||
watcher.on('all', (eventName, path) => {
|
||||
if (!['add', 'unlink'].includes(eventName)) {
|
||||
return;
|
||||
}
|
||||
if (filter(path)) {
|
||||
debugEasycom('watch', eventName, path);
|
||||
refreshEasycom();
|
||||
}
|
||||
});
|
||||
};
|
||||
exports.initEasycom = initEasycom;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function createPublicFileFilter(base?: string): (id: unknown) => boolean;
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createPublicFileFilter = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const pluginutils_1 = require("@rollup/pluginutils");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function createPublicFileFilter(base = '/') {
|
||||
const publicDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
|
||||
const uniModulesDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, 'uni_modules/*/' + uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
|
||||
return (0, pluginutils_1.createFilter)([publicDir, uniModulesDir]);
|
||||
}
|
||||
exports.createPublicFileFilter = createPublicFileFilter;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
export * from './filter';
|
||||
export * from './plugin';
|
||||
export * from './polyfill';
|
||||
export * from './nvue';
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./filter"), exports);
|
||||
__exportStar(require("./plugin"), exports);
|
||||
__exportStar(require("./polyfill"), exports);
|
||||
__exportStar(require("./nvue"), exports);
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* nvue 需要移除 scoped
|
||||
* @param nvuePages
|
||||
*/
|
||||
export declare function createNVueCompiler(): any;
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.createNVueCompiler = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const shared_1 = require("@vue/shared");
|
||||
/**
|
||||
* nvue 需要移除 scoped
|
||||
* @param nvuePages
|
||||
*/
|
||||
function createNVueCompiler() {
|
||||
const compileSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
|
||||
const { parse } = compileSfc;
|
||||
return (0, shared_1.extend)({}, compileSfc, {
|
||||
parse(source, options = {}) {
|
||||
const result = parse(source, options);
|
||||
result.descriptor.styles.forEach((style) => {
|
||||
if (style.scoped) {
|
||||
delete style.scoped;
|
||||
}
|
||||
});
|
||||
return result;
|
||||
},
|
||||
});
|
||||
}
|
||||
exports.createNVueCompiler = createNVueCompiler;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { type UniViteCopyPluginTarget, type UniVitePlugin } from '@dcloudio/uni-cli-shared';
|
||||
import type { TemplateCompiler } from '@vue/compiler-sfc';
|
||||
import type { VitePluginUniResolvedOptions } from '..';
|
||||
export declare function initPluginUniOptions(UniVitePlugins: UniVitePlugin[]): {
|
||||
compiler?: TemplateCompiler;
|
||||
copyOptions: {
|
||||
assets: string[];
|
||||
targets: UniViteCopyPluginTarget[];
|
||||
};
|
||||
transformEvent: Record<string, string>;
|
||||
compilerOptions: Required<Required<UniVitePlugin>['uni']>['compilerOptions'];
|
||||
jsxOptions: Required<Required<UniVitePlugin>['uni']>['jsxOptions'];
|
||||
styleOptions: Required<Required<UniVitePlugin>['uni']>['styleOptions'];
|
||||
};
|
||||
export declare function initExtraPlugins(cliRoot: string, platform: UniApp.PLATFORM, options: VitePluginUniResolvedOptions): Plugin<any>[];
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initExtraPlugins = exports.initPluginUniOptions = void 0;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
function initPluginUniOptions(UniVitePlugins) {
|
||||
const assets = [];
|
||||
const targets = [];
|
||||
const transformEvent = Object.create(null);
|
||||
const compilerOptions = {};
|
||||
const jsxOptions = {};
|
||||
const styleOptions = {};
|
||||
let compiler;
|
||||
UniVitePlugins.forEach((plugin) => {
|
||||
const { compiler: pluginTemplateCompiler, copyOptions: pluginCopyOptions, compilerOptions: pluginCompilerOptions, jsxOptions: pluginJsxOptions, styleOptions: pluginStyleOpitons, } = plugin.uni || {};
|
||||
if (pluginTemplateCompiler) {
|
||||
compiler = pluginTemplateCompiler;
|
||||
}
|
||||
if (pluginCompilerOptions) {
|
||||
(0, shared_1.extend)(compilerOptions, pluginCompilerOptions);
|
||||
}
|
||||
if (pluginJsxOptions) {
|
||||
(0, shared_1.extend)(jsxOptions, pluginJsxOptions);
|
||||
}
|
||||
if (pluginStyleOpitons) {
|
||||
(0, shared_1.extend)(styleOptions, pluginStyleOpitons);
|
||||
}
|
||||
if (pluginCopyOptions) {
|
||||
let copyOptions = pluginCopyOptions;
|
||||
if ((0, shared_1.isFunction)(pluginCopyOptions)) {
|
||||
copyOptions = pluginCopyOptions();
|
||||
}
|
||||
if (copyOptions.assets) {
|
||||
assets.push(...copyOptions.assets);
|
||||
}
|
||||
if (copyOptions.targets) {
|
||||
targets.push(...copyOptions.targets);
|
||||
}
|
||||
}
|
||||
});
|
||||
return {
|
||||
compiler,
|
||||
copyOptions: {
|
||||
assets,
|
||||
targets,
|
||||
},
|
||||
transformEvent,
|
||||
compilerOptions,
|
||||
jsxOptions,
|
||||
styleOptions,
|
||||
};
|
||||
}
|
||||
exports.initPluginUniOptions = initPluginUniOptions;
|
||||
function initExtraPlugins(cliRoot, platform, options) {
|
||||
return initPlugins(cliRoot, process.env.UNI_COMPILE_TARGET === 'ext-api' &&
|
||||
process.env.UNI_APP_NEXT_WORKSPACE
|
||||
? resolvePluginsByWorkSpace(process.env.UNI_APP_NEXT_WORKSPACE, platform, options.uvue)
|
||||
: resolvePluginsByCliRoot(cliRoot, platform, options.uvue), options);
|
||||
}
|
||||
exports.initExtraPlugins = initExtraPlugins;
|
||||
function initPlugin(_cliRoot, { pluginPath, config: { main } }, options) {
|
||||
let plugin = require(path_1.default.join(pluginPath, main || '/lib/uni.plugin.js'));
|
||||
plugin = plugin.default || plugin;
|
||||
if ((0, shared_1.isFunction)(plugin)) {
|
||||
plugin = plugin(options);
|
||||
}
|
||||
return plugin;
|
||||
}
|
||||
function initPlugins(cliRoot, plugins, options) {
|
||||
return plugins
|
||||
.map((plugin) => initPlugin(cliRoot, plugin, options))
|
||||
.flat()
|
||||
.filter(Boolean)
|
||||
.map((plugin) => {
|
||||
if ((0, shared_1.isFunction)(plugin)) {
|
||||
return plugin(options);
|
||||
}
|
||||
return plugin;
|
||||
})
|
||||
.flat();
|
||||
}
|
||||
function resolvePluginsByCliRoot(cliRoot, platform, uvue = false) {
|
||||
const pkg = require(path_1.default.join(cliRoot, 'package.json'));
|
||||
return resolvePlugins(Object.keys(pkg.devDependencies || {})
|
||||
.concat(Object.keys(pkg.dependencies || {}))
|
||||
.map((id) => {
|
||||
try {
|
||||
const pkgFileName = require.resolve(id + '/package.json', {
|
||||
paths: [cliRoot],
|
||||
});
|
||||
const pkg = require(pkgFileName);
|
||||
return {
|
||||
...pkg,
|
||||
pluginPath: path_1.default.dirname(pkgFileName),
|
||||
};
|
||||
}
|
||||
catch (e) { }
|
||||
})
|
||||
.filter(Boolean), platform, uvue);
|
||||
}
|
||||
function resolvePluginsByWorkSpace(workspaceFolder, platform, uvue = false) {
|
||||
const pkgDirs = path_1.default.resolve(workspaceFolder, 'packages');
|
||||
return resolvePlugins(fs_extra_1.default
|
||||
.readdirSync(pkgDirs)
|
||||
.map((dir) => {
|
||||
const pluginPath = path_1.default.join(pkgDirs, dir);
|
||||
const pkgFileName = path_1.default.join(pluginPath, 'package.json');
|
||||
if (fs_extra_1.default.existsSync(pkgFileName)) {
|
||||
return {
|
||||
...require(pkgFileName),
|
||||
pluginPath,
|
||||
};
|
||||
}
|
||||
})
|
||||
.filter(Boolean), platform, uvue);
|
||||
}
|
||||
function resolvePlugins(pkgs, platform, uvue = false) {
|
||||
return pkgs
|
||||
.map((pkg) => {
|
||||
try {
|
||||
const config = pkg['uni-app'];
|
||||
if (!config || !config.name) {
|
||||
return;
|
||||
}
|
||||
const { apply } = config;
|
||||
if ((0, shared_1.isArray)(apply)) {
|
||||
// 注册所有平台
|
||||
apply.forEach((p) => (0, uni_cli_shared_1.registerPlatform)(p));
|
||||
if (!apply.includes(platform)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if ((0, shared_1.isString)(apply)) {
|
||||
if (!new RegExp(apply).test(platform)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
// 插件必须支持 uvue
|
||||
if (uvue && !config.uvue) {
|
||||
return;
|
||||
}
|
||||
return {
|
||||
id: pkg.name,
|
||||
name: config.name,
|
||||
pluginPath: pkg.pluginPath,
|
||||
config,
|
||||
};
|
||||
}
|
||||
catch (e) { }
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import type { Plugin } from 'vite';
|
||||
/**
|
||||
* TODO 临时重写,解决 @vitejs/plugin-vue 的 Bug
|
||||
*/
|
||||
export declare function rewriteCompilerSfcParse(): void;
|
||||
/**
|
||||
* 已废弃,交由 rewriteExistsSyncHasRootFile 实现,因为新的 vite 版本在 configResolved 中重写已经晚了
|
||||
* 解决 HBuilderX 项目未包含 package.json 时,initTSConfck 可能导致查找过慢,或递归目录时权限不足报错
|
||||
* 即:未包含 package.json 时,直接移除 initTSConfck 相关逻辑
|
||||
* @param inputDir
|
||||
* @returns
|
||||
*/
|
||||
export declare function initFixedEsbuildInitTSConfck(inputDir: string): Plugin[];
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initFixedEsbuildInitTSConfck = exports.rewriteCompilerSfcParse = void 0;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const shared_1 = require("@vue/shared");
|
||||
/**
|
||||
* TODO 临时重写,解决 @vitejs/plugin-vue 的 Bug
|
||||
*/
|
||||
function rewriteCompilerSfcParse() {
|
||||
const compilerSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
|
||||
const { parse } = compilerSfc;
|
||||
let extname_vue = process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.X_EXTNAME_VUE : uni_cli_shared_1.EXTNAME_VUE;
|
||||
compilerSfc.parse = (source, options) => {
|
||||
if (options?.filename) {
|
||||
const extname = path_1.default.extname(options.filename);
|
||||
// wxs、filter、renderjs
|
||||
if (extname && !extname_vue.includes(extname)) {
|
||||
const tag = extname.slice(1);
|
||||
source = `<${tag}>` + source + `</${tag}>`;
|
||||
}
|
||||
}
|
||||
return parse(source, options);
|
||||
};
|
||||
}
|
||||
exports.rewriteCompilerSfcParse = rewriteCompilerSfcParse;
|
||||
/**
|
||||
* 已废弃,交由 rewriteExistsSyncHasRootFile 实现,因为新的 vite 版本在 configResolved 中重写已经晚了
|
||||
* 解决 HBuilderX 项目未包含 package.json 时,initTSConfck 可能导致查找过慢,或递归目录时权限不足报错
|
||||
* 即:未包含 package.json 时,直接移除 initTSConfck 相关逻辑
|
||||
* @param inputDir
|
||||
* @returns
|
||||
*/
|
||||
function initFixedEsbuildInitTSConfck(inputDir) {
|
||||
if (!(0, uni_cli_shared_1.isInHBuilderX)()) {
|
||||
return [];
|
||||
}
|
||||
if (fs_1.default.existsSync(path_1.default.resolve(inputDir, 'package.json'))) {
|
||||
return [];
|
||||
}
|
||||
// 'vite:esbuild', 'vite:esbuild-transpile' initTSConfck
|
||||
const existsSync = fs_1.default.existsSync;
|
||||
// 根目录 lerna.json 路径
|
||||
const lernaJsonPath = (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(inputDir, 'lerna.json'));
|
||||
return [
|
||||
{
|
||||
name: 'uni:fixed-HBuilderX-initTSConfck-before',
|
||||
enforce: 'pre',
|
||||
configResolved() {
|
||||
// 在 HBuilderX 项目中,缺少 package.json 时, 确保 searchForWorkspaceRoot 使用项目根目录, 否则 initTSConfck 会查找很费时,且可能访问目录权限报错
|
||||
// https://github.com/vitejs/vite/blob/43b7b78b1834a4c7128d8a5d987f66a4defcbd93/packages/vite/src/node/plugins/esbuild.ts#L407
|
||||
fs_1.default.existsSync = (p) => {
|
||||
if ((0, shared_1.isString)(p)) {
|
||||
// 访问根目录 lerna.json 时,直接返回 true
|
||||
// https://github.com/vitejs/vite/blob/43b7b78b1834a4c7128d8a5d987f66a4defcbd93/packages/vite/src/node/server/searchRoot.ts#L35
|
||||
if (p.endsWith('lerna.json') &&
|
||||
lernaJsonPath === (0, uni_cli_shared_1.normalizePath)(p)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return existsSync(p);
|
||||
};
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
exports.initFixedEsbuildInitTSConfck = initFixedEsbuildInitTSConfck;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { VitePluginUniResolvedOptions } from '../..';
|
||||
export declare function uniUVuePlugin(options: VitePluginUniResolvedOptions): Plugin;
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.uniUVuePlugin = void 0;
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const define_1 = require("../../config/define");
|
||||
const resolve_1 = require("../../config/resolve");
|
||||
const css_1 = require("../../config/css");
|
||||
const configResolved_1 = require("../../configResolved");
|
||||
function uniUVuePlugin(options) {
|
||||
return {
|
||||
name: 'uni:uvue',
|
||||
config(config, env) {
|
||||
options.command = env.command;
|
||||
let base = config.base;
|
||||
if (!base) {
|
||||
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(options.inputDir);
|
||||
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
|
||||
base = (h5 && h5.router && h5.router.base) || '';
|
||||
}
|
||||
if (!base) {
|
||||
base = '/';
|
||||
}
|
||||
options.base = base;
|
||||
return {
|
||||
base: process.env.UNI_H5_BASE || base,
|
||||
root: process.env.VITE_ROOT_DIR,
|
||||
// TODO 临时设置为__static__,屏蔽警告:https://github.com/vitejs/vite/blob/824d042535033a5c3d7006978c0d05c201cd1c25/packages/vite/src/node/server/middlewares/transform.ts#L125
|
||||
publicDir: config.publicDir || '__static__',
|
||||
define: (0, define_1.createDefine)(options),
|
||||
resolve: (0, resolve_1.createResolve)(options, config),
|
||||
logLevel: config.logLevel || 'warn', // 默认使用 warn 等级,因为 info 等级vite:report 会输出文件列表等信息
|
||||
optimizeDeps: {
|
||||
noDiscovery: true,
|
||||
include: [],
|
||||
},
|
||||
css: (0, css_1.createCss)(options, config),
|
||||
};
|
||||
},
|
||||
configResolved(config) {
|
||||
(0, configResolved_1.initLogger)(config);
|
||||
},
|
||||
};
|
||||
}
|
||||
exports.uniUVuePlugin = uniUVuePlugin;
|
||||
+1
@@ -0,0 +1 @@
|
||||
export * from './options';
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
__exportStar(require("./options"), exports);
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import type { TemplateCompiler } from '@vue/compiler-sfc';
|
||||
import type { Options as VueOptions } from '@vitejs/plugin-vue';
|
||||
import { type UniVitePlugin } from '@dcloudio/uni-cli-shared';
|
||||
import type { ViteLegacyOptions, VitePluginUniResolvedOptions } from '..';
|
||||
/**
|
||||
* 每次创建新的 plugin-vue 实例。因为该插件内部会 cache descriptor,而相同的vue文件在编译到vue页面和nvue页面时,不能共享缓存(条件编译,css scoped等均不同)
|
||||
* @returns
|
||||
*/
|
||||
export declare function createPluginVueInstance(options: VueOptions): Plugin<any>;
|
||||
export declare function initPluginVueOptions(options: VitePluginUniResolvedOptions, UniVitePlugins: UniVitePlugin[], uniPluginOptions: Required<Omit<Required<UniVitePlugin>['uni'], 'compiler'>> & {
|
||||
compiler?: TemplateCompiler;
|
||||
}): VueOptions;
|
||||
export declare function initPluginVueJsxOptions(options: VitePluginUniResolvedOptions, { isCustomElement, }: Required<Required<UniVitePlugin>['uni']>['compilerOptions'], jsxOptions: Required<Required<UniVitePlugin>['uni']>['jsxOptions']): import("@vue/babel-plugin-jsx").VueJSXPluginOptions & {
|
||||
babelPlugins?: any[] | undefined;
|
||||
};
|
||||
export declare function initPluginViteLegacyOptions(options: VitePluginUniResolvedOptions): ViteLegacyOptions;
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.initPluginViteLegacyOptions = exports.initPluginVueJsxOptions = exports.initPluginVueOptions = exports.createPluginVueInstance = void 0;
|
||||
const fs_extra_1 = __importDefault(require("fs-extra"));
|
||||
const shared_1 = require("@vue/shared");
|
||||
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
|
||||
const utils_1 = require("../utils");
|
||||
const uni_cli_shared_2 = require("@dcloudio/uni-cli-shared");
|
||||
const pluginVuePath = require.resolve('@vitejs/plugin-vue');
|
||||
const normalizedPluginVuePath = (0, uni_cli_shared_1.normalizePath)(pluginVuePath);
|
||||
/**
|
||||
* 每次创建新的 plugin-vue 实例。因为该插件内部会 cache descriptor,而相同的vue文件在编译到vue页面和nvue页面时,不能共享缓存(条件编译,css scoped等均不同)
|
||||
* @returns
|
||||
*/
|
||||
function createPluginVueInstance(options) {
|
||||
delete require.cache[pluginVuePath];
|
||||
delete require.cache[normalizedPluginVuePath];
|
||||
const vuePlugin = require('@vitejs/plugin-vue');
|
||||
const vuePluginInstance = vuePlugin(options);
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
// 删除 buildEnd 逻辑,因为里边清理了缓存,导致 watch 模式失效 https://github.com/vitejs/vite-plugin-vue/commit/96dbb220ff210d2f7391f43a807bcd8cfb0da776
|
||||
delete vuePluginInstance.buildEnd;
|
||||
}
|
||||
return vuePluginInstance;
|
||||
}
|
||||
exports.createPluginVueInstance = createPluginVueInstance;
|
||||
function initPluginVueOptions(options, UniVitePlugins, uniPluginOptions) {
|
||||
const vueOptions = options.vueOptions || (options.vueOptions = {});
|
||||
// if (!hasOwn(vueOptions, 'reactivityTransform')) {
|
||||
// vueOptions.reactivityTransform = true
|
||||
// }
|
||||
if (!vueOptions.include) {
|
||||
vueOptions.include = [];
|
||||
}
|
||||
if (!(0, shared_1.isArray)(vueOptions.include)) {
|
||||
vueOptions.include = [vueOptions.include];
|
||||
}
|
||||
vueOptions.include.push(uni_cli_shared_1.EXTNAME_VUE_RE);
|
||||
const styleOptions = vueOptions.style || (vueOptions.style = {});
|
||||
if (!styleOptions.postcssPlugins) {
|
||||
styleOptions.postcssPlugins = [];
|
||||
}
|
||||
// 解析 scoped 中 deep 等特殊语法
|
||||
styleOptions.postcssPlugins.push((0, uni_cli_shared_1.uniPostcssScopedPlugin)());
|
||||
const templateOptions = vueOptions.template || (vueOptions.template = {});
|
||||
const compilerOptions = templateOptions.compilerOptions || (templateOptions.compilerOptions = {});
|
||||
compilerOptions.isX = process.env.UNI_APP_X === 'true';
|
||||
const { compiler, styleOptions: { postcssPlugins }, compilerOptions: { miniProgram, isNativeTag, isVoidTag, isCustomElement, nodeTransforms, directiveTransforms, whitespace, }, } = uniPluginOptions;
|
||||
if (postcssPlugins) {
|
||||
styleOptions.postcssPlugins.push(...postcssPlugins);
|
||||
}
|
||||
if (compiler) {
|
||||
templateOptions.compiler = compiler;
|
||||
}
|
||||
if (miniProgram) {
|
||||
;
|
||||
compilerOptions.miniProgram = miniProgram;
|
||||
}
|
||||
if (isNativeTag) {
|
||||
const userIsNativeTag = compilerOptions.isNativeTag;
|
||||
compilerOptions.isNativeTag = (tag) => {
|
||||
if (isNativeTag(tag)) {
|
||||
return true;
|
||||
}
|
||||
if (userIsNativeTag && userIsNativeTag(tag)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
if (isVoidTag) {
|
||||
const userIsVoidTag = compilerOptions.isVoidTag;
|
||||
compilerOptions.isVoidTag = (tag) => {
|
||||
if (isVoidTag(tag)) {
|
||||
return true;
|
||||
}
|
||||
if (userIsVoidTag && userIsVoidTag(tag)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
if (whitespace) {
|
||||
compilerOptions.whitespace = whitespace;
|
||||
}
|
||||
if (isCustomElement) {
|
||||
const userIsCustomElement = compilerOptions.isCustomElement;
|
||||
compilerOptions.isCustomElement = (tag) => {
|
||||
if (isCustomElement(tag)) {
|
||||
return true;
|
||||
}
|
||||
if (userIsCustomElement && userIsCustomElement(tag)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
compilerOptions.directiveTransforms = {
|
||||
...compilerOptions.directiveTransforms,
|
||||
...directiveTransforms,
|
||||
};
|
||||
if (!compilerOptions.nodeTransforms) {
|
||||
compilerOptions.nodeTransforms = [];
|
||||
}
|
||||
// 合并 transformAssetUrls
|
||||
// 内置配置
|
||||
const builtInTransformAssetUrls = (0, uni_cli_shared_1.createUniVueTransformAssetUrls)((0, uni_cli_shared_1.isExternalUrl)(options.base) ? options.base : '');
|
||||
// 用户传递配置 eg: transformAssetUrls.tags = {'my-image': ['src']}
|
||||
// docs: https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue
|
||||
const userOptionsTransformAssetUrls = templateOptions.transformAssetUrls;
|
||||
templateOptions.transformAssetUrls = builtInTransformAssetUrls;
|
||||
if (typeof userOptionsTransformAssetUrls !== 'boolean' &&
|
||||
!!userOptionsTransformAssetUrls?.tags &&
|
||||
!Array.isArray(userOptionsTransformAssetUrls.tags)) {
|
||||
templateOptions.transformAssetUrls = {
|
||||
...builtInTransformAssetUrls,
|
||||
...userOptionsTransformAssetUrls,
|
||||
tags: {
|
||||
...builtInTransformAssetUrls.tags,
|
||||
...userOptionsTransformAssetUrls.tags,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (options.platform !== 'h5' && options.platform !== 'web') {
|
||||
compilerOptions.nodeTransforms.push(...(0, uni_cli_shared_1.getBaseNodeTransforms)(options.base));
|
||||
}
|
||||
if (nodeTransforms) {
|
||||
compilerOptions.nodeTransforms.push(...nodeTransforms);
|
||||
}
|
||||
// const compatConfig = parseCompatConfigOnce(options.inputDir)
|
||||
// compilerOptions.compatConfig = extend(
|
||||
// compilerOptions.compatConfig || {},
|
||||
// compatConfig
|
||||
// )
|
||||
// App,MP 平台不支持使用静态节点
|
||||
compilerOptions.hoistStatic = false;
|
||||
compilerOptions.root = process.env.UNI_INPUT_DIR;
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
// app-nvue | app-uvue 需要启用 customElement 机制来内联 styles
|
||||
if (process.env.UNI_COMPILER === 'nvue' ||
|
||||
(isX && (options.platform === 'app' || options.platform === 'app-harmony'))) {
|
||||
vueOptions.customElement = true;
|
||||
if (process.env.UNI_RENDERER_NATIVE !== 'appService' || isX) {
|
||||
// nvue 需要使用自己的 compiler,来移除 scoped
|
||||
vueOptions.compiler = (0, utils_1.createNVueCompiler)();
|
||||
}
|
||||
}
|
||||
if (!vueOptions.script) {
|
||||
vueOptions.script = {};
|
||||
}
|
||||
// TODO 目前暂不支持通过@/开头引入文件,因为需要tsconfig.json配置,建议使用相对路径
|
||||
// https://github.com/vuejs/core/blob/main/packages/compiler-sfc/src/script/resolveType.ts#L911
|
||||
require('@vue/compiler-sfc').registerTS(() => {
|
||||
if (isX) {
|
||||
return (0, uni_cli_shared_2.resolveUniTypeScript)();
|
||||
}
|
||||
return require('typescript');
|
||||
});
|
||||
if (!vueOptions.script.fs) {
|
||||
function resolveFile(file) {
|
||||
if (file.startsWith('@/')) {
|
||||
file = file.replace('@/', (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR));
|
||||
}
|
||||
return file;
|
||||
}
|
||||
vueOptions.script.fs = {
|
||||
fileExists(file) {
|
||||
return fs_extra_1.default.existsSync(resolveFile(file));
|
||||
},
|
||||
readFile(file) {
|
||||
const filename = resolveFile(file);
|
||||
// 需要走条件编译
|
||||
return (0, uni_cli_shared_1.preJs)(fs_extra_1.default.readFileSync(filename, 'utf-8'), filename);
|
||||
},
|
||||
realpath(file) {
|
||||
return resolveFile(file);
|
||||
},
|
||||
};
|
||||
}
|
||||
if (isX) {
|
||||
if (!vueOptions.script) {
|
||||
vueOptions.script = {
|
||||
babelParserPlugins: [],
|
||||
};
|
||||
}
|
||||
if (!vueOptions.script.babelParserPlugins) {
|
||||
vueOptions.script.babelParserPlugins = [];
|
||||
}
|
||||
if (!vueOptions.script.babelParserPlugins.includes('typescript')) {
|
||||
vueOptions.script.babelParserPlugins.push('typescript');
|
||||
}
|
||||
// decorators or decorators-legacy
|
||||
if (!vueOptions.script.babelParserPlugins.includes('decorators')) {
|
||||
vueOptions.script.babelParserPlugins.push('decorators');
|
||||
}
|
||||
}
|
||||
return vueOptions;
|
||||
}
|
||||
exports.initPluginVueOptions = initPluginVueOptions;
|
||||
function initPluginVueJsxOptions(options, { isCustomElement, }, jsxOptions) {
|
||||
const vueJsxOptions = (0, shared_1.isPlainObject)(options.vueJsxOptions)
|
||||
? options.vueJsxOptions
|
||||
: (options.vueJsxOptions = {});
|
||||
if (!(0, shared_1.hasOwn)(vueJsxOptions, 'optimize')) {
|
||||
vueJsxOptions.optimize = true;
|
||||
}
|
||||
vueJsxOptions.isCustomElement = isCustomElement;
|
||||
if (!vueJsxOptions.babelPlugins) {
|
||||
vueJsxOptions.babelPlugins = [];
|
||||
}
|
||||
if ((0, shared_1.isArray)(jsxOptions.babelPlugins)) {
|
||||
vueJsxOptions.babelPlugins.push(...jsxOptions.babelPlugins);
|
||||
}
|
||||
return vueJsxOptions;
|
||||
}
|
||||
exports.initPluginVueJsxOptions = initPluginVueJsxOptions;
|
||||
function initPluginViteLegacyOptions(options) {
|
||||
const viteLegacyOptions = options.viteLegacyOptions || (options.viteLegacyOptions = {});
|
||||
return viteLegacyOptions;
|
||||
}
|
||||
exports.initPluginViteLegacyOptions = initPluginViteLegacyOptions;
|
||||
+1
@@ -0,0 +1 @@
|
||||
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Generated
Vendored
+476
@@ -0,0 +1,476 @@
|
||||
# unplugin-auto-import
|
||||
|
||||
[](https://www.npmjs.com/package/unplugin-auto-import)
|
||||
|
||||
Auto import APIs on-demand for Vite, Webpack, Rspack, Rollup and esbuild. With TypeScript support. Powered by [unplugin](https://github.com/unjs/unplugin).
|
||||
|
||||
---
|
||||
|
||||
without
|
||||
|
||||
```ts
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const count = ref(0)
|
||||
const doubled = computed(() => count.value * 2)
|
||||
```
|
||||
|
||||
with
|
||||
|
||||
```ts
|
||||
const count = ref(0)
|
||||
const doubled = computed(() => count.value * 2)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
without
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react'
|
||||
|
||||
export function Counter() {
|
||||
const [count, setCount] = useState(0)
|
||||
return <div>{ count }</div>
|
||||
}
|
||||
```
|
||||
|
||||
with
|
||||
|
||||
```tsx
|
||||
export function Counter() {
|
||||
const [count, setCount] = useState(0)
|
||||
return <div>{ count }</div>
|
||||
}
|
||||
```
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm i -D unplugin-auto-import
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Vite</summary><br>
|
||||
|
||||
```ts
|
||||
// vite.config.ts
|
||||
import AutoImport from 'unplugin-auto-import/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
AutoImport({ /* options */ }),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
Example: [`playground/`](./playground/)
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Rollup</summary><br>
|
||||
|
||||
```ts
|
||||
// rollup.config.js
|
||||
import AutoImport from 'unplugin-auto-import/rollup'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
AutoImport({ /* options */ }),
|
||||
// other plugins
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Webpack</summary><br>
|
||||
|
||||
```ts
|
||||
// webpack.config.js
|
||||
module.exports = {
|
||||
/* ... */
|
||||
plugins: [
|
||||
require('unplugin-auto-import/webpack').default({ /* options */ }),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Rspack</summary><br>
|
||||
|
||||
```ts
|
||||
// rspack.config.js
|
||||
module.exports = {
|
||||
/* ... */
|
||||
plugins: [
|
||||
require('unplugin-auto-import/rspack').default({ /* options */ }),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Nuxt</summary><br>
|
||||
|
||||
> You **don't need** this plugin for Nuxt, it's already built-in.
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Vue CLI</summary><br>
|
||||
|
||||
```ts
|
||||
// vue.config.js
|
||||
module.exports = {
|
||||
/* ... */
|
||||
plugins: [
|
||||
require('unplugin-auto-import/webpack').default({ /* options */ }),
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
You can also rename the Vue configuration file to `vue.config.mjs` and use static import syntax (you should use latest `@vue/cli-service ^5.0.8`):
|
||||
```ts
|
||||
// vue.config.mjs
|
||||
import AutoImport from 'unplugin-auto-import/webpack'
|
||||
|
||||
export default {
|
||||
configureWebpack: {
|
||||
plugins: [
|
||||
AutoImport({ /* options */ }),
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Quasar</summary><br>
|
||||
|
||||
```ts
|
||||
// vite.config.js [Vite]
|
||||
import AutoImport from 'unplugin-auto-import/vite'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
AutoImport({ /* options */ })
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
```ts
|
||||
// quasar.conf.js [Webpack]
|
||||
const AutoImportPlugin = require('unplugin-auto-import/webpack').default
|
||||
|
||||
module.exports = {
|
||||
build: {
|
||||
chainWebpack(chain) {
|
||||
chain.plugin('unplugin-auto-import').use(
|
||||
AutoImportPlugin({ /* options */ }),
|
||||
)
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>esbuild</summary><br>
|
||||
|
||||
```ts
|
||||
// esbuild.config.js
|
||||
import { build } from 'esbuild'
|
||||
import AutoImport from 'unplugin-auto-import/esbuild'
|
||||
|
||||
build({
|
||||
/* ... */
|
||||
plugins: [
|
||||
AutoImport({
|
||||
/* options */
|
||||
}),
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
<details>
|
||||
<summary>Astro</summary><br>
|
||||
|
||||
```ts
|
||||
// astro.config.mjs
|
||||
import AutoImport from 'unplugin-auto-import/astro'
|
||||
|
||||
export default defineConfig({
|
||||
integrations: [
|
||||
AutoImport({
|
||||
/* options */
|
||||
})
|
||||
],
|
||||
})
|
||||
```
|
||||
|
||||
<br></details>
|
||||
|
||||
## Configuration
|
||||
|
||||
```ts
|
||||
AutoImport({
|
||||
// targets to transform
|
||||
include: [
|
||||
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
|
||||
/\.vue$/,
|
||||
/\.vue\?vue/, // .vue
|
||||
/\.md$/, // .md
|
||||
],
|
||||
|
||||
// global imports to register
|
||||
imports: [
|
||||
// presets
|
||||
'vue',
|
||||
'vue-router',
|
||||
// custom
|
||||
{
|
||||
'@vueuse/core': [
|
||||
// named imports
|
||||
'useMouse', // import { useMouse } from '@vueuse/core',
|
||||
// alias
|
||||
['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
|
||||
],
|
||||
'axios': [
|
||||
// default imports
|
||||
['default', 'axios'], // import { default as axios } from 'axios',
|
||||
],
|
||||
'[package-name]': [
|
||||
'[import-names]',
|
||||
// alias
|
||||
['[from]', '[alias]'],
|
||||
],
|
||||
},
|
||||
// example type import
|
||||
{
|
||||
from: 'vue-router',
|
||||
imports: ['RouteLocationRaw'],
|
||||
type: true,
|
||||
},
|
||||
],
|
||||
|
||||
// Array of strings of regexes that contains imports meant to be filtered out.
|
||||
ignore: [
|
||||
'useMouse',
|
||||
'useFetch'
|
||||
],
|
||||
|
||||
// Enable auto import by filename for default module exports under directories
|
||||
defaultExportByFilename: false,
|
||||
|
||||
// Options for scanning directories for auto import
|
||||
dirsScanOptions: {
|
||||
types: true // Enable auto import the types under the directories
|
||||
},
|
||||
|
||||
// Auto import for module exports under directories
|
||||
// by default it only scan one level of modules under the directory
|
||||
dirs: [
|
||||
'./hooks',
|
||||
'./composables', // only root modules
|
||||
'./composables/**', // all nested modules
|
||||
// ...
|
||||
|
||||
{
|
||||
glob: './hooks',
|
||||
types: true // enable import the types
|
||||
},
|
||||
{
|
||||
glob: './composables',
|
||||
types: false // If top level dirsScanOptions.types importing enabled, just only disable this directory
|
||||
}
|
||||
// ...
|
||||
],
|
||||
|
||||
// Filepath to generate corresponding .d.ts file.
|
||||
// Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
|
||||
// Set `false` to disable.
|
||||
dts: './auto-imports.d.ts',
|
||||
|
||||
// Array of strings of regexes that contains imports meant to be ignored during
|
||||
// the declaration file generation. You may find this useful when you need to provide
|
||||
// a custom signature for a function.
|
||||
ignoreDts: [
|
||||
'ignoredFunction',
|
||||
/^ignore_/
|
||||
],
|
||||
|
||||
// Auto import inside Vue template
|
||||
// see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
|
||||
vueTemplate: false,
|
||||
|
||||
// Auto import directives inside Vue template
|
||||
// see https://github.com/unjs/unimport/pull/374
|
||||
vueDirectives: undefined,
|
||||
|
||||
// Custom resolvers, compatible with `unplugin-vue-components`
|
||||
// see https://github.com/antfu/unplugin-auto-import/pull/23/
|
||||
resolvers: [
|
||||
/* ... */
|
||||
],
|
||||
|
||||
// Include auto-imported packages in Vite's `optimizeDeps` options
|
||||
// Recommend to enable
|
||||
viteOptimizeDeps: true,
|
||||
|
||||
// Inject the imports at the end of other imports
|
||||
injectAtEnd: true,
|
||||
|
||||
// Generate corresponding .eslintrc-auto-import.json file.
|
||||
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
|
||||
eslintrc: {
|
||||
enabled: false, // Default `false`
|
||||
// provide path ending with `.mjs` or `.cjs` to generate the file with the respective format
|
||||
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
|
||||
globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
|
||||
},
|
||||
|
||||
// Generate corresponding .biomelintrc-auto-import.json file.
|
||||
// biomejs extends Docs - https://biomejs.dev/guides/how-biome-works/#the-extends-option
|
||||
biomelintrc: {
|
||||
enabled: false, // Default `false`
|
||||
filepath: './.biomelintrc-auto-import.json', // Default `./.biomelintrc-auto-import.json`
|
||||
},
|
||||
|
||||
// Save unimport items into a JSON file for other tools to consume
|
||||
dumpUnimportItems: './auto-imports.json', // Default `false`
|
||||
})
|
||||
```
|
||||
|
||||
Refer to the [type definitions](./src/types.ts) for more options.
|
||||
|
||||
## Presets
|
||||
|
||||
See [src/presets](./src/presets).
|
||||
|
||||
## Package Presets
|
||||
|
||||
We only provide presets for the most popular packages, to use any package not included here you can install it as dev dependency and add it to the `packagePresets` array option:
|
||||
```ts
|
||||
AutoImport({
|
||||
/* other options */
|
||||
packagePresets: ['detect-browser-es'/* other local package names */]
|
||||
})
|
||||
```
|
||||
|
||||
You can check the [Svelte example](./examples/vite-svelte) for a working example registering `detect-browser-es` package preset and auto importing `detect` function in [App.svelte](./examples/vite-svelte/src/App.svelte).
|
||||
|
||||
Please refer to the [unimport PackagePresets jsdocs](https://github.com/unjs/unimport/blob/main/src/types.ts) for more information about options like `ignore` or `cache`.
|
||||
|
||||
**Note**: ensure local packages used have package exports configured properly, otherwise the corresponding modules exports will not be detected.
|
||||
|
||||
## TypeScript
|
||||
|
||||
In order to properly hint types for auto-imported APIs
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="400px" valign="top">
|
||||
|
||||
1. Enable `options.dts` so that `auto-imports.d.ts` file is automatically generated
|
||||
2. Make sure `auto-imports.d.ts` is not excluded in `tsconfig.json`
|
||||
|
||||
</td>
|
||||
<td width="600px"><br>
|
||||
|
||||
```ts
|
||||
AutoImport({
|
||||
dts: true // or a custom path
|
||||
})
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## ESLint
|
||||
|
||||
> 💡 When using TypeScript, we recommend to **disable** `no-undef` rule directly as TypeScript already check for them and you don't need to worry about this.
|
||||
|
||||
If you have encountered ESLint error of `no-undef`:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="400px">
|
||||
|
||||
1. Enable `eslintrc.enabled`
|
||||
|
||||
</td>
|
||||
<td width="600px"><br>
|
||||
|
||||
```ts
|
||||
AutoImport({
|
||||
eslintrc: {
|
||||
enabled: true, // <-- this
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
</td></tr></table>
|
||||
<table><tr><td width="400px">
|
||||
|
||||
2. Update your `eslintrc`:
|
||||
[Extending Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files)
|
||||
|
||||
</td>
|
||||
<td width="600px"><br>
|
||||
|
||||
```ts
|
||||
// .eslintrc.js
|
||||
module.exports = {
|
||||
extends: [
|
||||
'./.eslintrc-auto-import.json',
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## FAQ
|
||||
|
||||
### Compare to [`unimport`](https://github.com/unjs/unimport)
|
||||
|
||||
From v0.8.0, `unplugin-auto-import` **uses** `unimport` underneath. `unimport` is designed to be a lower-level tool (it also powered Nuxt's auto import). You can think `unplugin-auto-import` is a wrapper of it that provides more user-friendly config APIs and capabilities like resolvers. Development of new features will mostly happen in `unimport` from now.
|
||||
|
||||
### Compare to [`vue-global-api`](https://github.com/antfu/vue-global-api)
|
||||
|
||||
You can think of this plugin as a successor to `vue-global-api`, but offering much more flexibility and bindings with libraries other than Vue (e.g. React).
|
||||
|
||||
###### Pros
|
||||
|
||||
- Flexible and customizable
|
||||
- Tree-shakable (on-demand transforming)
|
||||
- No global population
|
||||
|
||||
###### Cons
|
||||
|
||||
- Relying on build tools integrations (while `vue-global-api` is pure runtime) - but hey, we have supported quite a few of them already!
|
||||
|
||||
## Sponsors
|
||||
|
||||
<p align="center">
|
||||
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
|
||||
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## License
|
||||
|
||||
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
|
||||
Generated
Vendored
+179
@@ -0,0 +1,179 @@
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
export {}
|
||||
declare global {
|
||||
const $: typeof import('vue/macros')['$']
|
||||
const $$: typeof import('vue/macros')['$$']
|
||||
const $computed: typeof import('vue/macros')['$computed']
|
||||
const $customRef: typeof import('vue/macros')['$customRef']
|
||||
const $ref: typeof import('vue/macros')['$ref']
|
||||
const $shallowRef: typeof import('vue/macros')['$shallowRef']
|
||||
const $toRef: typeof import('vue/macros')['$toRef']
|
||||
const EffectScope: typeof import('vue')['EffectScope']
|
||||
const THREE: typeof import('three.js')
|
||||
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
|
||||
const afterAll: typeof import('vitest')['afterAll']
|
||||
const afterEach: typeof import('vitest')['afterEach']
|
||||
const afterUpdate: typeof import('svelte')['afterUpdate']
|
||||
const assert: typeof import('vitest')['assert']
|
||||
const backIn: typeof import('svelte/easing')['backIn']
|
||||
const backInOut: typeof import('svelte/easing')['backInOut']
|
||||
const backOut: typeof import('svelte/easing')['backOut']
|
||||
const beforeAll: typeof import('vitest')['beforeAll']
|
||||
const beforeEach: typeof import('vitest')['beforeEach']
|
||||
const beforeUpdate: typeof import('svelte')['beforeUpdate']
|
||||
const blur: typeof import('svelte/transition')['blur']
|
||||
const bounceIn: typeof import('svelte/easing')['bounceIn']
|
||||
const bounceInOut: typeof import('svelte/easing')['bounceInOut']
|
||||
const bounceOut: typeof import('svelte/easing')['bounceOut']
|
||||
const chai: typeof import('vitest')['chai']
|
||||
const circIn: typeof import('svelte/easing')['circIn']
|
||||
const circInOut: typeof import('svelte/easing')['circInOut']
|
||||
const circOut: typeof import('svelte/easing')['circOut']
|
||||
const computed: typeof import('vue')['computed']
|
||||
const createApp: typeof import('vue')['createApp']
|
||||
const createEventDispatcher: typeof import('svelte')['createEventDispatcher']
|
||||
const createPinia: typeof import('pinia')['createPinia']
|
||||
const createRef: typeof import('react')['createRef']
|
||||
const crossfade: typeof import('svelte/transition')['crossfade']
|
||||
const cubicIn: typeof import('svelte/easing')['cubicIn']
|
||||
const cubicInOut: typeof import('svelte/easing')['cubicInOut']
|
||||
const cubicOut: typeof import('svelte/easing')['cubicOut']
|
||||
const customDefault: typeof import('custom')['default']
|
||||
const customDefaultAlias: typeof import('custom')['default']
|
||||
const customNamed: typeof import('custom')['customNamed']
|
||||
const customRef: typeof import('vue')['customRef']
|
||||
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
|
||||
const defineComponent: typeof import('vue')['defineComponent']
|
||||
const defineStore: typeof import('pinia')['defineStore']
|
||||
const derived: typeof import('svelte/store')['derived']
|
||||
const describe: typeof import('vitest')['describe']
|
||||
const draw: typeof import('svelte/transition')['draw']
|
||||
const effectScope: typeof import('vue')['effectScope']
|
||||
const elasticIn: typeof import('svelte/easing')['elasticIn']
|
||||
const elasticInOut: typeof import('svelte/easing')['elasticInOut']
|
||||
const elasticOut: typeof import('svelte/easing')['elasticOut']
|
||||
const expect: typeof import('vitest')['expect']
|
||||
const expoIn: typeof import('svelte/easing')['expoIn']
|
||||
const expoInOut: typeof import('svelte/easing')['expoInOut']
|
||||
const expoOut: typeof import('svelte/easing')['expoOut']
|
||||
const fade: typeof import('svelte/transition')['fade']
|
||||
const flip: typeof import('svelte/animate')['flip']
|
||||
const fly: typeof import('svelte/transition')['fly']
|
||||
const forwardRef: typeof import('react')['forwardRef']
|
||||
const get: typeof import('svelte/store')['get']
|
||||
const getActivePinia: typeof import('pinia')['getActivePinia']
|
||||
const getAllContexts: typeof import('svelte')['getAllContexts']
|
||||
const getContext: typeof import('svelte')['getContext']
|
||||
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
|
||||
const getCurrentScope: typeof import('vue')['getCurrentScope']
|
||||
const h: typeof import('vue')['h']
|
||||
const hasContext: typeof import('svelte')['hasContext']
|
||||
const inject: typeof import('vue')['inject']
|
||||
const isProxy: typeof import('vue')['isProxy']
|
||||
const isReactive: typeof import('vue')['isReactive']
|
||||
const isReadonly: typeof import('vue')['isReadonly']
|
||||
const isRef: typeof import('vue')['isRef']
|
||||
const it: typeof import('vitest')['it']
|
||||
const lazy: typeof import('react')['lazy']
|
||||
const linear: typeof import('svelte/easing')['linear']
|
||||
const mapActions: typeof import('pinia')['mapActions']
|
||||
const mapGetters: typeof import('pinia')['mapGetters']
|
||||
const mapState: typeof import('pinia')['mapState']
|
||||
const mapStores: typeof import('pinia')['mapStores']
|
||||
const mapWritableState: typeof import('pinia')['mapWritableState']
|
||||
const markRaw: typeof import('vue')['markRaw']
|
||||
const memo: typeof import('react')['memo']
|
||||
const nextTick: typeof import('vue')['nextTick']
|
||||
const onActivated: typeof import('vue')['onActivated']
|
||||
const onBeforeMount: typeof import('vue')['onBeforeMount']
|
||||
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
|
||||
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
|
||||
const onDeactivated: typeof import('vue')['onDeactivated']
|
||||
const onDestroy: typeof import('svelte')['onDestroy']
|
||||
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
|
||||
const onMount: typeof import('svelte')['onMount']
|
||||
const onMounted: typeof import('vue')['onMounted']
|
||||
const onRenderTracked: typeof import('vue')['onRenderTracked']
|
||||
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
|
||||
const onScopeDispose: typeof import('vue')['onScopeDispose']
|
||||
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
|
||||
const onUnmounted: typeof import('vue')['onUnmounted']
|
||||
const onUpdated: typeof import('vue')['onUpdated']
|
||||
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
|
||||
const provide: typeof import('vue')['provide']
|
||||
const quadIn: typeof import('svelte/easing')['quadIn']
|
||||
const quadInOut: typeof import('svelte/easing')['quadInOut']
|
||||
const quadOut: typeof import('svelte/easing')['quadOut']
|
||||
const quartIn: typeof import('svelte/easing')['quartIn']
|
||||
const quartInOut: typeof import('svelte/easing')['quartInOut']
|
||||
const quartOut: typeof import('svelte/easing')['quartOut']
|
||||
const quintIn: typeof import('svelte/easing')['quintIn']
|
||||
const quintInOut: typeof import('svelte/easing')['quintInOut']
|
||||
const quintOut: typeof import('svelte/easing')['quintOut']
|
||||
const reactive: typeof import('vue')['reactive']
|
||||
const readable: typeof import('svelte/store')['readable']
|
||||
const readonly: typeof import('vue')['readonly']
|
||||
const ref: typeof import('vue')['ref']
|
||||
const resolveComponent: typeof import('vue')['resolveComponent']
|
||||
const scale: typeof import('svelte/transition')['scale']
|
||||
const setActivePinia: typeof import('pinia')['setActivePinia']
|
||||
const setContext: typeof import('svelte')['setContext']
|
||||
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
|
||||
const shallowReactive: typeof import('vue')['shallowReactive']
|
||||
const shallowReadonly: typeof import('vue')['shallowReadonly']
|
||||
const shallowRef: typeof import('vue')['shallowRef']
|
||||
const sineIn: typeof import('svelte/easing')['sineIn']
|
||||
const sineInOut: typeof import('svelte/easing')['sineInOut']
|
||||
const sineOut: typeof import('svelte/easing')['sineOut']
|
||||
const slide: typeof import('svelte/transition')['slide']
|
||||
const spring: typeof import('svelte/motion')['spring']
|
||||
const startTransition: typeof import('react')['startTransition']
|
||||
const storeToRefs: typeof import('pinia')['storeToRefs']
|
||||
const suite: typeof import('vitest')['suite']
|
||||
const test: typeof import('vitest')['test']
|
||||
const tick: typeof import('svelte')['tick']
|
||||
const toRaw: typeof import('vue')['toRaw']
|
||||
const toRef: typeof import('vue')['toRef']
|
||||
const toRefs: typeof import('vue')['toRefs']
|
||||
const toValue: typeof import('vue')['toValue']
|
||||
const triggerRef: typeof import('vue')['triggerRef']
|
||||
const tweened: typeof import('svelte/motion')['tweened']
|
||||
const unref: typeof import('vue')['unref']
|
||||
const useAttrs: typeof import('vue')['useAttrs']
|
||||
const useCallback: typeof import('react')['useCallback']
|
||||
const useContext: typeof import('react')['useContext']
|
||||
const useCssModule: typeof import('vue')['useCssModule']
|
||||
const useCssVars: typeof import('vue')['useCssVars']
|
||||
const useDebugValue: typeof import('react')['useDebugValue']
|
||||
const useDeferredValue: typeof import('react')['useDeferredValue']
|
||||
const useDialogPluginComponent: typeof import('quasar')['useDialogPluginComponent']
|
||||
const useEffect: typeof import('react')['useEffect']
|
||||
const useFormChild: typeof import('quasar')['useFormChild']
|
||||
const useId: typeof import('react')['useId']
|
||||
const useImperativeHandle: typeof import('react')['useImperativeHandle']
|
||||
const useInsertionEffect: typeof import('react')['useInsertionEffect']
|
||||
const useLayoutEffect: typeof import('react')['useLayoutEffect']
|
||||
const useMemo: typeof import('react')['useMemo']
|
||||
const useMeta: typeof import('quasar')['useMeta']
|
||||
const useModel: typeof import('vue')['useModel']
|
||||
const useQuasar: typeof import('quasar')['useQuasar']
|
||||
const useReducer: typeof import('react')['useReducer']
|
||||
const useRef: typeof import('react')['useRef']
|
||||
const useSlots: typeof import('vue')['useSlots']
|
||||
const useState: typeof import('react')['useState']
|
||||
const useSyncExternalStore: typeof import('react')['useSyncExternalStore']
|
||||
const useTemplateRef: typeof import('vue')['useTemplateRef']
|
||||
const useTransition: typeof import('react')['useTransition']
|
||||
const vi: typeof import('vitest')['vi']
|
||||
const vitest: typeof import('vitest')['vitest']
|
||||
const watch: typeof import('vue')['watch']
|
||||
const watchEffect: typeof import('vue')['watchEffect']
|
||||
const watchPostEffect: typeof import('vue')['watchPostEffect']
|
||||
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
|
||||
const writable: typeof import('svelte/store')['writable']
|
||||
}
|
||||
TongjiUniApp/node_modules/@dcloudio/vite-plugin-uni/node_modules/unplugin-auto-import/dist/astro.cjs
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
||||
|
||||
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
|
||||
require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
// src/astro.ts
|
||||
function astro_default(options) {
|
||||
return {
|
||||
name: "unplugin-auto-import",
|
||||
hooks: {
|
||||
"astro:config:setup": async (astro) => {
|
||||
var _a;
|
||||
(_a = astro.config.vite).plugins || (_a.plugins = []);
|
||||
astro.config.vite.plugins.push(_chunkA6NGEVNDcjs.unplugin_default.vite(options));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
exports.default = astro_default;
|
||||
Generated
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
import { Options } from './types.cjs';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare function export_default(options: Options): {
|
||||
name: string;
|
||||
hooks: {
|
||||
'astro:config:setup': (astro: any) => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
export { export_default as default };
|
||||
Generated
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
import { Options } from './types.js';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare function export_default(options: Options): {
|
||||
name: string;
|
||||
hooks: {
|
||||
'astro:config:setup': (astro: any) => Promise<void>;
|
||||
};
|
||||
};
|
||||
|
||||
export { export_default as default };
|
||||
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
import {
|
||||
unplugin_default
|
||||
} from "./chunk-WD3TZPPT.js";
|
||||
import "./chunk-DTT25XJ5.js";
|
||||
|
||||
// src/astro.ts
|
||||
function astro_default(options) {
|
||||
return {
|
||||
name: "unplugin-auto-import",
|
||||
hooks: {
|
||||
"astro:config:setup": async (astro) => {
|
||||
var _a;
|
||||
(_a = astro.config.vite).plugins || (_a.plugins = []);
|
||||
astro.config.vite.plugins.push(unplugin_default.vite(options));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
export {
|
||||
astro_default as default
|
||||
};
|
||||
Generated
Vendored
+608
@@ -0,0 +1,608 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/presets/index.ts
|
||||
var _unimport = require('unimport');
|
||||
|
||||
// src/presets/ahooks.ts
|
||||
var _fs = require('fs');
|
||||
var _localpkg = require('local-pkg');
|
||||
var _cache;
|
||||
var ahooks_default = () => {
|
||||
if (!_cache) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const path = _localpkg.resolveModule.call(void 0, "ahooks/metadata.json");
|
||||
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache = {
|
||||
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache || {};
|
||||
};
|
||||
|
||||
// src/presets/jotai.ts
|
||||
var jotai = {
|
||||
jotai: [
|
||||
"atom",
|
||||
"useAtom",
|
||||
"useAtomValue",
|
||||
"useSetAtom"
|
||||
]
|
||||
};
|
||||
var jotaiUtils = {
|
||||
"jotai/utils": [
|
||||
"atomWithReset",
|
||||
"useResetAtom",
|
||||
"useReducerAtom",
|
||||
"atomWithReducer",
|
||||
"atomFamily",
|
||||
"selectAtom",
|
||||
"useAtomCallback",
|
||||
"freezeAtom",
|
||||
"freezeAtomCreator",
|
||||
"splitAtom",
|
||||
"atomWithDefault",
|
||||
"waitForAll",
|
||||
"atomWithStorage",
|
||||
"atomWithHash",
|
||||
"createJSONStorage",
|
||||
"atomWithObservable",
|
||||
"useHydrateAtoms",
|
||||
"loadable"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/mobx.ts
|
||||
var mobx = [
|
||||
// https://mobx.js.org/api.html
|
||||
"makeObservable",
|
||||
"makeAutoObservable",
|
||||
"extendObservable",
|
||||
"observable",
|
||||
"action",
|
||||
"runInAction",
|
||||
"flow",
|
||||
"flowResult",
|
||||
"computed",
|
||||
"autorun",
|
||||
"reaction",
|
||||
"when",
|
||||
"onReactionError",
|
||||
"intercept",
|
||||
"observe",
|
||||
"onBecomeObserved",
|
||||
"onBecomeUnobserved",
|
||||
"toJS"
|
||||
];
|
||||
var mobx_default = {
|
||||
mobx: [
|
||||
// https://mobx.js.org/api.html
|
||||
...mobx
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/mobx-react-lite.ts
|
||||
var mobx_react_lite_default = {
|
||||
// https://mobx.js.org/api.html
|
||||
"mobx-react-lite": [
|
||||
"observer",
|
||||
"Observer",
|
||||
"useLocalObservable"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/preact.ts
|
||||
var preact_default = {
|
||||
"preact/hooks": [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/quasar.ts
|
||||
var quasar_default = {
|
||||
quasar: [
|
||||
// https://quasar.dev/vue-composables
|
||||
"useQuasar",
|
||||
"useDialogPluginComponent",
|
||||
"useFormChild",
|
||||
"useMeta"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/react.ts
|
||||
var CommonReactAPI = [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer",
|
||||
"useImperativeHandle",
|
||||
"useDebugValue",
|
||||
"useDeferredValue",
|
||||
"useLayoutEffect",
|
||||
"useTransition",
|
||||
"startTransition",
|
||||
"useSyncExternalStore",
|
||||
"useInsertionEffect",
|
||||
"useId",
|
||||
"lazy",
|
||||
"memo",
|
||||
"createRef",
|
||||
"forwardRef"
|
||||
];
|
||||
var react_default = {
|
||||
react: CommonReactAPI
|
||||
};
|
||||
|
||||
// src/presets/react-i18next.ts
|
||||
var react_i18next_default = {
|
||||
"react-i18next": ["useTranslation"]
|
||||
};
|
||||
|
||||
// src/presets/react-router.ts
|
||||
var ReactRouterHooks = [
|
||||
"useOutletContext",
|
||||
"useHref",
|
||||
"useInRouterContext",
|
||||
"useLocation",
|
||||
"useNavigationType",
|
||||
"useNavigate",
|
||||
"useOutlet",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRoutes"
|
||||
];
|
||||
var react_router_default = {
|
||||
"react-router": [
|
||||
...ReactRouterHooks
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/react-router-dom.ts
|
||||
var react_router_dom_default = {
|
||||
"react-router-dom": [
|
||||
...ReactRouterHooks,
|
||||
// react-router-dom only hooks
|
||||
"useLinkClickHandler",
|
||||
"useSearchParams",
|
||||
// react-router-dom Component
|
||||
// call once in general
|
||||
// 'BrowserRouter',
|
||||
// 'HashRouter',
|
||||
// 'MemoryRouter',
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Routes"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/recoil.ts
|
||||
var recoil_default = {
|
||||
// https://recoiljs.org/docs/api-reference/core/atom/
|
||||
recoil: [
|
||||
"atom",
|
||||
"selector",
|
||||
"useRecoilState",
|
||||
"useRecoilValue",
|
||||
"useSetRecoilState",
|
||||
"useResetRecoilState",
|
||||
"useRecoilStateLoadable",
|
||||
"useRecoilValueLoadable",
|
||||
"isRecoilValue",
|
||||
"useRecoilCallback"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/solid.ts
|
||||
var solidCore = {
|
||||
"solid-js": [
|
||||
"createSignal",
|
||||
"createEffect",
|
||||
"createMemo",
|
||||
"createResource",
|
||||
"onMount",
|
||||
"onCleanup",
|
||||
"onError",
|
||||
"untrack",
|
||||
"batch",
|
||||
"on",
|
||||
"createRoot",
|
||||
"mergeProps",
|
||||
"splitProps",
|
||||
"useTransition",
|
||||
"observable",
|
||||
"mapArray",
|
||||
"indexArray",
|
||||
"createContext",
|
||||
"useContext",
|
||||
"children",
|
||||
"lazy",
|
||||
"createDeferred",
|
||||
"createRenderEffect",
|
||||
"createSelector",
|
||||
"For",
|
||||
"Show",
|
||||
"Switch",
|
||||
"Match",
|
||||
"Index",
|
||||
"ErrorBoundary",
|
||||
"Suspense",
|
||||
"SuspenseList"
|
||||
]
|
||||
};
|
||||
var solidStore = {
|
||||
"solid-js/store": [
|
||||
"createStore",
|
||||
"produce",
|
||||
"reconcile",
|
||||
"createMutable"
|
||||
]
|
||||
};
|
||||
var solidWeb = {
|
||||
"solid-js/web": [
|
||||
"Dynamic",
|
||||
"hydrate",
|
||||
"render",
|
||||
"renderToString",
|
||||
"renderToStringAsync",
|
||||
"renderToStream",
|
||||
"isServer",
|
||||
"Portal"
|
||||
]
|
||||
};
|
||||
var solid_default = {
|
||||
...solidCore,
|
||||
...solidStore,
|
||||
...solidWeb
|
||||
};
|
||||
|
||||
// src/presets/solid-app-router.ts
|
||||
var solid_app_router_default = {
|
||||
"solid-app-router": [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/solid-router.ts
|
||||
var solid_router_default = {
|
||||
"@solidjs/router": [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/svelte.ts
|
||||
var svelteAnimate = {
|
||||
"svelte/animate": [
|
||||
"flip"
|
||||
]
|
||||
};
|
||||
var svelteEasing = {
|
||||
"svelte/easing": [
|
||||
"back",
|
||||
"bounce",
|
||||
"circ",
|
||||
"cubic",
|
||||
"elastic",
|
||||
"expo",
|
||||
"quad",
|
||||
"quart",
|
||||
"quint",
|
||||
"sine"
|
||||
].reduce((acc, e) => {
|
||||
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
|
||||
return acc;
|
||||
}, ["linear"])
|
||||
};
|
||||
var svelteStore = {
|
||||
"svelte/store": [
|
||||
"writable",
|
||||
"readable",
|
||||
"derived",
|
||||
"get"
|
||||
]
|
||||
};
|
||||
var svelteMotion = {
|
||||
"svelte/motion": [
|
||||
"tweened",
|
||||
"spring"
|
||||
]
|
||||
};
|
||||
var svelteTransition = {
|
||||
"svelte/transition": [
|
||||
"fade",
|
||||
"blur",
|
||||
"fly",
|
||||
"slide",
|
||||
"scale",
|
||||
"draw",
|
||||
"crossfade"
|
||||
]
|
||||
};
|
||||
var svelte = {
|
||||
svelte: [
|
||||
// lifecycle
|
||||
"onMount",
|
||||
"beforeUpdate",
|
||||
"afterUpdate",
|
||||
"onDestroy",
|
||||
// tick
|
||||
"tick",
|
||||
// context
|
||||
"setContext",
|
||||
"getContext",
|
||||
"hasContext",
|
||||
"getAllContexts",
|
||||
// event dispatcher
|
||||
"createEventDispatcher"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/uni-app.ts
|
||||
var uni_app_default = {
|
||||
"@dcloudio/uni-app": [
|
||||
"onAddToFavorites",
|
||||
"onBackPress",
|
||||
"onError",
|
||||
"onHide",
|
||||
"onLaunch",
|
||||
"onLoad",
|
||||
"onNavigationBarButtonTap",
|
||||
"onNavigationBarSearchInputChanged",
|
||||
"onNavigationBarSearchInputClicked",
|
||||
"onNavigationBarSearchInputConfirmed",
|
||||
"onNavigationBarSearchInputFocusChanged",
|
||||
"onPageNotFound",
|
||||
"onPageScroll",
|
||||
"onPullDownRefresh",
|
||||
"onReachBottom",
|
||||
"onReady",
|
||||
"onResize",
|
||||
"onShareAppMessage",
|
||||
"onShareTimeline",
|
||||
"onShow",
|
||||
"onTabItemTap",
|
||||
"onThemeChange",
|
||||
"onUnhandledRejection",
|
||||
"onUnload"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vee-validate.ts
|
||||
var vee_validate_default = {
|
||||
"vee-validate": [
|
||||
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
|
||||
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
|
||||
"validate",
|
||||
"defineRule",
|
||||
"configure",
|
||||
"useField",
|
||||
"useForm",
|
||||
"useFieldArray",
|
||||
"useResetForm",
|
||||
"useIsFieldDirty",
|
||||
"useIsFieldTouched",
|
||||
"useIsFieldValid",
|
||||
"useIsSubmitting",
|
||||
"useValidateField",
|
||||
"useIsFormDirty",
|
||||
"useIsFormTouched",
|
||||
"useIsFormValid",
|
||||
"useValidateForm",
|
||||
"useSubmitCount",
|
||||
"useFieldValue",
|
||||
"useFormValues",
|
||||
"useFormErrors",
|
||||
"useFieldError",
|
||||
"useSubmitForm",
|
||||
"FormContextKey",
|
||||
"FieldContextKey"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vitepress.ts
|
||||
var vitepress_default = {
|
||||
vitepress: [
|
||||
// helper methods
|
||||
"useData",
|
||||
"useRoute",
|
||||
"useRouter",
|
||||
"withBase"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vue-router.ts
|
||||
var vue_router_default = {
|
||||
"vue-router": [
|
||||
"useRouter",
|
||||
"useRoute",
|
||||
"useLink",
|
||||
"onBeforeRouteLeave",
|
||||
"onBeforeRouteUpdate"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vue-router-composables.ts
|
||||
var vue_router_composables_default = {
|
||||
"vue-router/composables": [
|
||||
"useRouter",
|
||||
"useRoute",
|
||||
"useLink",
|
||||
"onBeforeRouteLeave",
|
||||
"onBeforeRouteUpdate"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vueuse-core.ts
|
||||
|
||||
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
|
||||
|
||||
var _cache2;
|
||||
var vueuse_core_default = () => {
|
||||
const excluded = ["toRefs", "utils", "toRef", "toValue"];
|
||||
if (!_cache2) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
|
||||
const path = _localpkg.resolveModule.call(void 0, "@vueuse/core/indexes.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache2 = {
|
||||
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache2 || {};
|
||||
};
|
||||
|
||||
// src/presets/vueuse-head.ts
|
||||
var vueuse_head_default = {
|
||||
"@vueuse/head": [
|
||||
"useHead",
|
||||
"useSeoMeta"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vueuse-math.ts
|
||||
|
||||
|
||||
|
||||
var _cache3;
|
||||
var vueuse_math_default = () => {
|
||||
if (!_cache3) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
|
||||
const path = _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache3 = {
|
||||
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache3 || {};
|
||||
};
|
||||
|
||||
// src/presets/vuex.ts
|
||||
var vuex_default = {
|
||||
vuex: [
|
||||
// https://next.vuex.vuejs.org/api/#createstore
|
||||
"createStore",
|
||||
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
|
||||
"createLogger",
|
||||
// https://next.vuex.vuejs.org/api/#component-binding-helpers
|
||||
"mapState",
|
||||
"mapGetters",
|
||||
"mapActions",
|
||||
"mapMutations",
|
||||
"createNamespacedHelpers",
|
||||
// https://next.vuex.vuejs.org/api/#composable-functions
|
||||
"useStore"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/index.ts
|
||||
var presets = {
|
||||
..._unimport.builtinPresets,
|
||||
"ahooks": ahooks_default,
|
||||
"@vueuse/core": vueuse_core_default,
|
||||
"@vueuse/math": vueuse_math_default,
|
||||
"@vueuse/head": vueuse_head_default,
|
||||
"mobx": mobx_default,
|
||||
"mobx-react-lite": mobx_react_lite_default,
|
||||
"preact": preact_default,
|
||||
"quasar": quasar_default,
|
||||
"react": react_default,
|
||||
"react-router": react_router_default,
|
||||
"react-router-dom": react_router_dom_default,
|
||||
"react-i18next": react_i18next_default,
|
||||
"svelte": svelte,
|
||||
"svelte/animate": svelteAnimate,
|
||||
"svelte/easing": svelteEasing,
|
||||
"svelte/motion": svelteMotion,
|
||||
"svelte/store": svelteStore,
|
||||
"svelte/transition": svelteTransition,
|
||||
"vee-validate": vee_validate_default,
|
||||
"vitepress": vitepress_default,
|
||||
"vue-router": vue_router_default,
|
||||
"vue-router/composables": vue_router_composables_default,
|
||||
"vuex": vuex_default,
|
||||
"uni-app": uni_app_default,
|
||||
"solid-js": solid_default,
|
||||
"@solidjs/router": solid_router_default,
|
||||
"solid-app-router": solid_app_router_default,
|
||||
"jotai": jotai,
|
||||
"jotai/utils": jotaiUtils,
|
||||
"recoil": recoil_default
|
||||
};
|
||||
|
||||
|
||||
|
||||
exports.presets = presets;
|
||||
Generated
Vendored
+504
@@ -0,0 +1,504 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
||||
|
||||
var _chunk6BSQ6ZKCcjs = require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
|
||||
function toArray(array) {
|
||||
array = array != null ? array : [];
|
||||
return Array.isArray(array) ? array : [array];
|
||||
}
|
||||
var VOID = Symbol("p-void");
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
function throttle$1(delay, callback, options) {
|
||||
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
|
||||
var timeoutID;
|
||||
var cancelled = false;
|
||||
var lastExec = 0;
|
||||
function clearExistingTimeout() {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
}
|
||||
}
|
||||
function cancel(options2) {
|
||||
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
|
||||
clearExistingTimeout();
|
||||
cancelled = !upcomingOnly;
|
||||
}
|
||||
function wrapper() {
|
||||
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
arguments_[_key] = arguments[_key];
|
||||
}
|
||||
var self = this;
|
||||
var elapsed = Date.now() - lastExec;
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
function exec() {
|
||||
lastExec = Date.now();
|
||||
callback.apply(self, arguments_);
|
||||
}
|
||||
function clear() {
|
||||
timeoutID = void 0;
|
||||
}
|
||||
if (!noLeading && debounceMode && !timeoutID) {
|
||||
exec();
|
||||
}
|
||||
clearExistingTimeout();
|
||||
if (debounceMode === void 0 && elapsed > delay) {
|
||||
if (noLeading) {
|
||||
lastExec = Date.now();
|
||||
if (!noTrailing) {
|
||||
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
|
||||
}
|
||||
} else {
|
||||
exec();
|
||||
}
|
||||
} else if (noTrailing !== true) {
|
||||
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
|
||||
}
|
||||
}
|
||||
wrapper.cancel = cancel;
|
||||
return wrapper;
|
||||
}
|
||||
function throttle(...args) {
|
||||
return throttle$1(...args);
|
||||
}
|
||||
|
||||
// src/core/unplugin.ts
|
||||
var _localpkg = require('local-pkg');
|
||||
var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
|
||||
var _unplugin = require('unplugin');
|
||||
|
||||
// src/core/ctx.ts
|
||||
var _fs = require('fs');
|
||||
var _path = require('path');
|
||||
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
|
||||
|
||||
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
|
||||
var _unimport = require('unimport');
|
||||
var _unpluginutils = require('unplugin-utils');
|
||||
|
||||
// src/core/biomelintrc.ts
|
||||
function generateBiomeLintConfigs(imports) {
|
||||
const names = imports.map((i) => {
|
||||
var _a;
|
||||
return (_a = i.as) != null ? _a : i.name;
|
||||
}).filter(Boolean).sort();
|
||||
const config = { javascript: { globals: names } };
|
||||
const jsonBody = JSON.stringify(config, null, 2);
|
||||
return jsonBody;
|
||||
}
|
||||
|
||||
// src/core/eslintrc.ts
|
||||
function generateESLintConfigs(imports, eslintrc, globals = {}) {
|
||||
const eslintConfigs = { globals };
|
||||
imports.map((i) => {
|
||||
var _a;
|
||||
return (_a = i.as) != null ? _a : i.name;
|
||||
}).filter(Boolean).sort().forEach((name) => {
|
||||
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
|
||||
});
|
||||
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
|
||||
return jsonBody;
|
||||
}
|
||||
|
||||
// src/core/resolvers.ts
|
||||
function normalizeImport(info, name) {
|
||||
if (typeof info === "string") {
|
||||
return {
|
||||
name: "default",
|
||||
as: name,
|
||||
from: info
|
||||
};
|
||||
}
|
||||
if ("path" in info) {
|
||||
return {
|
||||
from: info.path,
|
||||
as: info.name,
|
||||
name: info.importName,
|
||||
sideEffects: info.sideEffects
|
||||
};
|
||||
}
|
||||
return {
|
||||
name,
|
||||
as: name,
|
||||
...info
|
||||
};
|
||||
}
|
||||
async function firstMatchedResolver(resolvers, fullname) {
|
||||
let name = fullname;
|
||||
for (const resolver of resolvers) {
|
||||
if (typeof resolver === "object" && resolver.type === "directive") {
|
||||
if (name.startsWith("v"))
|
||||
name = name.slice(1);
|
||||
else
|
||||
continue;
|
||||
}
|
||||
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
|
||||
if (resolved)
|
||||
return normalizeImport(resolved, fullname);
|
||||
}
|
||||
}
|
||||
function resolversAddon(resolvers) {
|
||||
return {
|
||||
name: "unplugin-auto-import:resolvers",
|
||||
async matchImports(names, matched) {
|
||||
if (!resolvers.length)
|
||||
return;
|
||||
const dynamic = [];
|
||||
const sideEffects = [];
|
||||
await Promise.all([...names].map(async (name) => {
|
||||
const matchedImport = matched.find((i) => i.as === name);
|
||||
if (matchedImport) {
|
||||
if ("sideEffects" in matchedImport)
|
||||
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
|
||||
return;
|
||||
}
|
||||
const resolved = await firstMatchedResolver(resolvers, name);
|
||||
if (resolved)
|
||||
dynamic.push(resolved);
|
||||
if (resolved == null ? void 0 : resolved.sideEffects)
|
||||
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
|
||||
}));
|
||||
if (dynamic.length) {
|
||||
this.dynamicImports.push(...dynamic);
|
||||
this.invalidate();
|
||||
}
|
||||
if (dynamic.length || sideEffects.length)
|
||||
return [...matched, ...dynamic, ...sideEffects];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// src/core/ctx.ts
|
||||
function createContext(options = {}, root = _process2.default.cwd()) {
|
||||
var _a, _b, _c;
|
||||
root = slash(root);
|
||||
const {
|
||||
dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript"),
|
||||
dirsScanOptions,
|
||||
dirs,
|
||||
vueDirectives,
|
||||
vueTemplate
|
||||
} = options;
|
||||
const eslintrc = options.eslintrc || {};
|
||||
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
|
||||
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
|
||||
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
|
||||
const biomelintrc = options.biomelintrc || {};
|
||||
biomelintrc.enabled = biomelintrc.enabled !== void 0;
|
||||
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
|
||||
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
|
||||
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
|
||||
const injectAtEnd = options.injectAtEnd !== false;
|
||||
const unimport = _unimport.createUnimport.call(void 0, {
|
||||
imports: [],
|
||||
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
|
||||
dirsScanOptions: {
|
||||
...dirsScanOptions,
|
||||
cwd: root
|
||||
},
|
||||
dirs,
|
||||
injectAtEnd,
|
||||
parser: options.parser,
|
||||
addons: {
|
||||
addons: [
|
||||
resolversAddon(resolvers),
|
||||
{
|
||||
name: "unplugin-auto-import:dts",
|
||||
declaration(dts2) {
|
||||
return `${`
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
${dts2}`.trim()}
|
||||
`;
|
||||
}
|
||||
}
|
||||
],
|
||||
vueDirectives,
|
||||
vueTemplate
|
||||
}
|
||||
});
|
||||
const importsPromise = flattenImports(options.imports).then((imports) => {
|
||||
var _a2, _b2;
|
||||
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
|
||||
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
|
||||
const compare = (left, right) => {
|
||||
return right instanceof RegExp ? right.test(left) : right === left;
|
||||
};
|
||||
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
|
||||
const i = imports.find((i2) => compare(i2.as, name));
|
||||
if (i)
|
||||
i.disabled = true;
|
||||
});
|
||||
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
|
||||
const i = imports.find((i2) => compare(i2.as, name));
|
||||
if (i)
|
||||
i.dtsDisabled = true;
|
||||
});
|
||||
return unimport.getInternalContext().replaceImports(imports);
|
||||
});
|
||||
const filter = _unpluginutils.createFilter.call(void 0,
|
||||
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
|
||||
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
|
||||
);
|
||||
const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
|
||||
const multilineCommentsRE = /\/\*.*?\*\//gs;
|
||||
const singlelineCommentsRE = /\/\/.*$/gm;
|
||||
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
|
||||
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
|
||||
function parseDTS(dts2) {
|
||||
var _a2;
|
||||
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
|
||||
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
|
||||
if (!code)
|
||||
return;
|
||||
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
|
||||
}
|
||||
async function generateDTS(file) {
|
||||
await importsPromise;
|
||||
const dir = _path.dirname.call(void 0, file);
|
||||
const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
|
||||
const originalDTS = parseDTS(originalContent);
|
||||
let currentContent = await unimport.generateTypeDeclarations({
|
||||
resolvePath: (i) => {
|
||||
if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
|
||||
const related = slash(_path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
|
||||
return !related.startsWith(".") ? `./${related}` : related;
|
||||
}
|
||||
return i.from;
|
||||
}
|
||||
});
|
||||
const currentDTS = parseDTS(currentContent);
|
||||
if (options.vueTemplate) {
|
||||
currentContent = currentContent.replace(
|
||||
componentCustomPropertiesReg,
|
||||
($1) => `interface GlobalComponents {}
|
||||
${$1}`
|
||||
);
|
||||
}
|
||||
if (originalDTS) {
|
||||
Object.keys(currentDTS).forEach((key) => {
|
||||
originalDTS[key] = currentDTS[key];
|
||||
});
|
||||
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
|
||||
return currentContent.replace(dtsReg, () => `declare global {
|
||||
${dtsList.join("\n")}
|
||||
}`);
|
||||
}
|
||||
return currentContent;
|
||||
}
|
||||
async function parseESLint() {
|
||||
if (!eslintrc.filepath)
|
||||
return {};
|
||||
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
|
||||
return {};
|
||||
const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
|
||||
const config = JSON.parse(configStr || '{ "globals": {} }');
|
||||
return config.globals;
|
||||
}
|
||||
async function generateESLint() {
|
||||
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
|
||||
}
|
||||
async function generateBiomeLint() {
|
||||
return generateBiomeLintConfigs(await unimport.getImports());
|
||||
}
|
||||
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
|
||||
async function writeFile(filePath, content = "") {
|
||||
await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
|
||||
return await _fs.promises.writeFile(filePath, content, "utf-8");
|
||||
}
|
||||
let lastDTS;
|
||||
let lastESLint;
|
||||
let lastBiomeLint;
|
||||
let lastUnimportItems;
|
||||
async function writeConfigFiles() {
|
||||
const promises = [];
|
||||
if (dts) {
|
||||
promises.push(
|
||||
generateDTS(dts).then((content) => {
|
||||
if (content !== lastDTS) {
|
||||
lastDTS = content;
|
||||
return writeFile(dts, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (eslintrc.enabled && eslintrc.filepath) {
|
||||
const filepath = eslintrc.filepath;
|
||||
promises.push(
|
||||
generateESLint().then(async (content) => {
|
||||
if (filepath.endsWith(".cjs"))
|
||||
content = `module.exports = ${content}`;
|
||||
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
|
||||
content = `export default ${content}`;
|
||||
content = `${content}
|
||||
`;
|
||||
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
|
||||
lastESLint = content;
|
||||
return writeFile(eslintrc.filepath, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (biomelintrc.enabled) {
|
||||
promises.push(
|
||||
generateBiomeLint().then((content) => {
|
||||
if (content !== lastBiomeLint) {
|
||||
lastBiomeLint = content;
|
||||
return writeFile(biomelintrc.filepath, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (dumpUnimportItems) {
|
||||
promises.push(
|
||||
unimport.getImports().then((items) => {
|
||||
if (!dumpUnimportItems)
|
||||
return;
|
||||
const content = JSON.stringify(items, null, 2);
|
||||
if (content !== lastUnimportItems) {
|
||||
lastUnimportItems = content;
|
||||
return writeFile(dumpUnimportItems, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.all(promises);
|
||||
}
|
||||
async function scanDirs() {
|
||||
await unimport.modifyDynamicImports(async (imports) => {
|
||||
const exports_ = await unimport.scanImportsFromDir();
|
||||
exports_.forEach((i) => i.__source = "dir");
|
||||
return modifyDefaultExportsAlias([
|
||||
...imports.filter((i) => i.__source !== "dir"),
|
||||
...exports_
|
||||
], options);
|
||||
});
|
||||
writeConfigFilesThrottled();
|
||||
}
|
||||
async function transform(code, id) {
|
||||
await importsPromise;
|
||||
const s = new (0, _magicstring2.default)(code);
|
||||
await unimport.injectImports(s, id);
|
||||
if (!s.hasChanged())
|
||||
return;
|
||||
writeConfigFilesThrottled();
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({ source: id, includeContent: true, hires: true })
|
||||
};
|
||||
}
|
||||
return {
|
||||
root,
|
||||
dirs,
|
||||
filter,
|
||||
scanDirs,
|
||||
writeConfigFiles,
|
||||
writeConfigFilesThrottled,
|
||||
transform,
|
||||
generateDTS,
|
||||
generateESLint,
|
||||
unimport
|
||||
};
|
||||
}
|
||||
async function flattenImports(map) {
|
||||
const promises = await Promise.all(toArray(map).map(async (definition) => {
|
||||
if (typeof definition === "string") {
|
||||
if (!_chunk6BSQ6ZKCcjs.presets[definition])
|
||||
throw new Error(`[auto-import] preset ${definition} not found`);
|
||||
const preset = _chunk6BSQ6ZKCcjs.presets[definition];
|
||||
definition = typeof preset === "function" ? preset() : preset;
|
||||
}
|
||||
if ("from" in definition && "imports" in definition) {
|
||||
return await _unimport.resolvePreset.call(void 0, definition);
|
||||
} else {
|
||||
const resolved = [];
|
||||
for (const mod of Object.keys(definition)) {
|
||||
for (const id of definition[mod]) {
|
||||
const meta = {
|
||||
from: mod
|
||||
};
|
||||
if (Array.isArray(id)) {
|
||||
meta.name = id[0];
|
||||
meta.as = id[1];
|
||||
} else {
|
||||
meta.name = id;
|
||||
meta.as = id;
|
||||
}
|
||||
resolved.push(meta);
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
}));
|
||||
return promises.flat();
|
||||
}
|
||||
function modifyDefaultExportsAlias(imports, options) {
|
||||
if (options.defaultExportByFilename) {
|
||||
imports.forEach((i) => {
|
||||
var _a, _b, _c;
|
||||
if (i.name === "default")
|
||||
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
|
||||
});
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
// src/core/unplugin.ts
|
||||
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
|
||||
let ctx = createContext(options);
|
||||
return {
|
||||
name: "unplugin-auto-import",
|
||||
enforce: "post",
|
||||
transformInclude(id) {
|
||||
return ctx.filter(id);
|
||||
},
|
||||
async transform(code, id) {
|
||||
return ctx.transform(code, id);
|
||||
},
|
||||
async buildStart() {
|
||||
await ctx.scanDirs();
|
||||
},
|
||||
async buildEnd() {
|
||||
await ctx.writeConfigFiles();
|
||||
},
|
||||
vite: {
|
||||
async config(config) {
|
||||
var _a;
|
||||
if (options.viteOptimizeDeps === false)
|
||||
return;
|
||||
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
|
||||
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && _localpkg.isPackageExists.call(void 0, i)));
|
||||
if (!imports.size)
|
||||
return;
|
||||
return {
|
||||
optimizeDeps: {
|
||||
include: [...imports]
|
||||
}
|
||||
};
|
||||
},
|
||||
async handleHotUpdate({ file }) {
|
||||
var _a;
|
||||
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => _picomatch2.default.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
|
||||
await ctx.scanDirs();
|
||||
},
|
||||
async configResolved(config) {
|
||||
if (ctx.root !== config.root) {
|
||||
ctx = createContext(options, config.root);
|
||||
await ctx.scanDirs();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
|
||||
exports.unplugin_default = unplugin_default;
|
||||
Generated
Vendored
+608
@@ -0,0 +1,608 @@
|
||||
// src/presets/index.ts
|
||||
import { builtinPresets } from "unimport";
|
||||
|
||||
// src/presets/ahooks.ts
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolveModule } from "local-pkg";
|
||||
var _cache;
|
||||
var ahooks_default = () => {
|
||||
if (!_cache) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const path = resolveModule("ahooks/metadata.json");
|
||||
indexesJson = JSON.parse(readFileSync(path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache = {
|
||||
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache || {};
|
||||
};
|
||||
|
||||
// src/presets/jotai.ts
|
||||
var jotai = {
|
||||
jotai: [
|
||||
"atom",
|
||||
"useAtom",
|
||||
"useAtomValue",
|
||||
"useSetAtom"
|
||||
]
|
||||
};
|
||||
var jotaiUtils = {
|
||||
"jotai/utils": [
|
||||
"atomWithReset",
|
||||
"useResetAtom",
|
||||
"useReducerAtom",
|
||||
"atomWithReducer",
|
||||
"atomFamily",
|
||||
"selectAtom",
|
||||
"useAtomCallback",
|
||||
"freezeAtom",
|
||||
"freezeAtomCreator",
|
||||
"splitAtom",
|
||||
"atomWithDefault",
|
||||
"waitForAll",
|
||||
"atomWithStorage",
|
||||
"atomWithHash",
|
||||
"createJSONStorage",
|
||||
"atomWithObservable",
|
||||
"useHydrateAtoms",
|
||||
"loadable"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/mobx.ts
|
||||
var mobx = [
|
||||
// https://mobx.js.org/api.html
|
||||
"makeObservable",
|
||||
"makeAutoObservable",
|
||||
"extendObservable",
|
||||
"observable",
|
||||
"action",
|
||||
"runInAction",
|
||||
"flow",
|
||||
"flowResult",
|
||||
"computed",
|
||||
"autorun",
|
||||
"reaction",
|
||||
"when",
|
||||
"onReactionError",
|
||||
"intercept",
|
||||
"observe",
|
||||
"onBecomeObserved",
|
||||
"onBecomeUnobserved",
|
||||
"toJS"
|
||||
];
|
||||
var mobx_default = {
|
||||
mobx: [
|
||||
// https://mobx.js.org/api.html
|
||||
...mobx
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/mobx-react-lite.ts
|
||||
var mobx_react_lite_default = {
|
||||
// https://mobx.js.org/api.html
|
||||
"mobx-react-lite": [
|
||||
"observer",
|
||||
"Observer",
|
||||
"useLocalObservable"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/preact.ts
|
||||
var preact_default = {
|
||||
"preact/hooks": [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/quasar.ts
|
||||
var quasar_default = {
|
||||
quasar: [
|
||||
// https://quasar.dev/vue-composables
|
||||
"useQuasar",
|
||||
"useDialogPluginComponent",
|
||||
"useFormChild",
|
||||
"useMeta"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/react.ts
|
||||
var CommonReactAPI = [
|
||||
"useState",
|
||||
"useCallback",
|
||||
"useMemo",
|
||||
"useEffect",
|
||||
"useRef",
|
||||
"useContext",
|
||||
"useReducer",
|
||||
"useImperativeHandle",
|
||||
"useDebugValue",
|
||||
"useDeferredValue",
|
||||
"useLayoutEffect",
|
||||
"useTransition",
|
||||
"startTransition",
|
||||
"useSyncExternalStore",
|
||||
"useInsertionEffect",
|
||||
"useId",
|
||||
"lazy",
|
||||
"memo",
|
||||
"createRef",
|
||||
"forwardRef"
|
||||
];
|
||||
var react_default = {
|
||||
react: CommonReactAPI
|
||||
};
|
||||
|
||||
// src/presets/react-i18next.ts
|
||||
var react_i18next_default = {
|
||||
"react-i18next": ["useTranslation"]
|
||||
};
|
||||
|
||||
// src/presets/react-router.ts
|
||||
var ReactRouterHooks = [
|
||||
"useOutletContext",
|
||||
"useHref",
|
||||
"useInRouterContext",
|
||||
"useLocation",
|
||||
"useNavigationType",
|
||||
"useNavigate",
|
||||
"useOutlet",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRoutes"
|
||||
];
|
||||
var react_router_default = {
|
||||
"react-router": [
|
||||
...ReactRouterHooks
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/react-router-dom.ts
|
||||
var react_router_dom_default = {
|
||||
"react-router-dom": [
|
||||
...ReactRouterHooks,
|
||||
// react-router-dom only hooks
|
||||
"useLinkClickHandler",
|
||||
"useSearchParams",
|
||||
// react-router-dom Component
|
||||
// call once in general
|
||||
// 'BrowserRouter',
|
||||
// 'HashRouter',
|
||||
// 'MemoryRouter',
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Routes"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/recoil.ts
|
||||
var recoil_default = {
|
||||
// https://recoiljs.org/docs/api-reference/core/atom/
|
||||
recoil: [
|
||||
"atom",
|
||||
"selector",
|
||||
"useRecoilState",
|
||||
"useRecoilValue",
|
||||
"useSetRecoilState",
|
||||
"useResetRecoilState",
|
||||
"useRecoilStateLoadable",
|
||||
"useRecoilValueLoadable",
|
||||
"isRecoilValue",
|
||||
"useRecoilCallback"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/solid.ts
|
||||
var solidCore = {
|
||||
"solid-js": [
|
||||
"createSignal",
|
||||
"createEffect",
|
||||
"createMemo",
|
||||
"createResource",
|
||||
"onMount",
|
||||
"onCleanup",
|
||||
"onError",
|
||||
"untrack",
|
||||
"batch",
|
||||
"on",
|
||||
"createRoot",
|
||||
"mergeProps",
|
||||
"splitProps",
|
||||
"useTransition",
|
||||
"observable",
|
||||
"mapArray",
|
||||
"indexArray",
|
||||
"createContext",
|
||||
"useContext",
|
||||
"children",
|
||||
"lazy",
|
||||
"createDeferred",
|
||||
"createRenderEffect",
|
||||
"createSelector",
|
||||
"For",
|
||||
"Show",
|
||||
"Switch",
|
||||
"Match",
|
||||
"Index",
|
||||
"ErrorBoundary",
|
||||
"Suspense",
|
||||
"SuspenseList"
|
||||
]
|
||||
};
|
||||
var solidStore = {
|
||||
"solid-js/store": [
|
||||
"createStore",
|
||||
"produce",
|
||||
"reconcile",
|
||||
"createMutable"
|
||||
]
|
||||
};
|
||||
var solidWeb = {
|
||||
"solid-js/web": [
|
||||
"Dynamic",
|
||||
"hydrate",
|
||||
"render",
|
||||
"renderToString",
|
||||
"renderToStringAsync",
|
||||
"renderToStream",
|
||||
"isServer",
|
||||
"Portal"
|
||||
]
|
||||
};
|
||||
var solid_default = {
|
||||
...solidCore,
|
||||
...solidStore,
|
||||
...solidWeb
|
||||
};
|
||||
|
||||
// src/presets/solid-app-router.ts
|
||||
var solid_app_router_default = {
|
||||
"solid-app-router": [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/solid-router.ts
|
||||
var solid_router_default = {
|
||||
"@solidjs/router": [
|
||||
"Link",
|
||||
"NavLink",
|
||||
"Navigate",
|
||||
"Outlet",
|
||||
"Route",
|
||||
"Router",
|
||||
"Routes",
|
||||
"_mergeSearchString",
|
||||
"createIntegration",
|
||||
"hashIntegration",
|
||||
"normalizeIntegration",
|
||||
"pathIntegration",
|
||||
"staticIntegration",
|
||||
"useHref",
|
||||
"useIsRouting",
|
||||
"useLocation",
|
||||
"useMatch",
|
||||
"useNavigate",
|
||||
"useParams",
|
||||
"useResolvedPath",
|
||||
"useRouteData",
|
||||
"useRoutes",
|
||||
"useSearchParams"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/svelte.ts
|
||||
var svelteAnimate = {
|
||||
"svelte/animate": [
|
||||
"flip"
|
||||
]
|
||||
};
|
||||
var svelteEasing = {
|
||||
"svelte/easing": [
|
||||
"back",
|
||||
"bounce",
|
||||
"circ",
|
||||
"cubic",
|
||||
"elastic",
|
||||
"expo",
|
||||
"quad",
|
||||
"quart",
|
||||
"quint",
|
||||
"sine"
|
||||
].reduce((acc, e) => {
|
||||
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
|
||||
return acc;
|
||||
}, ["linear"])
|
||||
};
|
||||
var svelteStore = {
|
||||
"svelte/store": [
|
||||
"writable",
|
||||
"readable",
|
||||
"derived",
|
||||
"get"
|
||||
]
|
||||
};
|
||||
var svelteMotion = {
|
||||
"svelte/motion": [
|
||||
"tweened",
|
||||
"spring"
|
||||
]
|
||||
};
|
||||
var svelteTransition = {
|
||||
"svelte/transition": [
|
||||
"fade",
|
||||
"blur",
|
||||
"fly",
|
||||
"slide",
|
||||
"scale",
|
||||
"draw",
|
||||
"crossfade"
|
||||
]
|
||||
};
|
||||
var svelte = {
|
||||
svelte: [
|
||||
// lifecycle
|
||||
"onMount",
|
||||
"beforeUpdate",
|
||||
"afterUpdate",
|
||||
"onDestroy",
|
||||
// tick
|
||||
"tick",
|
||||
// context
|
||||
"setContext",
|
||||
"getContext",
|
||||
"hasContext",
|
||||
"getAllContexts",
|
||||
// event dispatcher
|
||||
"createEventDispatcher"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/uni-app.ts
|
||||
var uni_app_default = {
|
||||
"@dcloudio/uni-app": [
|
||||
"onAddToFavorites",
|
||||
"onBackPress",
|
||||
"onError",
|
||||
"onHide",
|
||||
"onLaunch",
|
||||
"onLoad",
|
||||
"onNavigationBarButtonTap",
|
||||
"onNavigationBarSearchInputChanged",
|
||||
"onNavigationBarSearchInputClicked",
|
||||
"onNavigationBarSearchInputConfirmed",
|
||||
"onNavigationBarSearchInputFocusChanged",
|
||||
"onPageNotFound",
|
||||
"onPageScroll",
|
||||
"onPullDownRefresh",
|
||||
"onReachBottom",
|
||||
"onReady",
|
||||
"onResize",
|
||||
"onShareAppMessage",
|
||||
"onShareTimeline",
|
||||
"onShow",
|
||||
"onTabItemTap",
|
||||
"onThemeChange",
|
||||
"onUnhandledRejection",
|
||||
"onUnload"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vee-validate.ts
|
||||
var vee_validate_default = {
|
||||
"vee-validate": [
|
||||
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
|
||||
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
|
||||
"validate",
|
||||
"defineRule",
|
||||
"configure",
|
||||
"useField",
|
||||
"useForm",
|
||||
"useFieldArray",
|
||||
"useResetForm",
|
||||
"useIsFieldDirty",
|
||||
"useIsFieldTouched",
|
||||
"useIsFieldValid",
|
||||
"useIsSubmitting",
|
||||
"useValidateField",
|
||||
"useIsFormDirty",
|
||||
"useIsFormTouched",
|
||||
"useIsFormValid",
|
||||
"useValidateForm",
|
||||
"useSubmitCount",
|
||||
"useFieldValue",
|
||||
"useFormValues",
|
||||
"useFormErrors",
|
||||
"useFieldError",
|
||||
"useSubmitForm",
|
||||
"FormContextKey",
|
||||
"FieldContextKey"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vitepress.ts
|
||||
var vitepress_default = {
|
||||
vitepress: [
|
||||
// helper methods
|
||||
"useData",
|
||||
"useRoute",
|
||||
"useRouter",
|
||||
"withBase"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vue-router.ts
|
||||
var vue_router_default = {
|
||||
"vue-router": [
|
||||
"useRouter",
|
||||
"useRoute",
|
||||
"useLink",
|
||||
"onBeforeRouteLeave",
|
||||
"onBeforeRouteUpdate"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vue-router-composables.ts
|
||||
var vue_router_composables_default = {
|
||||
"vue-router/composables": [
|
||||
"useRouter",
|
||||
"useRoute",
|
||||
"useLink",
|
||||
"onBeforeRouteLeave",
|
||||
"onBeforeRouteUpdate"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vueuse-core.ts
|
||||
import { readFileSync as readFileSync2 } from "node:fs";
|
||||
import process from "node:process";
|
||||
import { resolveModule as resolveModule2 } from "local-pkg";
|
||||
var _cache2;
|
||||
var vueuse_core_default = () => {
|
||||
const excluded = ["toRefs", "utils", "toRef", "toValue"];
|
||||
if (!_cache2) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const corePath = resolveModule2("@vueuse/core") || process.cwd();
|
||||
const path = resolveModule2("@vueuse/core/indexes.json") || resolveModule2("@vueuse/metadata/index.json") || resolveModule2("@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
indexesJson = JSON.parse(readFileSync2(path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache2 = {
|
||||
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache2 || {};
|
||||
};
|
||||
|
||||
// src/presets/vueuse-head.ts
|
||||
var vueuse_head_default = {
|
||||
"@vueuse/head": [
|
||||
"useHead",
|
||||
"useSeoMeta"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/vueuse-math.ts
|
||||
import { readFileSync as readFileSync3 } from "node:fs";
|
||||
import process2 from "node:process";
|
||||
import { resolveModule as resolveModule3 } from "local-pkg";
|
||||
var _cache3;
|
||||
var vueuse_math_default = () => {
|
||||
if (!_cache3) {
|
||||
let indexesJson;
|
||||
try {
|
||||
const corePath = resolveModule3("@vueuse/core") || process2.cwd();
|
||||
const path = resolveModule3("@vueuse/metadata/index.json") || resolveModule3("@vueuse/metadata/index.json", { paths: [corePath] });
|
||||
indexesJson = JSON.parse(readFileSync3(path, "utf-8"));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
|
||||
}
|
||||
if (indexesJson) {
|
||||
_cache3 = {
|
||||
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
|
||||
};
|
||||
}
|
||||
}
|
||||
return _cache3 || {};
|
||||
};
|
||||
|
||||
// src/presets/vuex.ts
|
||||
var vuex_default = {
|
||||
vuex: [
|
||||
// https://next.vuex.vuejs.org/api/#createstore
|
||||
"createStore",
|
||||
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
|
||||
"createLogger",
|
||||
// https://next.vuex.vuejs.org/api/#component-binding-helpers
|
||||
"mapState",
|
||||
"mapGetters",
|
||||
"mapActions",
|
||||
"mapMutations",
|
||||
"createNamespacedHelpers",
|
||||
// https://next.vuex.vuejs.org/api/#composable-functions
|
||||
"useStore"
|
||||
]
|
||||
};
|
||||
|
||||
// src/presets/index.ts
|
||||
var presets = {
|
||||
...builtinPresets,
|
||||
"ahooks": ahooks_default,
|
||||
"@vueuse/core": vueuse_core_default,
|
||||
"@vueuse/math": vueuse_math_default,
|
||||
"@vueuse/head": vueuse_head_default,
|
||||
"mobx": mobx_default,
|
||||
"mobx-react-lite": mobx_react_lite_default,
|
||||
"preact": preact_default,
|
||||
"quasar": quasar_default,
|
||||
"react": react_default,
|
||||
"react-router": react_router_default,
|
||||
"react-router-dom": react_router_dom_default,
|
||||
"react-i18next": react_i18next_default,
|
||||
"svelte": svelte,
|
||||
"svelte/animate": svelteAnimate,
|
||||
"svelte/easing": svelteEasing,
|
||||
"svelte/motion": svelteMotion,
|
||||
"svelte/store": svelteStore,
|
||||
"svelte/transition": svelteTransition,
|
||||
"vee-validate": vee_validate_default,
|
||||
"vitepress": vitepress_default,
|
||||
"vue-router": vue_router_default,
|
||||
"vue-router/composables": vue_router_composables_default,
|
||||
"vuex": vuex_default,
|
||||
"uni-app": uni_app_default,
|
||||
"solid-js": solid_default,
|
||||
"@solidjs/router": solid_router_default,
|
||||
"solid-app-router": solid_app_router_default,
|
||||
"jotai": jotai,
|
||||
"jotai/utils": jotaiUtils,
|
||||
"recoil": recoil_default
|
||||
};
|
||||
|
||||
export {
|
||||
presets
|
||||
};
|
||||
Generated
Vendored
+504
@@ -0,0 +1,504 @@
|
||||
import {
|
||||
presets
|
||||
} from "./chunk-DTT25XJ5.js";
|
||||
|
||||
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
|
||||
function toArray(array) {
|
||||
array = array != null ? array : [];
|
||||
return Array.isArray(array) ? array : [array];
|
||||
}
|
||||
var VOID = Symbol("p-void");
|
||||
function slash(str) {
|
||||
return str.replace(/\\/g, "/");
|
||||
}
|
||||
function throttle$1(delay, callback, options) {
|
||||
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
|
||||
var timeoutID;
|
||||
var cancelled = false;
|
||||
var lastExec = 0;
|
||||
function clearExistingTimeout() {
|
||||
if (timeoutID) {
|
||||
clearTimeout(timeoutID);
|
||||
}
|
||||
}
|
||||
function cancel(options2) {
|
||||
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
|
||||
clearExistingTimeout();
|
||||
cancelled = !upcomingOnly;
|
||||
}
|
||||
function wrapper() {
|
||||
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
|
||||
arguments_[_key] = arguments[_key];
|
||||
}
|
||||
var self = this;
|
||||
var elapsed = Date.now() - lastExec;
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
function exec() {
|
||||
lastExec = Date.now();
|
||||
callback.apply(self, arguments_);
|
||||
}
|
||||
function clear() {
|
||||
timeoutID = void 0;
|
||||
}
|
||||
if (!noLeading && debounceMode && !timeoutID) {
|
||||
exec();
|
||||
}
|
||||
clearExistingTimeout();
|
||||
if (debounceMode === void 0 && elapsed > delay) {
|
||||
if (noLeading) {
|
||||
lastExec = Date.now();
|
||||
if (!noTrailing) {
|
||||
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
|
||||
}
|
||||
} else {
|
||||
exec();
|
||||
}
|
||||
} else if (noTrailing !== true) {
|
||||
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
|
||||
}
|
||||
}
|
||||
wrapper.cancel = cancel;
|
||||
return wrapper;
|
||||
}
|
||||
function throttle(...args) {
|
||||
return throttle$1(...args);
|
||||
}
|
||||
|
||||
// src/core/unplugin.ts
|
||||
import { isPackageExists as isPackageExists2 } from "local-pkg";
|
||||
import pm from "picomatch";
|
||||
import { createUnplugin } from "unplugin";
|
||||
|
||||
// src/core/ctx.ts
|
||||
import { existsSync, promises as fs } from "node:fs";
|
||||
import { dirname, isAbsolute, relative, resolve } from "node:path";
|
||||
import process from "node:process";
|
||||
import { isPackageExists } from "local-pkg";
|
||||
import MagicString from "magic-string";
|
||||
import { createUnimport, resolvePreset } from "unimport";
|
||||
import { createFilter } from "unplugin-utils";
|
||||
|
||||
// src/core/biomelintrc.ts
|
||||
function generateBiomeLintConfigs(imports) {
|
||||
const names = imports.map((i) => {
|
||||
var _a;
|
||||
return (_a = i.as) != null ? _a : i.name;
|
||||
}).filter(Boolean).sort();
|
||||
const config = { javascript: { globals: names } };
|
||||
const jsonBody = JSON.stringify(config, null, 2);
|
||||
return jsonBody;
|
||||
}
|
||||
|
||||
// src/core/eslintrc.ts
|
||||
function generateESLintConfigs(imports, eslintrc, globals = {}) {
|
||||
const eslintConfigs = { globals };
|
||||
imports.map((i) => {
|
||||
var _a;
|
||||
return (_a = i.as) != null ? _a : i.name;
|
||||
}).filter(Boolean).sort().forEach((name) => {
|
||||
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
|
||||
});
|
||||
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
|
||||
return jsonBody;
|
||||
}
|
||||
|
||||
// src/core/resolvers.ts
|
||||
function normalizeImport(info, name) {
|
||||
if (typeof info === "string") {
|
||||
return {
|
||||
name: "default",
|
||||
as: name,
|
||||
from: info
|
||||
};
|
||||
}
|
||||
if ("path" in info) {
|
||||
return {
|
||||
from: info.path,
|
||||
as: info.name,
|
||||
name: info.importName,
|
||||
sideEffects: info.sideEffects
|
||||
};
|
||||
}
|
||||
return {
|
||||
name,
|
||||
as: name,
|
||||
...info
|
||||
};
|
||||
}
|
||||
async function firstMatchedResolver(resolvers, fullname) {
|
||||
let name = fullname;
|
||||
for (const resolver of resolvers) {
|
||||
if (typeof resolver === "object" && resolver.type === "directive") {
|
||||
if (name.startsWith("v"))
|
||||
name = name.slice(1);
|
||||
else
|
||||
continue;
|
||||
}
|
||||
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
|
||||
if (resolved)
|
||||
return normalizeImport(resolved, fullname);
|
||||
}
|
||||
}
|
||||
function resolversAddon(resolvers) {
|
||||
return {
|
||||
name: "unplugin-auto-import:resolvers",
|
||||
async matchImports(names, matched) {
|
||||
if (!resolvers.length)
|
||||
return;
|
||||
const dynamic = [];
|
||||
const sideEffects = [];
|
||||
await Promise.all([...names].map(async (name) => {
|
||||
const matchedImport = matched.find((i) => i.as === name);
|
||||
if (matchedImport) {
|
||||
if ("sideEffects" in matchedImport)
|
||||
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
|
||||
return;
|
||||
}
|
||||
const resolved = await firstMatchedResolver(resolvers, name);
|
||||
if (resolved)
|
||||
dynamic.push(resolved);
|
||||
if (resolved == null ? void 0 : resolved.sideEffects)
|
||||
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
|
||||
}));
|
||||
if (dynamic.length) {
|
||||
this.dynamicImports.push(...dynamic);
|
||||
this.invalidate();
|
||||
}
|
||||
if (dynamic.length || sideEffects.length)
|
||||
return [...matched, ...dynamic, ...sideEffects];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// src/core/ctx.ts
|
||||
function createContext(options = {}, root = process.cwd()) {
|
||||
var _a, _b, _c;
|
||||
root = slash(root);
|
||||
const {
|
||||
dts: preferDTS = isPackageExists("typescript"),
|
||||
dirsScanOptions,
|
||||
dirs,
|
||||
vueDirectives,
|
||||
vueTemplate
|
||||
} = options;
|
||||
const eslintrc = options.eslintrc || {};
|
||||
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
|
||||
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
|
||||
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
|
||||
const biomelintrc = options.biomelintrc || {};
|
||||
biomelintrc.enabled = biomelintrc.enabled !== void 0;
|
||||
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
|
||||
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
|
||||
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
|
||||
const injectAtEnd = options.injectAtEnd !== false;
|
||||
const unimport = createUnimport({
|
||||
imports: [],
|
||||
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
|
||||
dirsScanOptions: {
|
||||
...dirsScanOptions,
|
||||
cwd: root
|
||||
},
|
||||
dirs,
|
||||
injectAtEnd,
|
||||
parser: options.parser,
|
||||
addons: {
|
||||
addons: [
|
||||
resolversAddon(resolvers),
|
||||
{
|
||||
name: "unplugin-auto-import:dts",
|
||||
declaration(dts2) {
|
||||
return `${`
|
||||
/* eslint-disable */
|
||||
/* prettier-ignore */
|
||||
// @ts-nocheck
|
||||
// noinspection JSUnusedGlobalSymbols
|
||||
// Generated by unplugin-auto-import
|
||||
// biome-ignore lint: disable
|
||||
${dts2}`.trim()}
|
||||
`;
|
||||
}
|
||||
}
|
||||
],
|
||||
vueDirectives,
|
||||
vueTemplate
|
||||
}
|
||||
});
|
||||
const importsPromise = flattenImports(options.imports).then((imports) => {
|
||||
var _a2, _b2;
|
||||
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
|
||||
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
|
||||
const compare = (left, right) => {
|
||||
return right instanceof RegExp ? right.test(left) : right === left;
|
||||
};
|
||||
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
|
||||
const i = imports.find((i2) => compare(i2.as, name));
|
||||
if (i)
|
||||
i.disabled = true;
|
||||
});
|
||||
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
|
||||
const i = imports.find((i2) => compare(i2.as, name));
|
||||
if (i)
|
||||
i.dtsDisabled = true;
|
||||
});
|
||||
return unimport.getInternalContext().replaceImports(imports);
|
||||
});
|
||||
const filter = createFilter(
|
||||
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
|
||||
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
|
||||
);
|
||||
const dts = preferDTS === false ? false : preferDTS === true ? resolve(root, "auto-imports.d.ts") : resolve(root, preferDTS);
|
||||
const multilineCommentsRE = /\/\*.*?\*\//gs;
|
||||
const singlelineCommentsRE = /\/\/.*$/gm;
|
||||
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
|
||||
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
|
||||
function parseDTS(dts2) {
|
||||
var _a2;
|
||||
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
|
||||
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
|
||||
if (!code)
|
||||
return;
|
||||
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
|
||||
}
|
||||
async function generateDTS(file) {
|
||||
await importsPromise;
|
||||
const dir = dirname(file);
|
||||
const originalContent = existsSync(file) ? await fs.readFile(file, "utf-8") : "";
|
||||
const originalDTS = parseDTS(originalContent);
|
||||
let currentContent = await unimport.generateTypeDeclarations({
|
||||
resolvePath: (i) => {
|
||||
if (i.from.startsWith(".") || isAbsolute(i.from)) {
|
||||
const related = slash(relative(dir, i.from).replace(/\.ts(x)?$/, ""));
|
||||
return !related.startsWith(".") ? `./${related}` : related;
|
||||
}
|
||||
return i.from;
|
||||
}
|
||||
});
|
||||
const currentDTS = parseDTS(currentContent);
|
||||
if (options.vueTemplate) {
|
||||
currentContent = currentContent.replace(
|
||||
componentCustomPropertiesReg,
|
||||
($1) => `interface GlobalComponents {}
|
||||
${$1}`
|
||||
);
|
||||
}
|
||||
if (originalDTS) {
|
||||
Object.keys(currentDTS).forEach((key) => {
|
||||
originalDTS[key] = currentDTS[key];
|
||||
});
|
||||
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
|
||||
return currentContent.replace(dtsReg, () => `declare global {
|
||||
${dtsList.join("\n")}
|
||||
}`);
|
||||
}
|
||||
return currentContent;
|
||||
}
|
||||
async function parseESLint() {
|
||||
if (!eslintrc.filepath)
|
||||
return {};
|
||||
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
|
||||
return {};
|
||||
const configStr = existsSync(eslintrc.filepath) ? await fs.readFile(eslintrc.filepath, "utf-8") : "";
|
||||
const config = JSON.parse(configStr || '{ "globals": {} }');
|
||||
return config.globals;
|
||||
}
|
||||
async function generateESLint() {
|
||||
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
|
||||
}
|
||||
async function generateBiomeLint() {
|
||||
return generateBiomeLintConfigs(await unimport.getImports());
|
||||
}
|
||||
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
|
||||
async function writeFile(filePath, content = "") {
|
||||
await fs.mkdir(dirname(filePath), { recursive: true });
|
||||
return await fs.writeFile(filePath, content, "utf-8");
|
||||
}
|
||||
let lastDTS;
|
||||
let lastESLint;
|
||||
let lastBiomeLint;
|
||||
let lastUnimportItems;
|
||||
async function writeConfigFiles() {
|
||||
const promises = [];
|
||||
if (dts) {
|
||||
promises.push(
|
||||
generateDTS(dts).then((content) => {
|
||||
if (content !== lastDTS) {
|
||||
lastDTS = content;
|
||||
return writeFile(dts, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (eslintrc.enabled && eslintrc.filepath) {
|
||||
const filepath = eslintrc.filepath;
|
||||
promises.push(
|
||||
generateESLint().then(async (content) => {
|
||||
if (filepath.endsWith(".cjs"))
|
||||
content = `module.exports = ${content}`;
|
||||
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
|
||||
content = `export default ${content}`;
|
||||
content = `${content}
|
||||
`;
|
||||
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
|
||||
lastESLint = content;
|
||||
return writeFile(eslintrc.filepath, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (biomelintrc.enabled) {
|
||||
promises.push(
|
||||
generateBiomeLint().then((content) => {
|
||||
if (content !== lastBiomeLint) {
|
||||
lastBiomeLint = content;
|
||||
return writeFile(biomelintrc.filepath, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
if (dumpUnimportItems) {
|
||||
promises.push(
|
||||
unimport.getImports().then((items) => {
|
||||
if (!dumpUnimportItems)
|
||||
return;
|
||||
const content = JSON.stringify(items, null, 2);
|
||||
if (content !== lastUnimportItems) {
|
||||
lastUnimportItems = content;
|
||||
return writeFile(dumpUnimportItems, content);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
return Promise.all(promises);
|
||||
}
|
||||
async function scanDirs() {
|
||||
await unimport.modifyDynamicImports(async (imports) => {
|
||||
const exports_ = await unimport.scanImportsFromDir();
|
||||
exports_.forEach((i) => i.__source = "dir");
|
||||
return modifyDefaultExportsAlias([
|
||||
...imports.filter((i) => i.__source !== "dir"),
|
||||
...exports_
|
||||
], options);
|
||||
});
|
||||
writeConfigFilesThrottled();
|
||||
}
|
||||
async function transform(code, id) {
|
||||
await importsPromise;
|
||||
const s = new MagicString(code);
|
||||
await unimport.injectImports(s, id);
|
||||
if (!s.hasChanged())
|
||||
return;
|
||||
writeConfigFilesThrottled();
|
||||
return {
|
||||
code: s.toString(),
|
||||
map: s.generateMap({ source: id, includeContent: true, hires: true })
|
||||
};
|
||||
}
|
||||
return {
|
||||
root,
|
||||
dirs,
|
||||
filter,
|
||||
scanDirs,
|
||||
writeConfigFiles,
|
||||
writeConfigFilesThrottled,
|
||||
transform,
|
||||
generateDTS,
|
||||
generateESLint,
|
||||
unimport
|
||||
};
|
||||
}
|
||||
async function flattenImports(map) {
|
||||
const promises = await Promise.all(toArray(map).map(async (definition) => {
|
||||
if (typeof definition === "string") {
|
||||
if (!presets[definition])
|
||||
throw new Error(`[auto-import] preset ${definition} not found`);
|
||||
const preset = presets[definition];
|
||||
definition = typeof preset === "function" ? preset() : preset;
|
||||
}
|
||||
if ("from" in definition && "imports" in definition) {
|
||||
return await resolvePreset(definition);
|
||||
} else {
|
||||
const resolved = [];
|
||||
for (const mod of Object.keys(definition)) {
|
||||
for (const id of definition[mod]) {
|
||||
const meta = {
|
||||
from: mod
|
||||
};
|
||||
if (Array.isArray(id)) {
|
||||
meta.name = id[0];
|
||||
meta.as = id[1];
|
||||
} else {
|
||||
meta.name = id;
|
||||
meta.as = id;
|
||||
}
|
||||
resolved.push(meta);
|
||||
}
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
}));
|
||||
return promises.flat();
|
||||
}
|
||||
function modifyDefaultExportsAlias(imports, options) {
|
||||
if (options.defaultExportByFilename) {
|
||||
imports.forEach((i) => {
|
||||
var _a, _b, _c;
|
||||
if (i.name === "default")
|
||||
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
|
||||
});
|
||||
}
|
||||
return imports;
|
||||
}
|
||||
|
||||
// src/core/unplugin.ts
|
||||
var unplugin_default = createUnplugin((options) => {
|
||||
let ctx = createContext(options);
|
||||
return {
|
||||
name: "unplugin-auto-import",
|
||||
enforce: "post",
|
||||
transformInclude(id) {
|
||||
return ctx.filter(id);
|
||||
},
|
||||
async transform(code, id) {
|
||||
return ctx.transform(code, id);
|
||||
},
|
||||
async buildStart() {
|
||||
await ctx.scanDirs();
|
||||
},
|
||||
async buildEnd() {
|
||||
await ctx.writeConfigFiles();
|
||||
},
|
||||
vite: {
|
||||
async config(config) {
|
||||
var _a;
|
||||
if (options.viteOptimizeDeps === false)
|
||||
return;
|
||||
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
|
||||
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && isPackageExists2(i)));
|
||||
if (!imports.size)
|
||||
return;
|
||||
return {
|
||||
optimizeDeps: {
|
||||
include: [...imports]
|
||||
}
|
||||
};
|
||||
},
|
||||
async handleHotUpdate({ file }) {
|
||||
var _a;
|
||||
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => pm.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
|
||||
await ctx.scanDirs();
|
||||
},
|
||||
async configResolved(config) {
|
||||
if (ctx.root !== config.root) {
|
||||
ctx = createContext(options, config.root);
|
||||
await ctx.scanDirs();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
export {
|
||||
unplugin_default
|
||||
};
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
||||
|
||||
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
|
||||
require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
// src/esbuild.ts
|
||||
var esbuild_default = _chunkA6NGEVNDcjs.unplugin_default.esbuild;
|
||||
|
||||
|
||||
exports.default = esbuild_default;
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import { Options } from './types.cjs';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: (options?: Options) => any;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import { Options } from './types.js';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: (options?: Options) => any;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
unplugin_default
|
||||
} from "./chunk-WD3TZPPT.js";
|
||||
import "./chunk-DTT25XJ5.js";
|
||||
|
||||
// src/esbuild.ts
|
||||
var esbuild_default = unplugin_default.esbuild;
|
||||
export {
|
||||
esbuild_default as default
|
||||
};
|
||||
TongjiUniApp/node_modules/@dcloudio/vite-plugin-uni/node_modules/unplugin-auto-import/dist/index.cjs
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
||||
|
||||
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
|
||||
require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
|
||||
exports.default = _chunkA6NGEVNDcjs.unplugin_default;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import * as unplugin from 'unplugin';
|
||||
import { Options } from './types.cjs';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import * as unplugin from 'unplugin';
|
||||
import { Options } from './types.js';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import {
|
||||
unplugin_default
|
||||
} from "./chunk-WD3TZPPT.js";
|
||||
import "./chunk-DTT25XJ5.js";
|
||||
export {
|
||||
unplugin_default as default
|
||||
};
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
||||
|
||||
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
|
||||
require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
// src/nuxt.ts
|
||||
var _kit = require('@nuxt/kit');
|
||||
var nuxt_default = _kit.defineNuxtModule.call(void 0, {
|
||||
setup(options) {
|
||||
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
|
||||
_kit.addWebpackPlugin.call(void 0, _chunkA6NGEVNDcjs.unplugin_default.webpack(options));
|
||||
_kit.addVitePlugin.call(void 0, _chunkA6NGEVNDcjs.unplugin_default.vite(options));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
exports.default = nuxt_default;
|
||||
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import * as _nuxt_schema from '@nuxt/schema';
|
||||
import { Options } from './types.cjs';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
|
||||
|
||||
export { _default as default };
|
||||
TongjiUniApp/node_modules/@dcloudio/vite-plugin-uni/node_modules/unplugin-auto-import/dist/nuxt.d.ts
Generated
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import * as _nuxt_schema from '@nuxt/schema';
|
||||
import { Options } from './types.js';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: _nuxt_schema.NuxtModule<Options, Options, false>;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+17
@@ -0,0 +1,17 @@
|
||||
import {
|
||||
unplugin_default
|
||||
} from "./chunk-WD3TZPPT.js";
|
||||
import "./chunk-DTT25XJ5.js";
|
||||
|
||||
// src/nuxt.ts
|
||||
import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
|
||||
var nuxt_default = defineNuxtModule({
|
||||
setup(options) {
|
||||
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
|
||||
addWebpackPlugin(unplugin_default.webpack(options));
|
||||
addVitePlugin(unplugin_default.vite(options));
|
||||
}
|
||||
});
|
||||
export {
|
||||
nuxt_default as default
|
||||
};
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
||||
|
||||
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
|
||||
require('./chunk-6BSQ6ZKC.cjs');
|
||||
|
||||
// src/rollup.ts
|
||||
var rollup_default = _chunkA6NGEVNDcjs.unplugin_default.rollup;
|
||||
|
||||
|
||||
exports.default = rollup_default;
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import { Options } from './types.cjs';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: (options?: Options) => any;
|
||||
|
||||
export { _default as default };
|
||||
Generated
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import { Options } from './types.js';
|
||||
import '@antfu/utils';
|
||||
import 'unimport';
|
||||
import 'unplugin-utils';
|
||||
|
||||
declare const _default: (options?: Options) => any;
|
||||
|
||||
export { _default as default };
|
||||
TongjiUniApp/node_modules/@dcloudio/vite-plugin-uni/node_modules/unplugin-auto-import/dist/rollup.js
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
unplugin_default
|
||||
} from "./chunk-WD3TZPPT.js";
|
||||
import "./chunk-DTT25XJ5.js";
|
||||
|
||||
// src/rollup.ts
|
||||
var rollup_default = unplugin_default.rollup;
|
||||
export {
|
||||
rollup_default as default
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user