Skip to content

Commit

Permalink
feat(bundler): support Node.js direct json loading require("foo.json")
Browse files Browse the repository at this point in the history
  • Loading branch information
3cp committed Sep 27, 2018
1 parent 1a75ad7 commit 8fa8800
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/build/bundled-source.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ exports.BundledSource = class {
if (matchingPlugin) {
deps = findDeps(modulePath, this.contents);
this.contents = matchingPlugin.transform(moduleId, modulePath, this.contents);
} else if (path.extname(modulePath).toLowerCase() === '.json') {
// support Node.js's json module
let contents = `define(\'${moduleId}\',[],function(){return JSON.parse(${JSON.stringify(this.contents)});});`;
this.contents = contents;
} else {
// forceCjsWrap bypasses a r.js parse bug.
// See lib/amodro-trace/read/cjs.js for more info.
Expand Down
31 changes: 31 additions & 0 deletions spec/lib/build/bundled-source.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,37 @@ exports.t = t;
.toBe("define('foo/dist/cjs/lo',['require','exports','module'],function (require, exports, module) {});");
});

it('transforms npm package json file', () => {
let file = {
path: path.resolve(cwd, 'node_modules/foo/bar/lo.json'),
contents: '{"a":1}'
};

let bs = new BundledSource(bundler, file);
bs._getProjectRoot = () => 'src';
bs.includedBy = {
includedBy: {
description: {
name: 'foo',
mainId: 'foo/index',
loaderConfig: {
name: 'foo',
path: '../node_modules/foo',
main: 'index'
}
}
}
};
bs._getLoaderPlugins = () => [];
bs._getLoaderConfig = () => ({paths: {}});

let deps = bs.transform();
expect(deps).toBeUndefined();
expect(bs.requiresTransform).toBe(false);
expect(bs.contents)
.toBe('define(\'foo/bar/lo.json\',[],function(){return JSON.parse("{\\\"a\\\":1}");});');
});

it('transforms npm package non-js file', () => {
let file = {
path: path.resolve(cwd, 'node_modules/foo/bar/lo.html'),
Expand Down

0 comments on commit 8fa8800

Please sign in to comment.