Skip to content

Commit

Permalink
fix: support hashbangs in commonjs modules (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
privatenumber authored Oct 4, 2023
1 parent 7b751d0 commit 7fde56a
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/utils/get-rollup-configs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { esbuildTransform, esbuildMinify } from './rollup-plugins/esbuild.js';
import { externalizeNodeBuiltins } from './rollup-plugins/externalize-node-builtins.js';
import { patchBinary } from './rollup-plugins/patch-binary.js';
import { resolveTypescriptMjsCts } from './rollup-plugins/resolve-typescript-mjs-cjs.js';
import { stripHashbang } from './rollup-plugins/strip-hashbang.js';
import { getExternalDependencies } from './parse-package-json/get-external-dependencies.js';

type Options = {
Expand Down Expand Up @@ -92,6 +93,7 @@ const getConfig = {
})]
: []
),
stripHashbang(),
commonjs(),
json(),
esbuildTransform(esbuildConfig),
Expand Down
21 changes: 21 additions & 0 deletions src/utils/rollup-plugins/strip-hashbang.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { Plugin } from 'rollup';
import MagicString from 'magic-string';

const hashbangPattern = /^#!.*/;
export const stripHashbang = (): Plugin => ({
name: 'strip-hashbang',

transform: (code) => {
if (!hashbangPattern.test(code)) {
return null;
}

const transformed = new MagicString(code);
transformed.replace(hashbangPattern, '');

return {
code: transformed.toString(),
map: transformed.generateMap({ hires: true }),
};
},
});
2 changes: 2 additions & 0 deletions tests/fixture-package/src/cjs.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#! /usr/bin/env node

console.log('side effect');

module.exports = function sayHello(name) {
Expand Down
2 changes: 2 additions & 0 deletions tests/fixture-package/src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#! /usr/bin/env node

import value from './value.js';
import { Component } from './component.tsx';
import { sayHello } from './utils.js';
Expand Down
2 changes: 2 additions & 0 deletions tests/fixture-package/src/value.js
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
#! /usr/bin/env node

export default 1234;

0 comments on commit 7fde56a

Please sign in to comment.