Skip to content

Commit

Permalink
[WiP] Remove require() in favor of import
Browse files Browse the repository at this point in the history
  • Loading branch information
kleisauke committed Dec 9, 2023
1 parent aa6465c commit d52171f
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 71 deletions.
7 changes: 0 additions & 7 deletions src/library.js
Original file line number Diff line number Diff line change
Expand Up @@ -2345,13 +2345,6 @@ addToLibrary({
emscripten_random: () => Math.random(),

emscripten_get_now: `;
#if ENVIRONMENT_MAY_BE_NODE && MIN_NODE_VERSION < 160000
// The performance global was added to node in v16.0.0:
// https://nodejs.org/api/globals.html#performance
if (ENVIRONMENT_IS_NODE) {
global.performance = require('perf_hooks').performance;
}
#endif
#if PTHREADS && !AUDIO_WORKLET
// Pthreads need their clocks synchronized to the execution of the main
// thread, so, when using them, make sure to adjust all timings to the
Expand Down
2 changes: 1 addition & 1 deletion src/library_pthread.js
Original file line number Diff line number Diff line change
Expand Up @@ -709,7 +709,7 @@ var LibraryPThread = {

emscripten_num_logical_cores: () => {
#if ENVIRONMENT_MAY_BE_NODE
if (ENVIRONMENT_IS_NODE) return require('os').cpus().length;
ENVIRONMENT_IS_NODE ? availableParallelism() :
#endif
return navigator['hardwareConcurrency'];
},
Expand Down
7 changes: 3 additions & 4 deletions src/library_wasm_worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -250,12 +250,11 @@ if (ENVIRONMENT_IS_WASM_WORKER) {
_wasmWorkers[id].postMessage({'_wsc': funcPtr, 'x': readEmAsmArgs(sigPtr, varargs) });
},

emscripten_navigator_hardware_concurrency: () => {
emscripten_navigator_hardware_concurrency: () =>
#if ENVIRONMENT_MAY_BE_NODE
if (ENVIRONMENT_IS_NODE) return require('os').cpus().length;
ENVIRONMENT_IS_NODE ? availableParallelism() :
#endif
return navigator['hardwareConcurrency'];
},
navigator['hardwareConcurrency'],

emscripten_atomics_is_lock_free: (width) => {
return Atomics.isLockFree(width);
Expand Down
10 changes: 0 additions & 10 deletions src/proxyClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,6 @@
#endif

#if ENVIRONMENT_MAY_BE_NODE
var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions == 'object' && typeof process.versions.node == 'string';
if (ENVIRONMENT_IS_NODE) {
let nodeWorkerThreads;
try {
nodeWorkerThreads = require('worker_threads');
} catch (e) {
console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?');
throw e;
}
global.Worker = nodeWorkerThreads.Worker;
var Module = Module || {}
} else
#endif
Expand Down
76 changes: 43 additions & 33 deletions src/shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,28 +212,56 @@ if (ENVIRONMENT_IS_NODE) {
}
#endif

// `require()` is no-op in an ESM module, use `createRequire()` to construct
// the require()` function. This is only necessary for multi-environment
// builds, `-sENVIRONMENT=node` emits a static import declaration instead.
// TODO: Swap all `require()`'s with `import()`'s?
#if EXPORT_ES6 && ENVIRONMENT_MAY_BE_WEB
const { createRequire } = await import('module');
/** @suppress{duplicate} */
var require = createRequire(import.meta.url);
#endif
#if EXPORT_ES6

#if ENVIRONMENT_MAY_BE_WEB
// These modules will usually be used on Node.js. Load them eagerly to avoid
// the complexity of lazy-loading.
var fs = require('fs');
var nodePath = require('path');
// the complexity of lazy-loading. This is only necessary for multi-environment
// builds, `-sENVIRONMENT=node` emits a static import declaration instead.
var fs = await import('node:fs');
var nodePath = await import('node:path');
const { fileURLToPath } = await import('node:url');
#if PTHREADS || WASM_WORKERS
var { Worker } = await import('node:worker_threads');
#if MIN_NODE_VERSION < 181400
const { cpus } = await import('node:os');
var availableParallelism = () => cpus().length;
#else
var { availableParallelism } = await import('node:os');
#endif // MIN_NODE_VERSION < 181400
#endif // PTHREADS || WASM_WORKERS
#if MIN_NODE_VERSION < 160000
// The performance global was added to node in v16.0.0:
// https://nodejs.org/api/globals.html#performance
var { performance } = await import('node:perf_hooks');
#endif // MIN_NODE_VERSION < 160000
#endif // ENVIRONMENT_MAY_BE_WEB

#if EXPORT_ES6
// EXPORT_ES6 + ENVIRONMENT_IS_NODE always requires use of import.meta.url,
// since there's no way getting the current absolute path of the module when
// support for that is not available.
scriptDirectory = require('url').fileURLToPath(new URL('./', import.meta.url)); // includes trailing slash
scriptDirectory = fileURLToPath(new URL('./', import.meta.url)); // includes trailing slash

#else // !EXPORT_ES6
var fs = require('node:fs');
var nodePath = require('node:path');
#if PTHREADS || WASM_WORKERS
var { Worker } = require('node:worker_threads');
#if MIN_NODE_VERSION < 181400
const { cpus } = require('node:os');
var availableParallelism = () => cpus().length;
#else
var { availableParallelism } = require('node:os');
#endif // MIN_NODE_VERSION < 181400
#endif // PTHREADS || WASM_WORKERS
#if MIN_NODE_VERSION < 160000
// The performance global was added to node in v16.0.0:
// https://nodejs.org/api/globals.html#performance
var { performance } = require('node:perf_hooks');
#endif // MIN_NODE_VERSION < 160000

scriptDirectory = __dirname + '/';
#endif
#endif // EXPORT_ES6

#include "node_shell_read.js"

Expand Down Expand Up @@ -282,17 +310,6 @@ if (ENVIRONMENT_IS_NODE) {

Module['inspect'] = () => '[Emscripten Module object]';

#if PTHREADS || WASM_WORKERS
let nodeWorkerThreads;
try {
nodeWorkerThreads = require('worker_threads');
} catch (e) {
console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?');
throw e;
}
global.Worker = nodeWorkerThreads.Worker;
#endif

#if WASM == 2
// If target shell does not support Wasm, load the JS version of the code.
if (typeof WebAssembly == 'undefined') {
Expand Down Expand Up @@ -444,13 +461,6 @@ if (!ENVIRONMENT_IS_AUDIO_WORKLET)
}

#if ENVIRONMENT_MAY_BE_NODE && PTHREADS
if (ENVIRONMENT_IS_NODE) {
// Polyfill the performance object, which emscripten pthreads support
// depends on for good timing.
if (typeof performance == 'undefined') {
global.performance = require('perf_hooks').performance;
}
}

// Set up the out() and err() hooks, which are how we can print to stdout or
// stderr, respectively.
Expand Down
2 changes: 1 addition & 1 deletion src/shell_minimal.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ if (ENVIRONMENT_IS_NODE && ENVIRONMENT_IS_SHELL) {
// Wasm or Wasm2JS loading:

if (ENVIRONMENT_IS_NODE) {
var fs = require('fs');
var fs = require('node:fs');
#if WASM == 2
if (typeof WebAssembly != 'undefined') Module['wasm'] = fs.readFileSync(__dirname + '/{{{ TARGET_BASENAME }}}.wasm');
else eval(fs.readFileSync(__dirname + '/{{{ TARGET_BASENAME }}}.wasm.js')+'');
Expand Down
8 changes: 3 additions & 5 deletions src/wasm_worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,19 @@ var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions
if (ENVIRONMENT_IS_NODE) {
// Create as web-worker-like an environment as we can.

var nodeWorkerThreads = require('worker_threads');

var parentPort = nodeWorkerThreads.parentPort;
var { Worker, parentPort } = require('node:worker_threads');

parentPort.on('message', (data) => typeof onmessage === "function" && onmessage({ data: data }));

var fs = require('fs');
var fs = require('node:fs');

Object.assign(global, {
self: global,
require,
location: {
href: __filename
},
Worker: nodeWorkerThreads.Worker,
Worker,
importScripts: (f) => (0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f),
postMessage: (msg) => parentPort.postMessage(msg),
performance: global.performance || { now: Date.now },
Expand Down
8 changes: 3 additions & 5 deletions src/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,11 @@ var ENVIRONMENT_IS_NODE = typeof process == 'object' && typeof process.versions
if (ENVIRONMENT_IS_NODE) {
// Create as web-worker-like an environment as we can.

var nodeWorkerThreads = require('worker_threads');

var parentPort = nodeWorkerThreads.parentPort;
var { Worker, parentPort } = require('node:worker_threads');

parentPort.on('message', (data) => onmessage({ data: data }));

var fs = require('fs');
var fs = require('node:fs');

Object.assign(global, {
self: global,
Expand All @@ -34,7 +32,7 @@ if (ENVIRONMENT_IS_NODE) {
__filename,
__dirname,
#endif
Worker: nodeWorkerThreads.Worker,
Worker,
importScripts: (f) => (0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f),
postMessage: (msg) => parentPort.postMessage(msg),
performance: global.performance || { now: Date.now },
Expand Down
27 changes: 22 additions & 5 deletions tools/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -2281,11 +2281,28 @@ def node_es6_imports():
return ''

# Use static import declaration if we only target Node.js
return '''
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
'''

static_import = '''
import fs from 'node:fs';
import { default as nodePath } from 'node:path';
import { fileURLToPath } from 'node:url';'''

if settings.PTHREADS or settings.WASM_WORKERS:
static_import += '''
import { Worker } from 'node:worker_threads';'''
if settings.MIN_NODE_VERSION < 181400:
static_import += '''
import { cpus } from 'node:os';
const availableParallelism = () => cpus().length;'''
else:
static_import += '''
import { availableParallelism } from 'node:os';'''
if settings.MIN_NODE_VERSION < 160000:
# The performance global was added to node in v16.0.0:
# https://nodejs.org/api/globals.html#performance
static_import += '''
import { performance } from 'node:perf_hooks';'''

return static_import

def modularize():
global final_js
Expand Down

0 comments on commit d52171f

Please sign in to comment.