Skip to content

feat: Add support for importing external ES Modules #221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion packages/vite-plugin-monkey/src/node/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ export const resolvedOption = (
Object.entries(externalGlobals2).forEach((s) => externalGlobals.push(s));
}

const userExternalModules = build?.externalModules ?? {};
const externalModules: [string, string | Mod2UrlFn][] = [];
if (userExternalModules instanceof Array) {
userExternalModules.forEach((s) => externalModules.push(s));
} else {
Object.entries(userExternalModules).forEach((s) => externalModules.push(s));
}

const { grant = [], $extra = [] } = pluginOption.userscript ?? {};
let {
name = {},
Expand Down Expand Up @@ -300,9 +308,11 @@ export const resolvedOption = (
fileName,
metaFileName: metaFileFc ? () => metaFileFc(fileName) : undefined,
autoGrant: build.autoGrant ?? true,
externalGlobals: externalGlobals,
externalGlobals,
externalModules,
externalResource: externalResource2,
},
importsList: {},
collectRequireUrls: [],
collectResource: {},
globalsPkg2VarName: {},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ export const externalGlobalsPlugin = (
build: {
rollupOptions: {
external(source, _importer, _isResolved) {
return source in globalsPkg2VarName;
return (
source in finalOption.globalsPkg2VarName ||
source in finalOption.importsList
);
},
// output: {
// globals: globalsPkg2VarName,
Expand Down
42 changes: 42 additions & 0 deletions packages/vite-plugin-monkey/src/node/plugins/externalModules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Plugin } from 'vite';
import type { FinalMonkeyOption } from '../types';
import { getModuleRealInfo } from '../_util';

export const externalModulesPlugin = (
finalOption: FinalMonkeyOption,
): Plugin => {
const { importsList } = finalOption;
return {
name: 'monkey:externalModules',
enforce: 'pre',
apply: 'build',
async config() {
for (const [moduleName, varName2LibUrl] of finalOption.build
.externalModules) {
const { name, version } = await getModuleRealInfo(moduleName);

if (typeof varName2LibUrl == 'string') {
importsList[moduleName] = varName2LibUrl;
} else if (typeof varName2LibUrl == 'function') {
importsList[moduleName] = await varName2LibUrl(
version,
name,
moduleName,
);
}
}
return {
build: {
rollupOptions: {
external(source, _importer, _isResolved) {
return (
source in finalOption.globalsPkg2VarName ||
source in finalOption.importsList
);
},
},
},
};
},
};
};
55 changes: 54 additions & 1 deletion packages/vite-plugin-monkey/src/node/plugins/finalBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,55 @@ export const finalBundlePlugin = (finalOption: FinalMonkeyOption): Plugin => {

const tlaIdentifier = lazyValue(() => findSafeTlaIdentifier(rawBundle));

const transformImports = (code: string) => {
const modulesList = finalOption.importsList;
const modules = Object.keys(modulesList);
const modulesRegex = new RegExp(`^(${modules.join('|')})(/|$)`);

if (!modules.length) return code;

// https://stackoverflow.com/questions/52086611/regex-for-matching-js-import-statements
const importRegex =
/import(\s*(?:[^\n;{}]+\s*,?)?(?:\s*\{(?:\s*[^\s"'{}]+\s*,?)+\})?\s*)from\s*(['"])([^'"\n]+)(?:['"])/g;
const result = code.replace(
importRegex,
(match, imports: string, _quote, pkg: string) => {
if (modulesRegex.test(pkg)) {
const namedImports = [...imports.matchAll(/\{([^}]*)\}/g)]
.flatMap((m) => m[1].trim().split(','))
.map((s) => s.trim().replace(/\sas\s/, ':'))
.filter((s) => s);
const nonNamedImports = imports
.replace(/\{[^{}]*\}/g, '')
.trim()
.split(',')
.map((s) => s.trim())
.filter((s) => s);

const url = modulesList[pkg];
let res = '';

if (namedImports.length > 0) {
res += `const {${namedImports.join(',')}} = await import("${url}");`;
}

for (const currentImport of nonNamedImports) {
if (currentImport.match(/\sas\s/)) {
res += `const ${currentImport.split(/\sas\s/)[1].trim()} = await import("${url}");`;
} else {
res += `const ${currentImport} = await import("${url}").then((m) => m.default);`;
}
}

return res;
}
return match;
},
);

return result;
};

const buildResult = (await build({
logLevel: 'error',
configFile: false,
Expand Down Expand Up @@ -95,6 +144,7 @@ export const finalBundlePlugin = (finalOption: FinalMonkeyOption): Plugin => {
) ?? [];
if (chunk && chunk.type == 'chunk' && k) {
usedModules.add(k);
chunk.code = transformImports(chunk.code);
if (!hasDynamicImport) {
const ch = transformTlaToIdentifier(
this,
Expand Down Expand Up @@ -125,7 +175,10 @@ export const finalBundlePlugin = (finalOption: FinalMonkeyOption): Plugin => {
target: 'esnext',
rollupOptions: {
external(source) {
return source in finalOption.globalsPkg2VarName;
return (
source in finalOption.globalsPkg2VarName ||
source in finalOption.importsList
);
},
output: {
globals: finalOption.globalsPkg2VarName,
Expand Down
2 changes: 2 additions & 0 deletions packages/vite-plugin-monkey/src/node/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { externalResourcePlugin } from './externalResource';
import { finalBundlePlugin } from './finalBundle';
import { perviewPlugin } from './perview';
import { redirectClientPlugin } from './redirectClient';
import { externalModulesPlugin } from './externalModules';

const monkeyPluginList = [
// only serve
Expand All @@ -21,6 +22,7 @@ const monkeyPluginList = [
externalLoaderPlugin,
externalResourcePlugin,
externalGlobalsPlugin,
externalModulesPlugin,

// only build, final build
finalBundlePlugin,
Expand Down
13 changes: 13 additions & 0 deletions packages/vite-plugin-monkey/src/node/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ export type ExternalGlobals =
| Record<string, IArray<string | Mod2UrlFn>>
| [string, IArray<string | Mod2UrlFn>][];

export type ExternalModules =
| Record<string, string | Mod2UrlFn>
| [string, string | Mod2UrlFn][];

export type ExternalResource = Record<
string,
| string
Expand Down Expand Up @@ -103,6 +107,7 @@ export interface FinalMonkeyOption {
metaFileName?: () => string;
autoGrant: boolean;
externalGlobals: [string, IArray<string | Mod2UrlFn>][];
externalModules: [string, string | Mod2UrlFn][];
externalResource: Record<
string,
{
Expand All @@ -114,6 +119,7 @@ export interface FinalMonkeyOption {
>;
};
collectRequireUrls: string[];
importsList: Record<string, string>;
collectResource: Record<string, string>;
globalsPkg2VarName: Record<string, string>;
requirePkgList: { moduleName: string; url: string }[];
Expand Down Expand Up @@ -243,6 +249,13 @@ export interface MonkeyOption {
*/
externalGlobals?: ExternalGlobals;

/**
* same as `externalGlobals`, but the imports will be treated as modules
*
* @see https://github.com/lisonge/vite-plugin-monkey/issues/180
*/
externalModules?: ExternalModules;

/**
* according to final code bundle, auto inject GM_* or GM.* to userscript comment grant
*
Expand Down