Skip to content

Commit

Permalink
Add experimental transformer setting for disabling require() renaming (
Browse files Browse the repository at this point in the history
…#677)

Summary:
**Summary**

Adds a flag, `unstable_disableModuleWrapping`, that disables wrapping of JS modules and transforming `require(...)` calls to `$$_REQUIRE(dependencyMap[n], ...)`. This is required for plugging in third-party bundlers such as [esbuild](https://esbuild.github.io/).

**Test plan**

A test has been added to ensure that `require()` calls are untouched.

Pull Request resolved: #677

Reviewed By: GijsWeterings

Differential Revision: D29358450

Pulled By: motiz88

fbshipit-source-id: cf5c25f891fc2c2bf87af1e6aa4434db70dc2bb3
  • Loading branch information
tido64 authored and facebook-github-bot committed Jun 24, 2021
1 parent 25be2a8 commit 598de6f
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 9 deletions.
Expand Up @@ -131,6 +131,7 @@ Object {
"unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js",
"unstable_compactOutput": false,
"unstable_dependencyMapReservedName": null,
"unstable_disableModuleWrapping": false,
"unstable_disableNormalizePseudoGlobals": false,
"workerPath": "metro/src/DeltaBundler/Worker",
},
Expand Down Expand Up @@ -272,6 +273,7 @@ Object {
"unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js",
"unstable_compactOutput": false,
"unstable_dependencyMapReservedName": null,
"unstable_disableModuleWrapping": false,
"unstable_disableNormalizePseudoGlobals": false,
"workerPath": "metro/src/DeltaBundler/Worker",
},
Expand Down Expand Up @@ -413,6 +415,7 @@ Object {
"unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js",
"unstable_compactOutput": false,
"unstable_dependencyMapReservedName": null,
"unstable_disableModuleWrapping": false,
"unstable_disableNormalizePseudoGlobals": false,
"workerPath": "metro/src/DeltaBundler/Worker",
},
Expand Down Expand Up @@ -554,6 +557,7 @@ Object {
"unstable_collectDependenciesPath": "metro/src/ModuleGraph/worker/collectDependencies.js",
"unstable_compactOutput": false,
"unstable_dependencyMapReservedName": null,
"unstable_disableModuleWrapping": false,
"unstable_disableNormalizePseudoGlobals": false,
"workerPath": "metro/src/DeltaBundler/Worker",
},
Expand Down
1 change: 1 addition & 0 deletions packages/metro-config/src/defaults/index.js
Expand Up @@ -119,6 +119,7 @@ const getDefaultValues = (projectRoot: ?string): ConfigT => ({
unstable_collectDependenciesPath:
'metro/src/ModuleGraph/worker/collectDependencies.js',
unstable_dependencyMapReservedName: null,
unstable_disableModuleWrapping: false,
unstable_disableNormalizePseudoGlobals: false,
unstable_compactOutput: false,
},
Expand Down
42 changes: 42 additions & 0 deletions packages/metro-transform-worker/src/__tests__/index-test.js
Expand Up @@ -62,6 +62,7 @@ const baseConfig: JsTransformerConfig = {
'metro/src/ModuleGraph/worker/collectDependencies',
unstable_dependencyMapReservedName: null,
unstable_compactOutput: false,
unstable_disableModuleWrapping: false,
unstable_disableNormalizePseudoGlobals: false,
};

Expand Down Expand Up @@ -266,6 +267,27 @@ it('does not add "use strict" on non-modules', async () => {
);
});

it('preserves require() calls when module wrapping is disabled', async () => {
const contents = ['require("./c");'].join('\n');

const result = await Transformer.transform(
{
...baseConfig,
unstable_disableModuleWrapping: true,
},
'/root',
'local/file.js',
contents,
{
dev: true,
type: 'module',
},
);

expect(result.output[0].type).toBe('js/module');
expect(result.output[0].data.code).toBe('require("./c");');
});

it('reports filename when encountering unsupported dynamic dependency', async () => {
const contents = [
'require("./a");',
Expand Down Expand Up @@ -360,6 +382,26 @@ it('minifies a JSON file', async () => {
);
});

it('does not wrap a JSON file when disableModuleWrapping is enabled', async () => {
expect(
(
await Transformer.transform(
{
...baseConfig,
unstable_disableModuleWrapping: true,
},
'/root',
'local/file.json',
'arbitrary(code);',
{
dev: true,
type: 'module',
},
)
).output[0].data.code,
).toBe('module.exports = arbitrary(code);;');
});

it('transforms a script to JS source and bytecode', async () => {
const result = await Transformer.transform(
baseConfig,
Expand Down
41 changes: 32 additions & 9 deletions packages/metro-transform-worker/src/index.js
Expand Up @@ -36,7 +36,10 @@ const {
} = require('metro-source-map');
import type {TransformResultDependency} from 'metro/src/DeltaBundler';
import type {AllowOptionalDependencies} from 'metro/src/DeltaBundler/types.flow.js';
import type {DynamicRequiresBehavior} from 'metro/src/ModuleGraph/worker/collectDependencies';
import type {
DependencyTransformer,
DynamicRequiresBehavior,
} from 'metro/src/ModuleGraph/worker/collectDependencies';
import type {
BasicSourceMap,
FBSourceFunctionMap,
Expand Down Expand Up @@ -93,6 +96,7 @@ export type JsTransformerConfig = $ReadOnly<{|
allowOptionalDependencies: AllowOptionalDependencies,
unstable_collectDependenciesPath: string,
unstable_dependencyMapReservedName: ?string,
unstable_disableModuleWrapping: boolean,
unstable_disableNormalizePseudoGlobals: boolean,
unstable_compactOutput: boolean,
|}>;
Expand Down Expand Up @@ -257,6 +261,14 @@ const compileToBytecode = (
return HermesCompiler.compile(code, options);
};

const disabledDependencyTransformer: DependencyTransformer<mixed> = {
transformSyncRequire: () => void 0,
transformImportCall: () => void 0,
transformJSResource: () => void 0,
transformPrefetch: () => void 0,
transformIllegalDynamicRequire: () => void 0,
};

class InvalidRequireCallError extends Error {
innerError: InternalInvalidRequireCallError;
filename: string;
Expand Down Expand Up @@ -372,6 +384,10 @@ async function transformJS(
try {
const opts = {
asyncRequireModulePath: config.asyncRequireModulePath,
dependencyTransformer:
config.unstable_disableModuleWrapping === true
? disabledDependencyTransformer
: undefined,
dynamicRequires: getDynamicDepsBehavior(
config.dynamicDepsInPackages,
file.filename,
Expand All @@ -391,13 +407,17 @@ async function transformJS(
throw error;
}

({ast: wrappedAst} = JsFileWrapping.wrapModule(
ast,
importDefault,
importAll,
dependencyMapName,
config.globalPrefix,
));
if (config.unstable_disableModuleWrapping === true) {
wrappedAst = ast;
} else {
({ast: wrappedAst} = JsFileWrapping.wrapModule(
ast,
importDefault,
importAll,
dependencyMapName,
config.globalPrefix,
));
}
}

const minify =
Expand Down Expand Up @@ -540,7 +560,10 @@ async function transformJSON(
file: JSONFile,
{options, config, projectRoot}: TransformationContext,
): Promise<TransformResponse> {
let code = JsFileWrapping.wrapJson(file.code, config.globalPrefix);
let code =
config.unstable_disableModuleWrapping === true
? JsFileWrapping.jsonToCommonJS(file.code)
: JsFileWrapping.wrapJson(file.code, config.globalPrefix);
let map = [];

// TODO: When we can reuse transformJS for JSON, we should not derive `minify` separately.
Expand Down

0 comments on commit 598de6f

Please sign in to comment.