From 8fa88008da6cdb024d9bdcd7d668728ac2618dc1 Mon Sep 17 00:00:00 2001 From: Chunpeng Huo Date: Mon, 3 Sep 2018 08:36:00 +1000 Subject: [PATCH] feat(bundler): support Node.js direct json loading require("foo.json") --- lib/build/bundled-source.js | 4 ++++ spec/lib/build/bundled-source.spec.js | 31 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/build/bundled-source.js b/lib/build/bundled-source.js index b0737e459..b96af475f 100644 --- a/lib/build/bundled-source.js +++ b/lib/build/bundled-source.js @@ -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. diff --git a/spec/lib/build/bundled-source.spec.js b/spec/lib/build/bundled-source.spec.js index 4746737fa..356fc4942 100644 --- a/spec/lib/build/bundled-source.spec.js +++ b/spec/lib/build/bundled-source.spec.js @@ -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'),