Add improved logic for loading Node.js module (fixes #118)

This commit is contained in:
Vanilagy
2025-09-16 21:13:32 +02:00
parent 1bb3c0e262
commit 555006b9c3
5 changed files with 25 additions and 5 deletions
+4
View File
@@ -22,6 +22,10 @@
"dist",
"src"
],
"browser": {
"./dist/modules/src/node.js": false,
"./src/node.ts": false
},
"sideEffects": false,
"scripts": {
"build": "./build.sh",
+1 -1
View File
@@ -24,7 +24,7 @@ const walkDir = (dir: string) => {
const fixFile = (filePath: string) => {
const content = fs.readFileSync(filePath, 'utf8');
const fixed = content.replace(
/(\s+from\s+['"])([^'"]*)(['"])/g,
/(\s+from\s+['"])(\.[^'"]*)(['"])/g, // This only matches relative imports
'$1$2.js$3',
);
+3
View File
@@ -16,6 +16,9 @@ const createVariants = async (
entryPoints: [entryPoint],
bundle: true,
logLevel: 'info',
logOverride: {
'import-is-undefined': 'silent', // Warning caused by the disabled "node.ts" import
},
banner: {
js: `/*!
* Copyright (c) 2025-present, Vanilagy and contributors
+11
View File
@@ -0,0 +1,11 @@
/*!
* Copyright (c) 2025-present, Vanilagy and contributors
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
// This file contains Node.js-specific code that does not run in a browser.
export * as fs from 'node:fs/promises';
+6 -4
View File
@@ -18,6 +18,9 @@ import {
toDataView,
toUint8Array,
} from './misc';
import * as nodeAlias from './node';
const node = nodeAlias; // Aliasing it prevents some bundler warnings
export type ReadResult = {
bytes: Uint8Array;
@@ -548,9 +551,7 @@ export class FilePathSource extends Source {
// Let's back this source with a StreamSource, makes the implementation very simple
this._streamSource = new StreamSource({
getSize: async () => {
const FS_MODULE_NAME = 'node:fs/promises';
const fs = await import(/* @vite-ignore */ FS_MODULE_NAME) as typeof import('node:fs/promises');
fileHandle = await fs.open(filePath, 'r');
fileHandle = await node.fs.open(filePath, 'r');
const stats = await fileHandle.stat();
return stats.size;
@@ -558,8 +559,9 @@ export class FilePathSource extends Source {
read: async (start, end) => {
assert(fileHandle);
const buffer = Buffer.alloc(end - start);
const buffer = new Uint8Array(end - start);
await fileHandle.read(buffer, 0, end - start, start);
return buffer;
},
maxCacheSize: options.maxCacheSize,