eight04/rollup-plugin-cjs-es

any chance of adding json handling?

Closed this issue · 5 comments

hey @eight04 ,

this is possible in Node:

const cfg = require("./config.json");

it would be useful if cjs-es could transform this into a static constant instead of:

UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token (2:34)

thanks!

You need rollup-plugin-json to load JSON files. Also, the plugin order does matter:

import json from "rollup-plugin-json";
import cjs from "rollup-plugin-cjs-es";
export default {
  ...
  plugins: [
    json(), // before cjs transform
    cjs()
  ]
}

thanks!

Also, the plugin order does matter:

i haven't tried it yet, but how exactly would json -> cjs order work if rollup has no knowledge of how to process a chain of require calls? let's say the const cfg = require("config.json"); is not in the entry file but 2 or 3 requires deep.

Rollup can only process ES6 modules. When a file is loaded (by import statements or the entry point), it would be passed into multiple transformers that are provided by plugins.

cjs-es plugin only transforms CommonJS statements from:

const cfg = require("./config.json");

to

import * as cfg from "./config.json";

Therefore, rollup would detect the config.json file, resolve it to absolute path, then load the file.

When loading config.json, json plugin involves. It would transform JSON from:

{
  "foo": "bar"
}

to something like

const _1 = "bar";
export {_1 as foo};

(I didn't look into the json plugin so the implementation might be different, but the idea is the same)

In the end, all files are transformed and collect, then rollup bundles them into one single file.

tried it, it seems to work. thanks!