packager Module.js: remove extractRequires

Reviewed By: davidaurelio

Differential Revision: D4147275

fbshipit-source-id: 7c1d7d16f6b8164d7031963618aeab2857f5d497
This commit is contained in:
Jean Lauliac 2016-11-10 09:06:56 -08:00 committed by Facebook Github Bot
parent 9e61473172
commit f40aafac8a
7 changed files with 76 additions and 306 deletions

View File

@ -15,7 +15,6 @@ const TransformCache = require('../lib/TransformCache');
const crypto = require('crypto'); const crypto = require('crypto');
const docblock = require('./DependencyGraph/docblock'); const docblock = require('./DependencyGraph/docblock');
const extractRequires = require('./lib/extractRequires');
const invariant = require('invariant'); const invariant = require('invariant');
const isAbsolutePath = require('absolute-path'); const isAbsolutePath = require('absolute-path');
const jsonStableStringify = require('json-stable-stringify'); const jsonStableStringify = require('json-stable-stringify');
@ -26,8 +25,6 @@ import type Cache from './Cache';
import type ModuleCache from './ModuleCache'; import type ModuleCache from './ModuleCache';
import type FastFs from './fastfs'; import type FastFs from './fastfs';
export type Extractor = (sourceCode: string) => {deps: {sync: Array<string>}};
type TransformedCode = { type TransformedCode = {
code: string, code: string,
dependencies?: ?Array<string>, dependencies?: ?Array<string>,
@ -60,8 +57,7 @@ export type ConstructorArgs = {
fastfs: FastFs, fastfs: FastFs,
moduleCache: ModuleCache, moduleCache: ModuleCache,
cache: Cache, cache: Cache,
extractor: Extractor, transformCode: ?TransformCode,
transformCode: TransformCode,
transformCacheKey: ?string, transformCacheKey: ?string,
depGraphHelpers: DepGraphHelpers, depGraphHelpers: DepGraphHelpers,
options: Options, options: Options,
@ -75,8 +71,7 @@ class Module {
_fastfs: FastFs; _fastfs: FastFs;
_moduleCache: ModuleCache; _moduleCache: ModuleCache;
_cache: Cache; _cache: Cache;
_extractor: Extractor; _transformCode: ?TransformCode;
_transformCode: TransformCode;
_transformCacheKey: ?string; _transformCacheKey: ?string;
_depGraphHelpers: DepGraphHelpers; _depGraphHelpers: DepGraphHelpers;
_options: Options; _options: Options;
@ -90,7 +85,6 @@ class Module {
fastfs, fastfs,
moduleCache, moduleCache,
cache, cache,
extractor = extractRequires,
transformCode, transformCode,
transformCacheKey, transformCacheKey,
depGraphHelpers, depGraphHelpers,
@ -106,7 +100,6 @@ class Module {
this._fastfs = fastfs; this._fastfs = fastfs;
this._moduleCache = moduleCache; this._moduleCache = moduleCache;
this._cache = cache; this._cache = cache;
this._extractor = extractor;
this._transformCode = transformCode; this._transformCode = transformCode;
this._transformCacheKey = transformCacheKey; this._transformCacheKey = transformCacheKey;
invariant( invariant(
@ -221,23 +214,22 @@ class Module {
extern: boolean, extern: boolean,
result: TransformedCode, result: TransformedCode,
) { ) {
const {
code,
dependencies = extern ? [] : this._extractor(code).deps.sync,
} = result;
if (this._options.cacheTransformResults === false) { if (this._options.cacheTransformResults === false) {
const {dependencies} = result;
return {dependencies}; return {dependencies};
} else {
return {...result, dependencies, id, source};
} }
return {...result, id, source};
} }
_transformAndCache( _transformAndCache(
transformOptions: mixed, transformOptions: mixed,
callback: (error: ?Error, result: ?TransformedCode) => void, callback: (error: ?Error, result: ?TransformedCode) => void,
) { ) {
this._readSourceCode().then(sourceCode => {
const transformCode = this._transformCode; const transformCode = this._transformCode;
// AssetModule_DEPRECATED doesn't provide transformCode, but these should
// never be transformed anyway.
invariant(transformCode != null, 'missing code transform funtion');
this._readSourceCode().then(sourceCode => {
if (!transformCode) { if (!transformCode) {
return callback(null, {code: sourceCode}); return callback(null, {code: sourceCode});
} }

View File

@ -21,7 +21,6 @@ const path = require('path');
import type Cache from './Cache'; import type Cache from './Cache';
import type { import type {
DepGraphHelpers, DepGraphHelpers,
Extractor,
TransformCode, TransformCode,
Options as ModuleOptions, Options as ModuleOptions,
} from './Module'; } from './Module';
@ -33,7 +32,6 @@ class ModuleCache {
_packageCache: {[filePath: string]: Package}; _packageCache: {[filePath: string]: Package};
_fastfs: FastFs; _fastfs: FastFs;
_cache: Cache; _cache: Cache;
_extractRequires: Extractor;
_transformCode: TransformCode; _transformCode: TransformCode;
_transformCacheKey: string; _transformCacheKey: string;
_depGraphHelpers: DepGraphHelpers; _depGraphHelpers: DepGraphHelpers;
@ -54,7 +52,6 @@ class ModuleCache {
}: { }: {
fastfs: FastFs, fastfs: FastFs,
cache: Cache, cache: Cache,
extractRequires: Extractor,
transformCode: TransformCode, transformCode: TransformCode,
transformCacheKey: string, transformCacheKey: string,
depGraphHelpers: DepGraphHelpers, depGraphHelpers: DepGraphHelpers,
@ -65,7 +62,6 @@ class ModuleCache {
this._packageCache = Object.create(null); this._packageCache = Object.create(null);
this._fastfs = fastfs; this._fastfs = fastfs;
this._cache = cache; this._cache = cache;
this._extractRequires = extractRequires;
this._transformCode = transformCode; this._transformCode = transformCode;
this._transformCacheKey = transformCacheKey; this._transformCacheKey = transformCacheKey;
this._depGraphHelpers = depGraphHelpers; this._depGraphHelpers = depGraphHelpers;
@ -84,7 +80,6 @@ class ModuleCache {
fastfs: this._fastfs, fastfs: this._fastfs,
moduleCache: this, moduleCache: this,
cache: this._cache, cache: this._cache,
extractor: this._extractRequires,
transformCode: this._transformCode, transformCode: this._transformCode,
transformCacheKey: this._transformCacheKey, transformCacheKey: this._transformCacheKey,
depGraphHelpers: this._depGraphHelpers, depGraphHelpers: this._depGraphHelpers,

View File

@ -28,6 +28,7 @@ beforeEach(() => {
describe('DependencyGraph', function() { describe('DependencyGraph', function() {
let Module; let Module;
let extractDependencies;
let defaults; let defaults;
function getOrderedDependenciesAsJSON(dgraph, entryPath, platform, recursive = true) { function getOrderedDependenciesAsJSON(dgraph, entryPath, platform, recursive = true) {
@ -97,6 +98,9 @@ describe('DependencyGraph', function() {
}); });
Cache.prototype.end = jest.genMockFn(); Cache.prototype.end = jest.genMockFn();
const transformCacheKey = 'abcdef';
extractDependencies =
require('../../JSTransformer/worker/extract-dependencies');
defaults = { defaults = {
assetExts: ['png', 'jpg'], assetExts: ['png', 'jpg'],
cache: new Cache(), cache: new Cache(),
@ -117,7 +121,16 @@ describe('DependencyGraph', function() {
useWatchman: false, useWatchman: false,
maxWorkers: 1, maxWorkers: 1,
resetCache: true, resetCache: true,
transformCacheKey: 'abcdef', transformCode: (module, sourceCode, transformOptions) => {
return new Promise(resolve => {
let deps = {dependencies: [], dependencyOffsets: []};
if (!module.path.endsWith('.json')) {
deps = extractDependencies(sourceCode);
}
resolve({...deps, code: sourceCode});
});
},
transformCacheKey,
}; };
}); });
@ -1468,7 +1481,7 @@ describe('DependencyGraph', function() {
'subdir': { 'subdir': {
'lolynot.js': 'require("../other")', 'lolynot.js': 'require("../other")',
}, },
'other.js': 'some code', 'other.js': '/* some code */',
}, },
}, },
}); });
@ -1558,7 +1571,7 @@ describe('DependencyGraph', function() {
browser: 'client.js', browser: 'client.js',
}, fieldName)), }, fieldName)),
'main.js': 'some other code', 'main.js': 'some other code',
'client.js': 'some code', 'client.js': '/* some code */',
}, },
}, },
}); });
@ -1613,7 +1626,7 @@ describe('DependencyGraph', function() {
browser: 'client', browser: 'client',
}, fieldName)), }, fieldName)),
'main.js': 'some other code', 'main.js': 'some other code',
'client.js': 'some code', 'client.js': '/* some code */',
}, },
}, },
}); });
@ -1668,7 +1681,7 @@ describe('DependencyGraph', function() {
}, },
}, fieldName)), }, fieldName)),
'main.js': 'some other code', 'main.js': 'some other code',
'client.js': 'some code', 'client.js': '/* some code */',
}, },
}, },
}); });
@ -1724,7 +1737,7 @@ describe('DependencyGraph', function() {
}, },
}, fieldName)), }, fieldName)),
'main.js': 'some other code', 'main.js': 'some other code',
'client.js': 'some code', 'client.js': '/* some code */',
}, },
}, },
}); });
@ -1785,17 +1798,17 @@ describe('DependencyGraph', function() {
'./hello.js': './bye.js', './hello.js': './bye.js',
}, },
}, fieldName)), }, fieldName)),
'main.js': 'some other code', 'main.js': '/* some other code */',
'client.js': 'require("./node")\nrequire("./dir/server.js")', 'client.js': 'require("./node")\nrequire("./dir/server.js")',
'not-node.js': 'require("./not-browser")', 'not-node.js': 'require("./not-browser")',
'not-browser.js': 'require("./dir/server")', 'not-browser.js': 'require("./dir/server")',
'browser.js': 'some browser code', 'browser.js': '/* some browser code */',
'dir': { 'dir': {
'server.js': 'some node code', 'server.js': '/* some node code */',
'client.js': 'require("../hello")', 'client.js': 'require("../hello")',
}, },
'hello.js': 'hello', 'hello.js': '/* hello */',
'bye.js': 'bye', 'bye.js': '/* bye */',
}, },
}, },
}); });
@ -1889,13 +1902,13 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package', 'name': 'node-package',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'browser-package': { 'browser-package': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'browser-package', 'name': 'browser-package',
}), }),
'index.js': 'some browser code', 'index.js': '/* some browser code */',
}, },
}, },
}, },
@ -1959,13 +1972,13 @@ describe('DependencyGraph', function() {
'index.js': 'require("./dir/ooga")', 'index.js': 'require("./dir/ooga")',
'dir': { 'dir': {
'ooga.js': 'require("node-package")', 'ooga.js': 'require("node-package")',
'browser.js': 'some browser code', 'browser.js': '/* some browser code */',
}, },
'node-package': { 'node-package': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package', 'name': 'node-package',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
}, },
}, },
@ -2040,13 +2053,13 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package', 'name': 'node-package',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'browser-package': { 'browser-package': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'browser-package', 'name': 'browser-package',
}), }),
'index.js': 'some browser code', 'index.js': '/* some browser code */',
}, },
}, },
}, },
@ -2112,7 +2125,7 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'booga', 'name': 'booga',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
}, },
}, },
@ -2165,7 +2178,7 @@ describe('DependencyGraph', function() {
}, },
}, fieldName)), }, fieldName)),
'index.js': 'require("./booga")', 'index.js': 'require("./booga")',
'booga.js': 'some node code', 'booga.js': '/* some node code */',
}, },
}, },
}); });
@ -2223,7 +2236,7 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package', 'name': 'node-package',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'rn-package': { 'rn-package': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
@ -2238,7 +2251,7 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'nested-browser-package', 'name': 'nested-browser-package',
}), }),
'index.js': 'some code', 'index.js': '/* some code */',
}, },
}, },
}, },
@ -2365,49 +2378,49 @@ describe('DependencyGraph', function() {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package-a', 'name': 'node-package-a',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'node-package-b': { 'node-package-b': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package-b', 'name': 'node-package-b',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'node-package-c': { 'node-package-c': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package-c', 'name': 'node-package-c',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'node-package-d': { 'node-package-d': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'node-package-d', 'name': 'node-package-d',
}), }),
'index.js': 'some node code', 'index.js': '/* some node code */',
}, },
'rn-package-a': { 'rn-package-a': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'rn-package-a', 'name': 'rn-package-a',
}), }),
'index.js': 'some rn code', 'index.js': '/* some rn code */',
}, },
'rn-package-b': { 'rn-package-b': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'rn-package-b', 'name': 'rn-package-b',
}), }),
'index.js': 'some rn code', 'index.js': '/* some rn code */',
}, },
'rn-package-c': { 'rn-package-c': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'rn-package-c', 'name': 'rn-package-c',
}), }),
'index.js': 'some rn code', 'index.js': '/* some rn code */',
}, },
'rn-package-d': { 'rn-package-d': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
'name': 'rn-package-d', 'name': 'rn-package-d',
}), }),
'index.js': 'some rn code', 'index.js': '/* some rn code */',
}, },
}, },
}, },
@ -2638,6 +2651,7 @@ describe('DependencyGraph', function() {
jest.resetModules(); jest.resetModules();
jest.mock('path', () => path.win32); jest.mock('path', () => path.win32);
DependencyGraph = require('../index'); DependencyGraph = require('../index');
extractDependencies = require('../../JSTransformer/worker/extract-dependencies');
}); });
afterEach(function() { afterEach(function() {
@ -2716,7 +2730,7 @@ describe('DependencyGraph', function() {
const root = 'C:\\root'; const root = 'C:\\root';
setMockFileSystem({ setMockFileSystem({
'root': { 'root': {
'index.js': 'require("C:\\root\\arbitrary.js");', 'index.js': 'require("C:\\\\root\\\\arbitrary.js");',
'arbitrary.js': '', 'arbitrary.js': '',
}, },
}); });
@ -2782,14 +2796,14 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar");\nfoo module', 'main.js': 'require("bar");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
}, },
}, },
}, },
@ -2798,7 +2812,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 2 module', 'main.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -2942,14 +2956,14 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar/lol");\nfoo module', 'main.js': 'require("bar/lol");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
'lol.js': '', 'lol.js': '',
}, },
}, },
@ -2959,7 +2973,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 2 module', 'main.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -3033,7 +3047,7 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar/lol");\nfoo module', 'main.js': 'require("bar/lol");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
@ -3043,7 +3057,7 @@ describe('DependencyGraph', function() {
'./lol': './wow', './lol': './wow',
}, },
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
'lol.js': '', 'lol.js': '',
'wow.js': '', 'wow.js': '',
}, },
@ -3054,7 +3068,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
browser: './main2', browser: './main2',
}), }),
'main2.js': 'bar 2 module', 'main2.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -3434,7 +3448,7 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'foo module', 'main.js': '/* foo module */',
}, },
}, },
}, },
@ -3833,14 +3847,14 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar");\nfoo module', 'main.js': 'require("bar");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
}, },
}, },
}, },
@ -3849,7 +3863,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 2 module', 'main.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -3993,14 +4007,14 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar/lol");\nfoo module', 'main.js': 'require("bar/lol");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
'lol.js': '', 'lol.js': '',
}, },
}, },
@ -4010,7 +4024,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 2 module', 'main.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -4084,7 +4098,7 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar/lol");\nfoo module', 'main.js': 'require("bar/lol");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
@ -4094,7 +4108,7 @@ describe('DependencyGraph', function() {
'./lol': './wow', './lol': './wow',
}, },
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
'lol.js': '', 'lol.js': '',
'wow.js': '', 'wow.js': '',
}, },
@ -4105,7 +4119,7 @@ describe('DependencyGraph', function() {
name: 'bar', name: 'bar',
browser: './main2', browser: './main2',
}), }),
'main2.js': 'bar 2 module', 'main2.js': '/* bar 2 module */',
}, },
}, },
}, },
@ -4484,7 +4498,7 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'foo module', 'main.js': '/* foo module */',
}, },
}, },
}, },
@ -5559,14 +5573,14 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'require("bar");\nfoo module', 'main.js': 'require("bar");\n/* foo module */',
'node_modules': { 'node_modules': {
'bar': { 'bar': {
'package.json': JSON.stringify({ 'package.json': JSON.stringify({
name: 'bar', name: 'bar',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'bar 1 module', 'main.js': '/* bar 1 module */',
}, },
}, },
}, },
@ -5665,8 +5679,8 @@ describe('DependencyGraph', function() {
name: 'foo', name: 'foo',
main: 'main.js', main: 'main.js',
}), }),
'main.js': 'foo module', 'main.js': '/* foo module */',
'browser.js': 'foo module', 'browser.js': '/* foo module */',
}, },
}, },
}, },

