Skip to content

Instantly share code, notes, and snippets.

@KernelDeimos
Created July 25, 2022 03:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KernelDeimos/f72091e44b3055e1193461eb1c0740a3 to your computer and use it in GitHub Desktop.
Save KernelDeimos/f72091e44b3055e1193461eb1c0740a3 to your computer and use it in GitHub Desktop.
Something awful I had to do
/*
The situation was as follows:
- A project has a number of `.js` files under `dist/`
- they're bundled by webpack for the browser
- they're ES6 modules
- A `tools` folder contians commonjs `.js` files
- Want to run tests for files in `dist/` from a node script
- test.js fails because it can't import ES6 modules
Things that didn't work:
- setting { "type": "module" } in package.json
- commonjs files in `tools` would stop working
- various flags I tried in node.js
- migrating commonjs files to es6 modules
- why should I have to?
- renaming all the files in `dist/` to `.mjs`
- fuck that
*/
import { spawn } from 'child_process';
import * as fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const tempPackage = path.join(__dirname, '../../dist/package.json');
fs.writeFileSync(tempPackage, `{ "type": "module" }\n`);
const s = spawn('node', [
'--experimental-specifier-resolution=node',
path.join(__dirname, 'test.js')]);
s.stdout.on('data', function (msg) {
process.stdout.write(msg, (_err) => {});
})
s.stderr.on('data', function (msg) {
process.stderr.write(msg, (_err) => {});
})
s.on('close', () => {
// Oh yeah, need to wait a second or the hotloader
// won't realize it's gone... EVEN AFTER subsequent
// saves to other files.
setTimeout(() => {
fs.unlinkSync(tempPackage)
}, 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment