Path: blob/main/build/vite/rollup-url-to-module-plugin/index.mjs
4772 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45/**6* @type {() => import('rollup').Plugin}7*/8export function urlToEsmPlugin() {9return {10name: 'import-meta-url',11async transform(code, id) {12if (this.environment?.mode === 'dev') {13return;14}1516// Look for `new URL(..., import.meta.url)` patterns.17const regex = /new\s+URL\s*\(\s*(['"`])(.*?)\1\s*,\s*import\.meta\.url\s*\)?/g;1819let match;20let modified = false;21let result = code;22let offset = 0;2324while ((match = regex.exec(code)) !== null) {25let path = match[2];2627if (!path.startsWith('.') && !path.startsWith('/')) {28path = `./${path}`;29}30const resolved = await this.resolve(path, id);3132if (!resolved) {33continue;34}3536// Add the file as an entry point37const refId = this.emitFile({38type: 'chunk',39id: resolved.id,40});4142const start = match.index;43const end = start + match[0].length;4445const replacement = `import.meta.ROLLUP_FILE_URL_OBJ_${refId}`;4647result = result.slice(0, start + offset) + replacement + result.slice(end + offset);48offset += replacement.length - (end - start);49modified = true;50}5152if (!modified) {53return null;54}5556return {57code: result,58map: null59};60}61};62}636465