Skip to content

Commit

Permalink
feat: support mts, cts, mjs and cts files in source code (#595)
Browse files Browse the repository at this point in the history
### Summary

currently these files get treated as assets and are copied over as is.
however this is not the correct behavior. this changes them to be trated
as source code.

in addition, the module syntax in .mts or .mjs files is preserved as is.

### Test plan

tested in a generated project by creating `.mts` and `.cts` files.
  • Loading branch information
satya164 authored Jul 23, 2024
1 parent 2a62bed commit d522793
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions packages/react-native-builder-bob/src/utils/compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ type Options = Input & {
exclude: string;
};

const sourceExt = /\.([cm])?[jt]sx?$/;

export default async function compile({
root,
source,
Expand Down Expand Up @@ -73,17 +75,15 @@ export default async function compile({
});
}

const outputExtension = '.js';

await Promise.all(
files.map(async (filepath) => {
const outputFilename = path
.join(output, path.relative(source, filepath))
.replace(/\.(jsx?|tsx?)$/, outputExtension);
.replace(sourceExt, '.$1js');

await fs.mkdirp(path.dirname(outputFilename));

if (!/\.(jsx?|tsx?)$/.test(filepath)) {
if (!sourceExt.test(filepath)) {
// Copy files which aren't source code
fs.copy(filepath, outputFilename);
return;
Expand All @@ -102,7 +102,15 @@ export default async function compile({
? null
: {
presets: [
[require.resolve('../../babel-preset'), { modules, esm }],
[
require.resolve('../../babel-preset'),
{
modules:
// If a file is explicitly marked as ESM, then preserve the syntax
/\.m[jt]s$/.test(filepath) ? 'preserve' : modules,
esm,
},
],
],
}),
});
Expand Down Expand Up @@ -136,18 +144,20 @@ export default async function compile({

const getGeneratedEntryPath = async () => {
if (pkg.source) {
const indexName =
path.basename(pkg.source).replace(/\.(jsx?|tsx?)$/, '') +
outputExtension;

const potentialPath = path.join(
output,
path.dirname(path.relative(source, path.join(root, pkg.source))),
indexName
);

if (await fs.pathExists(potentialPath)) {
return path.relative(root, potentialPath);
for (const ext of ['.js', '.cjs', '.mjs']) {
const indexName =
// The source field may not have an extension, so we add it instead of replacing directly
path.basename(pkg.source).replace(sourceExt, '') + ext;

const potentialPath = path.join(
output,
path.dirname(path.relative(source, path.join(root, pkg.source))),
indexName
);

if (await fs.pathExists(potentialPath)) {
return path.relative(root, potentialPath);
}
}
}

Expand Down

0 comments on commit d522793

Please sign in to comment.