Giter VIP home page Giter VIP logo

rollup-plugin-json's Introduction

Moved

This module has moved and is now available at @rollup/plugin-json. Please update your dependencies. This repository is no longer maintained.

rollup-plugin-json

Convert .json files to ES6 modules:

// import a single property from a JSON file,
// discarding the rest
import { version } from './package.json';
console.log( `running version ${version}` );

// import the whole file as an object
import pkg from './package.json';
console.log( `running version ${pkg.version}` );

Installation

npm install --save-dev rollup-plugin-json

Usage

// rollup.config.js
import json from 'rollup-plugin-json';

export default {
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife'
  },

  plugins: [
    json({
      // All JSON files will be parsed by default,
      // but you can also specifically include/exclude files
      include: 'node_modules/**',
      exclude: [ 'node_modules/foo/**', 'node_modules/bar/**' ],

      // for tree-shaking, properties will be declared as
      // variables, using either `var` or `const`
      preferConst: true, // Default: false

      // specify indentation for the generated default export —
      // defaults to '\t'
      indent: '  ',

      // ignores indent and generates the smallest code
      compact: true, // Default: false

      // generate a named export for every property of the JSON object
      namedExports: true // Default: true
    })
  ]
};

License

MIT

rollup-plugin-json's People

Contributors

bhousel avatar btakita avatar eventualbuddha avatar jacobmischka avatar jnields avatar jonataswalker avatar lukastaegert avatar maranomynet avatar ndelvalle avatar notwoods avatar realityking avatar rich-harris avatar shellscape avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rollup-plugin-json's Issues

How to disable the indent change when using this plugin?

when I'm using this plugin to handle the package.json file, I found it changes the indent to a tab while the origin indent of my source file is two spaces. This caused the eslint throw some errors. So, would you please so kind to tell me is there any option to config the indent of output file from rollup-plugin-json?

Support JSON5

It's just better all around, plus, it parses regular JSON files, so you can easily support both in parallel: https://github.com/json5/json5

It could either support it by default, or if you don't want to have it as a dependency, support passing the parser as a config option.

json({ parser: JSON5.parse })

build error with uglifyjs

I'm using rollup to build my library. here is the error

src/index.js → stdout...
  3590 | 
  3591 | 
> 3592 |        const wrapAnsi16 = (fn, offset) => function () {
       | ^ Unexpected token: keyword (const)
  3593 |          const code = fn.apply(colorConvert, arguments);
  3594 |          return `\u001B[${code + offset}m`;
  3595 |        };