View File

@ -13,7 +13,6 @@ jest
.dontMock('json-stable-stringify') .dontMock('json-stable-stringify')
.dontMock('imurmurhash') .dontMock('imurmurhash')
.dontMock('../fastfs') .dontMock('../fastfs')
.dontMock('../lib/extractRequires')
.dontMock('../lib/replacePatterns') .dontMock('../lib/replacePatterns')
.dontMock('../DependencyGraph/docblock') .dontMock('../DependencyGraph/docblock')
.dontMock('../Module'); .dontMock('../Module');
@ -214,57 +213,6 @@ describe('Module', () => {
); );
}); });
describe('Extractors', () => {
pit('uses custom require extractors if specified', () => {
mockIndexFile('');
const module = createModule({
extractor: code => ({deps: {sync: ['foo', 'bar']}}),
});
return module.getDependencies().then(actual =>
expect(actual).toEqual(['foo', 'bar']));
});
pit('uses a default extractor to extract dependencies', () => {
mockIndexFile(`
require('dependency-a');
import * as b from "dependency-b";
export {something} from 'dependency-c';
`);
const module = createModule();
return module.getDependencies().then(dependencies =>
expect(dependencies.sort())
.toEqual(['dependency-a', 'dependency-b', 'dependency-c'])
);
});
pit('does not extract dependencies from files annotated with @extern', () => {
mockIndexFile(`
/**
* @extern
*/
require('dependency-a');
import * as b from "dependency-b";
export {something} from 'dependency-c';
`);
const module = createModule();
return module.getDependencies().then(dependencies =>
expect(dependencies).toEqual([])
);
});
pit('does not extract dependencies from JSON files', () => {
mockPackageFile();
const module = createJSONModule();
return module.getDependencies().then(dependencies =>
expect(dependencies).toEqual([])
);
});
});
describe('Custom Code Transform', () => { describe('Custom Code Transform', () => {
let transformCode; let transformCode;
let transformResult; let transformResult;
@ -355,15 +303,6 @@ describe('Module', () => {
}); });
}); });
pit('uses the code that `transformCode` resolves to to extract dependencies', () => {
transformResult = {code: exampleCode};
const module = createModule({transformCode});
return module.getDependencies().then(dependencies => {
expect(dependencies).toEqual(['a', 'c']);
});
});
pit('uses dependencies that `transformCode` resolves to, instead of extracting them', () => { pit('uses dependencies that `transformCode` resolves to, instead of extracting them', () => {
const mockedDependencies = ['foo', 'bar']; const mockedDependencies = ['foo', 'bar'];
transformResult = { transformResult = {

View File

@ -24,7 +24,6 @@ const Polyfill = require('./Polyfill');
const ResolutionRequest = require('./DependencyGraph/ResolutionRequest'); const ResolutionRequest = require('./DependencyGraph/ResolutionRequest');
const ResolutionResponse = require('./DependencyGraph/ResolutionResponse'); const ResolutionResponse = require('./DependencyGraph/ResolutionResponse');
const extractRequires = require('./lib/extractRequires');
const getAssetDataFromName = require('./lib/getAssetDataFromName'); const getAssetDataFromName = require('./lib/getAssetDataFromName');
const getInverseDependencies = require('./lib/getInverseDependencies'); const getInverseDependencies = require('./lib/getInverseDependencies');
const getPlatformExtension = require('./lib/getPlatformExtension'); const getPlatformExtension = require('./lib/getPlatformExtension');
@ -37,7 +36,6 @@ const util = require('util');
import type { import type {
TransformCode, TransformCode,
Options as ModuleOptions, Options as ModuleOptions,
Extractor,
} from './Module'; } from './Module';
const ERROR_BUILDING_DEP_GRAPH = 'DependencyGraphError'; const ERROR_BUILDING_DEP_GRAPH = 'DependencyGraphError';
@ -63,7 +61,6 @@ class DependencyGraph {
preferNativePlatform: boolean, preferNativePlatform: boolean,
extensions: Array<string>, extensions: Array<string>,
mocksPattern: mixed, mocksPattern: mixed,
extractRequires: Extractor,
transformCode: TransformCode, transformCode: TransformCode,
transformCacheKey: string, transformCacheKey: string,
shouldThrowOnUnresolvedErrors: () => boolean, shouldThrowOnUnresolvedErrors: () => boolean,
@ -98,7 +95,6 @@ class DependencyGraph {
cache, cache,
extensions, extensions,
mocksPattern, mocksPattern,
extractRequires,
transformCode, transformCode,
transformCacheKey, transformCacheKey,
shouldThrowOnUnresolvedErrors = () => true, shouldThrowOnUnresolvedErrors = () => true,
@ -123,7 +119,6 @@ class DependencyGraph {
cache: Cache, cache: Cache,
extensions: Array<string>, extensions: Array<string>,
mocksPattern: mixed, mocksPattern: mixed,
extractRequires: Extractor,
transformCode: TransformCode, transformCode: TransformCode,
transformCacheKey: string, transformCacheKey: string,
shouldThrowOnUnresolvedErrors: () => boolean, shouldThrowOnUnresolvedErrors: () => boolean,
@ -147,7 +142,6 @@ class DependencyGraph {
preferNativePlatform: preferNativePlatform || false, preferNativePlatform: preferNativePlatform || false,
extensions: extensions || ['js', 'json'], extensions: extensions || ['js', 'json'],
mocksPattern, mocksPattern,
extractRequires,
transformCode, transformCode,
transformCacheKey, transformCacheKey,
shouldThrowOnUnresolvedErrors, shouldThrowOnUnresolvedErrors,
@ -209,7 +203,6 @@ class DependencyGraph {
this._moduleCache = new ModuleCache({ this._moduleCache = new ModuleCache({
fastfs: this._fastfs, fastfs: this._fastfs,
cache: this._cache, cache: this._cache,
extractRequires: this._opts.extractRequires,
transformCode: this._opts.transformCode, transformCode: this._opts.transformCode,
transformCacheKey: this._opts.transformCacheKey, transformCacheKey: this._opts.transformCacheKey,
depGraphHelpers: this._helpers, depGraphHelpers: this._helpers,
@ -421,7 +414,6 @@ class DependencyGraph {
static FileWatcher; static FileWatcher;
static Module; static Module;
static Polyfill; static Polyfill;
static extractRequires;
static getAssetDataFromName; static getAssetDataFromName;
static getPlatformExtension; static getPlatformExtension;
static replacePatterns; static replacePatterns;
@ -435,7 +427,6 @@ Object.assign(DependencyGraph, {
FileWatcher, FileWatcher,
Module, Module,
Polyfill, Polyfill,
extractRequires,
getAssetDataFromName, getAssetDataFromName,
getPlatformExtension, getPlatformExtension,
replacePatterns, replacePatterns,

View File

@ -1,106 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
jest.dontMock('../extractRequires');
jest.dontMock('../replacePatterns');
const extractRequires = require('../extractRequires');
describe('extractRequires', () => {
it('should extract both requires and imports from code', () => {
const code = `
import module1 from 'module1';
const module2 = require('module2');
const module3 = require(\`module3\`);
`;
expect(extractRequires(code)).toEqual({
code,
deps: {sync: ['module1', 'module2', 'module3']},
});
});
it('should extract requires in order', () => {
const code = `
const module1 = require('module1');
const module2 = require('module2');
const module3 = require('module3');
`;
expect(extractRequires(code)).toEqual({
code,
deps: {sync: ['module1', 'module2', 'module3']},
});
});
it('should strip out comments from code', () => {
const code = '// comment';
expect(extractRequires(code)).toEqual({
code: '',
deps: {sync: []},
});
});
it('should ignore requires in comments', () => {
const code = [
'// const module1 = require("module1");',
'/**',
' * const module2 = require("module2");',
' */',
].join('\n');
expect(extractRequires(code)).toEqual({
code: '\n',
deps: {sync: []},
});
});
it('should ignore requires in comments with Windows line endings', () => {
const code = [
'// const module1 = require("module1");',
'/**',
' * const module2 = require("module2");',
' */',
].join('\r\n');
expect(extractRequires(code)).toEqual({
code: '\r\n',
deps: {sync: []},
});
});
it('should ignore requires in comments with unicode line endings', () => {
const code = [
'// const module1 = require("module1");\u2028',
'// const module1 = require("module2");\u2029',
'/*\u2028',
'const module2 = require("module3");\u2029',
' */',
].join('');
expect(extractRequires(code)).toEqual({
code: '\u2028\u2029',
deps: {sync: []},
});
});
it('should dedup duplicated requires', () => {
const code = `
const module1 = require('module1');
const module1Dup = require('module1');
`;
expect(extractRequires(code)).toEqual({
code,
deps: {sync: ['module1']},
});
});
});

View File

@ -1,55 +0,0 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const replacePatterns = require('./replacePatterns');
/**
* Extract all required modules from a `code` string.
*/
const blockCommentRe = /\/\*[^]*?\*\//g;
const lineCommentRe = /\/\/.*/g;
function extractRequires(code) {
const cache = Object.create(null);
var deps = {
sync: [],
};
const addDependency = (dep) => {
if (!cache[dep]) {
cache[dep] = true;
deps.sync.push(dep);
}
};
code = code
.replace(blockCommentRe, '')
.replace(lineCommentRe, '')
// Parse the sync dependencies this module has. When the module is
// required, all it's sync dependencies will be loaded into memory.
// Sync dependencies can be defined either using `require` or the ES6
// `import` or `export` syntaxes:
// var dep1 = require('dep1');
.replace(replacePatterns.IMPORT_RE, (match, pre, quot, dep, post) => {
addDependency(dep);
return match;
})
.replace(replacePatterns.EXPORT_RE, (match, pre, quot, dep, post) => {
addDependency(dep);
return match;
})
.replace(replacePatterns.REQUIRE_RE, (match, pre, quot, dep, post) => {
addDependency(dep);
return match;
});
return {code, deps};
}
module.exports = extractRequires;