[react-packager] Allow json files as modules

This commit is contained in:
Amjad Masad 2015-04-21 10:57:53 -07:00
parent 201d65dead
commit f91f7084ec
6 changed files with 86 additions and 4 deletions

View File

@ -45,6 +45,8 @@ function ModuleDescriptor(fields) {
this.altId = fields.altId; this.altId = fields.altId;
this.isJSON = fields.isJSON;
this._fields = fields; this._fields = fields;
} }

View File

@ -101,6 +101,46 @@ describe('DependencyGraph', function() {
}); });
}); });
pit('should get json dependencies', function() {
var root = '/root';
fs.__setMockFilesystem({
'root': {
'package.json': JSON.stringify({
name: 'package'
}),
'index.js': [
'/**',
' * @providesModule index',
' */',
'require("./a.json")'
].join('\n'),
'a.json': JSON.stringify({}),
}
});
var dgraph = new DependencyGraph({
roots: [root],
fileWatcher: fileWatcher
});
return dgraph.load().then(function() {
expect(dgraph.getOrderedDependencies('/root/index.js'))
.toEqual([
{
id: 'index',
altId: 'package/index',
path: '/root/index.js',
dependencies: ['./a.json']
},
{
id: 'package/a.json',
isJSON: true,
path: '/root/a.json',
dependencies: []
},
]);
});
});
pit('should get dependencies with deprecated assets', function() { pit('should get dependencies with deprecated assets', function() {
var root = '/root'; var root = '/root';
fs.__setMockFilesystem({ fs.__setMockFilesystem({

View File

@ -66,7 +66,7 @@ function DependecyGraph(options) {
this._debugUpdateEvents = []; this._debugUpdateEvents = [];
this._moduleExtPattern = new RegExp( this._moduleExtPattern = new RegExp(
'\.(' + ['js'].concat(this._assetExts).join('|') + ')$' '\.(' + ['js', 'json'].concat(this._assetExts).join('|') + ')$'
); );
// Kick off the search process to precompute the dependency graph. // Kick off the search process to precompute the dependency graph.
@ -259,7 +259,7 @@ DependecyGraph.prototype.resolveDependency = function(
} }
// JS modules can be required without extensios. // JS modules can be required without extensios.
if (!this._isFileAsset(modulePath)) { if (!this._isFileAsset(modulePath) && !modulePath.match(/\.json$/)) {
modulePath = withExtJs(modulePath); modulePath = withExtJs(modulePath);
} }
@ -432,6 +432,15 @@ DependecyGraph.prototype._processModule = function(modulePath) {
return Promise.resolve(module); return Promise.resolve(module);
} }
if (extname(modulePath) === 'json') {
moduleData.id = this._lookupName(modulePath);
moduleData.isJSON = true;
moduleData.dependencies = [];
module = new ModuleDescriptor(moduleData);
this._updateGraphWithModule(module);
return Promise.resolve(module);
}
var self = this; var self = this;
return readFile(modulePath, 'utf8') return readFile(modulePath, 'utf8')
.then(function(content) { .then(function(content) {

View File

@ -43,6 +43,10 @@ describe('Packager', function() {
}; };
}); });
require('fs').readFile.mockImpl(function(file, callback) {
callback(null, '{"json":true}');
});
var packager = new Packager({projectRoots: ['/root']}); var packager = new Packager({projectRoots: ['/root']});
var modules = [ var modules = [
{id: 'foo', path: '/root/foo.js', dependencies: []}, {id: 'foo', path: '/root/foo.js', dependencies: []},
@ -60,7 +64,13 @@ describe('Packager', function() {
isAsset: true, isAsset: true,
resolution: 2, resolution: 2,
dependencies: [] dependencies: []
} },
{
id: 'package/file.json',
path: '/root/file.json',
isJSON: true,
dependencies: [],
},
]; ];
getDependencies.mockImpl(function() { getDependencies.mockImpl(function() {
@ -137,6 +147,12 @@ describe('Packager', function() {
'/root/img/new_image.png' '/root/img/new_image.png'
]); ]);
expect(p.addModule.mock.calls[4]).toEqual([
'lol module.exports = {"json":true}; lol',
'module.exports = {"json":true};',
'/root/file.json'
]);
expect(p.finalize.mock.calls[0]).toEqual([ expect(p.finalize.mock.calls[0]).toEqual([
{runMainModule: true} {runMainModule: true}
]); ]);

View File

@ -21,6 +21,7 @@ var declareOpts = require('../lib/declareOpts');
var imageSize = require('image-size'); var imageSize = require('image-size');
var sizeOf = Promise.promisify(imageSize); var sizeOf = Promise.promisify(imageSize);
var readFile = Promise.promisify(fs.readFile);
var validateOpts = declareOpts({ var validateOpts = declareOpts({
projectRoots: { projectRoots: {
@ -147,6 +148,8 @@ Packager.prototype._transformModule = function(ppackage, module) {
transform = this.generateAssetModule_DEPRECATED(ppackage, module); transform = this.generateAssetModule_DEPRECATED(ppackage, module);
} else if (module.isAsset) { } else if (module.isAsset) {
transform = this.generateAssetModule(ppackage, module); transform = this.generateAssetModule(ppackage, module);
} else if (module.isJSON) {
transform = generateJSONModule(module);
} else { } else {
transform = this._transformer.loadFileAndTransform( transform = this._transformer.loadFileAndTransform(
path.resolve(module.path) path.resolve(module.path)
@ -206,6 +209,18 @@ Packager.prototype.generateAssetModule = function(ppackage, module) {
var code = 'module.exports = ' + JSON.stringify(img) + ';'; var code = 'module.exports = ' + JSON.stringify(img) + ';';
return {
code: code,
sourceCode: code,
sourcePath: module.path,
};
});
};
function generateJSONModule(module) {
return readFile(module.path).then(function(data) {
var code = 'module.exports = ' + data.toString('utf8') + ';';
return { return {
code: code, code: code,
sourceCode: code, sourceCode: code,

View File

@ -80,7 +80,7 @@ function Server(options) {
dir: dir, dir: dir,
globs: [ globs: [
'**/*.js', '**/*.js',
'**/package.json', '**/*.json',
].concat(assetGlobs), ].concat(assetGlobs),
}; };
}); });