Skip to content
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

feat: source-map using MagicString #46

Closed
wants to merge 2 commits into from
Closed
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
6 changes: 4 additions & 2 deletions packages/vite-plugin-commonjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"version": "1.0.3",
"description": "A vite plugin that support commonjs to esm in vite",
"scripts": {
"build": "tsc -p tsconfig.json"
"build": "tsc -p tsconfig.json",
"dev": "tsc -p tsconfig.json --watch"
},
"main": "lib/index.js",
"files": [
Expand All @@ -24,7 +25,8 @@
},
"homepage": "https://github.com/originjs/vite-plugins/tree/main/packages/vite-plugin-commonjs",
"dependencies": {
"esbuild": "^0.14.14"
"esbuild": "^0.14.14",
"magic-string": "^0.30.0"
},
"devDependencies": {
"@types/node": "^15.12.2",
Expand Down
19 changes: 11 additions & 8 deletions packages/vite-plugin-commonjs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { transformRequire, isCommonJS } from "./lib";
import * as fs from "fs";
import { Plugin } from "vite";
import createFilter from "./filter";
import MagicString from 'magic-string';

export type Options = {
include?: string | string[] | undefined;
Expand All @@ -25,16 +26,17 @@ export function viteCommonjs(
return null;
}

let result = transformRequire(code, id);
const ms = new MagicString(code);
const replaced = transformRequire(ms, id);

if (id.indexOf("/node_modules/.vite/") == -1 && isCommonJS(code)) {
return transformSync(result.code, { format: "esm" });
return transformSync(ms.toString(), { format: "esm" });
}

if (result.replaced) {
if (replaced) {
return {
code: result.code,
map: null,
code: ms.toString(),
map: ms.generateMap().toString(),
warnings: null,
};
}
Expand All @@ -54,10 +56,11 @@ export function esbuildCommonjs(include: string[] = []) {
},
async ({ path: id }) => {
const code = fs.readFileSync(id).toString();
let result = transformRequire(code, id);
if (result.replaced) {
const ms = new MagicString(code);
const replaced = transformRequire(ms, id);
if (replaced) {
return {
contents: result.code,
contents: ms.toString(),
loader: "js",
};
}
Expand Down
40 changes: 15 additions & 25 deletions packages/vite-plugin-commonjs/src/lib.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,23 @@
import MagicString from 'magic-string';

const commonJSRegex: RegExp = /\b(module\.exports|exports\.\w+|exports\s*=\s*|exports\s*\[.*\]\s*=\s*)/;
const requireRegex: RegExp = /(?<!\.)\b_{0,2}require\s*\(\s*(["'`].*?["'`])\s*\)/g;
const IMPORT_STRING_PREFIX: String = "__require_for_vite";
const multilineCommentsRegex = /\/\*(.|[\r\n])*?\*\//gm
const singleCommentsRegex = /([^\:])\/\/.*/g

export interface TransformRequireResult {
code: string;
replaced: boolean;
}

export function transformRequire(code: string, id: string): TransformRequireResult {
export function transformRequire(ms: MagicString, id: string): boolean {
let replaced = false;
// skip if has no require
if (!/require/.test(code)) {
return {
replaced,
code,
};
if (!/require/.test(ms.toString())) {
return replaced
}
// empty multiline comments
code = removeComments(code, multilineCommentsRegex, '/* */');
removeComments(ms, multilineCommentsRegex, '/* */');
// remove singleline comments
code = removeComments(code, singleCommentsRegex);
removeComments(ms, singleCommentsRegex);

const requireMatches = code.matchAll(requireRegex);
const requireMatches = ms.toString().matchAll(requireRegex);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These steps might not work correctly, because the modified string is being returned here, but replacements happen in the original string.

This should probably be improved, but I feel this code needs to be modified anyway (with a proper JS parser instead of regex).

let importsString = '';
let packageName = '';
for (let item of requireMatches) {
Expand All @@ -34,28 +28,25 @@ export function transformRequire(code: string, id: string): TransformRequireResu
replaced = true;
packageName = `${IMPORT_STRING_PREFIX}_${randomString(6)}`;
importsString += `import * as ${packageName} from ${item[1].replace(/`/g, `'`)};\n`;
code = code.replace(item[0], `(${packageName}.default || ${packageName})`);
ms.replace(item[0], `(${packageName}.default || ${packageName})`);
}

if (replaced) {
code = importsString + code;
ms.prepend(importsString);
}
return {
replaced,
code,
};
return replaced;
}

export function isCommonJS(code: string): boolean {
return commonJSRegex.test(code);
}

function removeComments(
code: string,
ms: MagicString,
exp: RegExp,
replaceValue?: string
): string {
const matches = code.matchAll(exp);
): void {
const matches = ms.toString().matchAll(exp);
let matcheStr: string;
for (let item of matches) {
matcheStr = item[0];
Expand All @@ -65,9 +56,8 @@ function removeComments(
if (!replaceValue) {
replaceValue = item[1] || '';
}
code = code.replace(matcheStr, replaceValue);
ms.replace(matcheStr, replaceValue);
}
return code;
}

function randomString(length: number): string {
Expand Down