[!] (uglify plugin) Error: Unexpected token: keyword (const)
SyntaxError: Unexpected token: keyword (const)
    at JS_Parse_Error.get (eval at <anonymous> (/Users/jessie/Documents/Projects/test/node_modules/uglify-js/tools/node.js:20:1),

and here is the config

import alias from 'rollup-plugin-alias';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import babel from 'rollup-plugin-babel';
import {uglify} from 'rollup-plugin-uglify';
import builtins from 'rollup-plugin-node-builtins';
import paths from './paths';

const name = 'test';
const banner = '';

const baseConfig = {
    input: 'src/index.js',
    plugins: [
        alias({
            resolve: ['.js']
        }),
        resolve(),
        babel({
            exclude: 'node_modules/**',
            runtimeHelpers: true
        }),
        commonjs(),
        builtins(),
        process.env.NODE_ENV === 'production' && uglify()
    ]
};
export default [
    {
        ...baseConfig,
        output: [
            {
                name,
                file: `${paths.output}/${name}.js`,
                format: 'umd',
                sourcemap: true
            },
            // cjs and esm version
            {
                file: `${paths.output}/${name}.cjs.js`,
                format: 'cjs',
                banner
            },
            // cjs and esm version
            {
                file: `${paths.output}/${name}.esm.js`,
                format: 'es',
                banner
            }
        ]
    },
    // .min.js
    {
        ...baseConfig,
        output: [
            // umd with compress version
            {
                file: `dist/${name}.min.js`,
                format: 'umd',
                name,
                banner
            }
        ]
    }
];

.babelrc

{
    "presets": [
        [
            "@babel/env",
            {
                "modules": false
            }
        ]
    ],
    "plugins": [
        "@babel/proposal-object-rest-spread"
    ]
}

deps:

"dependencies": {
    "jsondiffpatch": "^0.3.11"
  },
  "devDependencies": {
    "@babel/core": "^7.2.0",
    "@babel/plugin-external-helpers": "^7.2.0",
    "@babel/plugin-proposal-object-rest-spread": "^7.2.0",
    "@babel/preset-env": "^7.2.0",
    "babel-eslint": "^10.0.1",
    "babel-loader": "^8.0.4",
    "chalk": "^2.4.1",
    "clean-webpack-plugin": "^1.0.0",
    "cross-env": "^5.2.0",
    "eslint": "^5.9.0",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-import-resolver-webpack": "^0.10.1",
    "eslint-plugin-import": "^2.14.0",
    "rimraf": "^2.6.2",
    "rollup": "^0.67.4",
    "rollup-plugin-alias": "^1.4.0",
    "rollup-plugin-babel": "^4.0.3",
    "rollup-plugin-commonjs": "^9.2.0",
    "rollup-plugin-node-builtins": "^2.1.2",
    "rollup-plugin-node-resolve": "^3.4.0",
    "rollup-plugin-uglify": "^6.0.0"
  }

I can't figure out why.....Please help to check this.

Unable to install via git url

I imagine this is likely a problem with all rollup plugins, but it seems it's impossible to install this one at least via a git url.

This is because the dist directory isn't checked into source control, and this project's rollup config is missing from the files array in package.json and there's no {pre,,post}install script. So the dist files aren't downloaded when installing, and can't be built either.

The two solutions I can imagine are either: dist should be checked into source control, or rollup.config.js should be added to the files array and an install script of some kind should be added. I'm not sure which feels less dirty to you.

Certainly this isn't a very big issue, as installing from the npm registry works correctly, and if someone needs to install via a git url they can fix this themselves, but it might be something worth considering.

Thanks for everything!

Importing large JSON files is slow

Hi I was trying to import a large topo json file (718 kb), and rollup is not able to finish building. The topo json file is for the world map and has many nested values which is why I'm guessing it goes slow. Is this due to tree shaking? Is there a way to just import the json file as it is, and do no processing on it so it can be imported faster?

Improve performance by putting JSON.parse in the bundle?

Based on this article:

Because the JSON grammar is much simpler than JavaScript’s grammar, JSON can be parsed more efficiently than JavaScript.

...

As long as the JSON string is only evaluated once, the JSON.parse approach is much faster compared to the JavaScript object literal, especially for cold loads. A good rule of thumb is to apply this technique for objects of 10 kB or larger — but as always with performance advice, measure the actual impact before making any changes.

Would it make sense to change rollup-plugin-json to return a JSON string wrapped in JSON.parse for sufficiently large files?

Unless someone convinces me this is a horrible idea, I think I might give it a try, since I have an application that bundles a couple large JSON files with Rollup and I'd like to learn more about Rollup plugins :)

Is it possible to import the package.json into the rollup.config.js?

Hi there. I want to do the following but it throws a PARSE_ERROR as it tries to parse the json as js:

import json from "rollup-plugin-json";
import pkg from "../package.json";

export default {
    banner : `${name}${version}`,
    entry : "src/index.js",
    plugins : [
        json()
    ]
};

Generated quote style

Is there anyway to customize the quoting style used in the output of this plugin?
eg. make it use single quotes instead of the current double quotes?

Currently the below source:

import {
	name
	,version
} from '../package.json'

const _MODULE_NAME = name.split('/')[1]
const _MODULE_VERSION = version
...

Produces: (using: plugins: json({preferConst: true}) )

const name = "<pkg.name>";		// content replaced for example
const version = "<pkg.version>";	// content replaced for example
...

While viewing the generated code in my editor (atom-beta) using eslint, i get errors from my quotes config.
I know there are more issues with linting generated code from rollup, but this is, together with the extra semicolons after each line that i also disallow, that bothers me at moment...

Should pass Array objects to dataToEsm

Currently according to source, if a parsed JSON were determined to be not an Object, as in Object.prototype.toString.call(data) !== '[object Object]', it will not be passed on to dataToEsm. However this behavior excludes the case when the JSON is an Array. Since by definition JSON can be an object or an array, I believe it's appropriate to modify the conditional to allow '[object Array]' or perhaps remove the block altogether. Right now, for instance, a formatted JSON array will not be compacted even if the option compact: true is provided since it does not go through dataToEsm. Thanks for consideration.

JSON from commonjs style path (without .json)

Hi, I am not sure if this is a rollup-plugin-json issue. My bundle breaks on a dependency that does

var agents = require('caniuse-db/data').agents

caniuse-db/data is a JSON file that isn't found. I tried to setup namedExports in commonjs without success. Also just tried to replace caniuse-db/data': 'caniuse-db/data.json'. Is this a bug?

Please let me know if I should setup a minimal testing repo

Avoiding generating many top-level fields

I have this in my code:

import packageInfo from '../../package.json';

And this is what gets generated:

const name = "app";
const version = "1.0.0";
...
var packageInfo = {
  name: name,
  version: version,
  ...
};

So a bunch of noise is generated (Eg. dependencies, devDependencies, scripts, etc.)

It would be nice if the following two were enabled.

First: avoiding generating the top-level fields. Instead just this (single object) would be better:

  var packageInfo = {
    name: "app",
    version: "1.0.0",
    ...
  };

Second: providing a way to specify the keys that should be included per included json file. This would allow including just the version field for example.

Looking for some clarification on plugin usage...

I'm a tad behind the times, only just getting into ES6 now, so I apologise if this seems like an obviously simple point; but like many things in life, it's only easy once you know how..

This plugin's readme starts off with an example of import { version } from './package.json';, but then in the usage section it goes into a more verbose example that uses import json from 'rollup-plugin-json';.

Is the package.json import line also powered by this plugin? Or is that simply part of ES6 itself?

Just to give a bit of context here: I'm working on a proprietary JS library that parses configuration stored inside numerous JSON files, then uses a combination of them to render custom data dashboards.. Once I manage to transpile my project with Rollup, it looks like I may be able to use this plugin to bundle a set a predefined widget configurations in a script file. From what I can see, this would effectively allow us to create specialised builds of the overall dashboard project with custom widgets designed for specific customers.

..or am I completely missing the mark here?

Support HJSON

It would be great from this plugin to optionally support HJSON as well. I'm not sure is it better to implement this as an distinct rollup-plugin-hjson or inside this package. Both ways has some peculiarities.

Throw on invalid JSON with array as top-level structure

This plugin is really simple and good. Thank you for your efforts!

But it can be even better if it would check the validity of JSON to insert a little bit better. For example, insertion of JSON with array as top-level structure is available. But contents of JSON is just concatenated to bundled script (not squashed as will be with object as top-level element). preferConst isn't working as well. Neither validation of supplied structure.

It would be better to, at least, warn the user that he supplied something that is not fully supported, or just throw an error.

Quoted properties generate invalid JavaScript

I'm using rollup with the iD project and it's lovely! We're running into one problem importing a large JSON file that includes escaped quotes as property keys. rollup-plugin-json transforms these keys, unescaping the quotes and producing invalid JavaScript:

2016-08-09 at 1 23 pm

I'll push a failing testcase in a moment.

Rolled up JSON assigned to the value "name" doesn't work in-browser

Hi,

I'm sure I'm doing something wrong, but I'm having trouble when rolling up a JSON value where it has a JSON key of "name":

{ "name" : { "key": "name-tag", "value": "Mr Jones" }, "address" : { "key": "address-tag", "value" : "1 Somewhere Street" } }

it rolls-up to the following:

var name = {"key":"name-tag","value":"Mr Jones"}; var address = {"key":"address-tag","value":"1 Somewhere Street"}; var fields = { name: name, address: address };

But it appears that name is defined in the global scope of Chrome, so the value is not overwritten, and the fields.name value is set to the globally scoped name.

I've created a simple project which reproduces the situation at https://github.com/Psigio/rollup-plugin-json-test

Am I missing some configuration option perhaps? One approach I tried was editing the list of reserved words in the https://github.com/rollup/rollup-pluginutils package to include "name" and this seemed to address the issue - the output was:
var address = {"key":"address-tag","value":"1 Somewhere Street"}; var fields = { address: address, "name": {"key":"name-tag","value":"Mr Jones"} };, but I wondered if there was a direct approach in rollup-plugin-json to achieve this?

Thanks!

Jon

CommonJS Require

I am trying to use the plugin to require in package.json to include on the version information. When I look at the resultant bundling, the entire JSON object has been pulled in, recreated, and frozen with Object.freeze. I've tried moving this plugin around to different spots in the plugins array with no success.

My end goal is I just want the version property.

My plugins stack looks like this

const plugins = [
  resolve({
    browser: true,
    preferBuiltins: false,
  }), json(), commonJs(), babel({
    exclude: 'node_modules/**',
    presets: ['es2015-rollup']
  })];

Generate fake AST

Since Rollup can theoretically ingest an AST for a module, we might be able to do a clever hack here – this plugin could generate a fake AST that avoided the initial parse step and subsequent traversals. A similar optimisation could apply to e.g. rollup-plugin-string

Weird/gunky default JSON import output

Why does

import data from './data.json';

...result in this:

var key = "value";
var key2 = 999;
var object = {"prop":999,"prop2":"value"};
var require$$0 = {
    key: key,
    key2: key2,
    object: object
};
var data = require$$0;

...instead of simply this:

var require$$0 = {
  "key": "value",
  "key2": 999,
  "object": {
    "prop": 999,
    "prop2": "value"
  }
};
var data = require$$0;

Named exports

Re @Victorystick's suggestion on rollup/rollup#269 (comment) – it'd be nice to import a single field from e.g. package.json. Right now, this plugin only generates a default export:

export default {
  "name": "my-neato-package",
  "version": "1.33.7",
  "main": "dist/my-neato-package.umd.js",
  ...
};

We could easily generate named exports too:

export var name = "my-neato-package";
export var version = "1.33.7";
export var main = "dist/my-neato-package.umd.js";

export default {
  name: name,
  version: version,
  main: main,
  ...
};

That way, import { version } from './package.json' wouldn't include unnecessary gubbins.

It gets slightly tricky with key names that aren't valid identifiers, like jsnext:main. Do we ignore them, or turn them into valid identifiers?

export var jsnext_main = 'dist/my-neato-package.es6.js';

export default {
  'jsnext:main': jsnext_main,
  ...

};

Could also supply a function as an option that replaces keys for a given file.

Empty JSON keys

There seems to be a problem with handling of empty JSON object keys. Given the following valid JSON object:

{"": "a", "b": "c"}

In a file named test.json, doing import foo from './test.json'; results in the following invalid code being generated:

var  = "a";
var b = "c";
var foo = {
	: ,
	b: b
};

I stumbled upon this working with Jed, which uses empty object keys in its locale data format.

rollup fails when JSON keys contain quotes

with a JSON file like this (test.json):

{
	"a key with \"quotes\"": "foo"
}

and a simple main.js like this

import data from './test.json';
console.log(data);

rollup-plugin-json generates invalid code:

(function () {
'use strict';

var data = {
	"a key with "quotes"": "foo"
};

console.log(data);

}());

Unexpected Token

Upon running the rollup config:

import babel from 'rollup-plugin-babel';
import json from 'rollup-plugin-json';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

export default {
  entry: 'server/server.js',
  format: 'umd',
  dest: 'bundelIndex.js',
  external: ['bluebird', 'knex', 'node-gyp', 'fsevents'],
  plugins: [
    babel({
      exclude: 'node_modules/**',
      babelrc: false,
      presets: ['react', 'es2015-rollup', 'stage-0'],
      plugins: ['transform-decorators-legacy'],
    }),
    json(),
    nodeResolve({ jsnext: true, main: true}),
    commonjs(),
  ],
};

I get the following error at runtime:

/Users/gigavinyl/Projects/ceres/server/assets.json: Unexpected token (1:5)
SyntaxError: /Users/gigavinyl/Projects/ceres/server/assets.json: Unexpected token (1:5)
{"js":"bundle.79f6da3830e25bcf5a6a.min.js"}

This appears to conform to the usage demonstrated in the README, what am I doing wrong here? Or is this an actual bug perhaps?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.