From dbf1fa5a8ecdb08089a1005f175075414e70f187 Mon Sep 17 00:00:00 2001 From: Rabbit Date: Wed, 15 Mar 2017 13:36:55 +0800 Subject: [PATCH] fix: add `stringify` option to output JSON object as string (#45) --- README.md | 12 ++++++++++++ index.js | 16 ++++++++++------ package.json | 3 +++ 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index ddd6c4f..854931a 100644 --- a/README.md +++ b/README.md @@ -62,6 +62,17 @@ import json from 'file.json'; import json from 'json-loader!file.json'; ``` + + +### Options + +#### `stringify` + +By default, the json-loader will output the json object, set this query parameter to 'true' can output the json object as a string, e.g. `require('json-loader?stringify!../index.json')`. + + + +

Maintainer

@@ -76,6 +87,7 @@ import json from 'json-loader!file.json';
+ [npm]: https://img.shields.io/npm/v/json-loader.svg [npm-url]: https://npmjs.com/package/json-loader diff --git a/index.js b/index.js index bb7b2c0..5cadd7d 100644 --- a/index.js +++ b/index.js @@ -1,10 +1,14 @@ /* - MIT License http://www.opensource.org/licenses/mit-license.php - Author Tobias Koppers @sokra + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra */ +var loaderUtils = require('loader-utils'); + module.exports = function(source) { - this.cacheable && this.cacheable(); - var value = typeof source === "string" ? JSON.parse(source) : source; - this.value = [value]; - return "module.exports = " + JSON.stringify(value) + ";"; + var value = typeof source === "string" ? JSON.parse(source) : source; + var options = loaderUtils.getOptions(this) || {}; + value = JSON.stringify(value) + value = options.stringify ? `'${value}'` : value + var module = this.version && this.version >= 2 ? `export default ${value};` : `module.exports = ${value};`; + return module } diff --git a/package.json b/package.json index 71422c5..75593f0 100644 --- a/package.json +++ b/package.json @@ -7,5 +7,8 @@ "repository": { "type": "git", "url": "https://github.com/webpack/json-loader.git" + }, + "dependencies": { + "loader-utils": "^1.0.3" } }