GithubHelp home page GithubHelp logo

rolldown-old / old-rolldown Goto Github PK

View Code? Open in Web Editor NEW
73.0 3.0 1.0 93 KB

Modern bundler built on Rollup with couple more features, such as multiple entry points, presets, better configuration experience and more.

License: MIT License

JavaScript 100.00%
rollup bundler modern es2015 es2015-modules modules es6

old-rolldown's Issues

rolldown 2019

const fs = require('fs');
const path = require('path');
const rollup = require('rollup');
const argParser = require('mri');
const commonjs = require('rollup-plugin-commonjs');
const progress = require('rollup-plugin-progress');
const filesize = require('rollup-plugin-filesize');
const resolve = require('rollup-plugin-node-resolve');
const terser = require('rollup-plugin-terser');
const babel = require('rollup-plugin-babel');
const json = require('rollup-plugin-json');
const builtinModules = require('builtin-modules');

function prettierPlugin() {
  return {
    name: 'rollup-plugin-prettier-bundle',
    generateBundle(output) {},
  };
}

async function createConfig(input, options) {
  const opts = Object.assign({}, options);
  const extMap = {
    es: '.mjs',
    cjs: '.js',
  };
  const destMap = {
    es: 'module',
    cjs: 'main',
  };

  const cwd = process.cwd();
  const outDir = (x) => opts.outDir || path.join(cwd, 'dist', destMap[x]);
  const outFile = (x) => path.join(outDir(x), `index${extMap[x]}`);

  const join = (...x) => path.join(cwd, ...x);

  const pkg = require(join('package.json'));

  const exts = arrayify(opts.extensions);
  const extensions =
    exts.length > 0 ? exts : ['.js', '.jsx', '.mjs', '.ts', '.tsx'];

  const possibleInputs = [
    input,
    join('index.js'),
    join('src', 'index.js'),
    join('src', 'index.mjs'),
    join('src', 'index.ts'),
  ];

  // first existing, for now
  const [inputFile] = possibleInputs.filter((x) => fs.existsSync(x));
  const license = `/** Released under the ${opts.license ||
    pkg.license} License. See LICENSE file. */`;

  const outMap = {
    cjs: {
      exports: 'named',
      banner: license,
      file: outFile('cjs'),
      format: 'cjs',
      preferConst: true,

      // don't break oldschool/classic/normal node.js
      outro: 'module.exports = exports.default || exports;',
    },
    es: {
      exports: 'named',
      banner: license,
      file: outFile('es'),
      format: 'es',
      preferConst: true,
    },
  };
  outMap.esm = outMap.es;

  let formats = arrayify(opts.format)
    .reduce((acc, x) => acc.concat(x.indexOf(',') > -1 ? x.split(',') : x), [])
    .filter(Boolean);

  let output = null;

  if (formats.length === 0) {
    formats = ['cjs', 'es'];
  }
  if (formats.length === 1) {
    output = outMap[formats[0]];
  } else {
    output = formats.map((x) => outMap[x]);
  }

  return {
    input: inputFile,
    output,

    external: builtinModules,

    inlineDynamicImports: true,
    experimentalTopLevelAwait: true,

    plugins: [
      progress(),
      resolve({
        preferBuiltins: true,
        module: true,
        jsnext: true,
        main: true,
      }),
      json({ preferConst: true }),
      babel({
        exclude: 'node_modules/**',
        externalHelpers: true,
        extensions,
      }),
      commonjs({
        extensions,
      }),
      opts.minify && terser.terser(),
      filesize({
        showBrotliSize: true,
        showGzippedSize: true,
        showMinifiedSize: true,
      }),
    ],
  };
}

const argv = argParser(process.argv.slice(2), {
  alias: {
    i: 'input',
    d: ['out-dir', 'outdir', 'outDir'],
    f: 'format',
    m: 'minify',
    x: ['ext', 'extensions'],
    l: ['license'],
  },
});

let ROLLUP_CACHE = null;

createConfig(argv.input || argv._[0], argv)
  .then(async (cfg) => {
    const bundle = await rollup.rollup(
      Object.assign({}, cfg, { cache: ROLLUP_CACHE }),
    );

    ROLLUP_CACHE = bundle.cache;

    arrayify(cfg.output).map(async (outputOptions) => {
      await bundle.write(outputOptions);
    });
  })
  .catch(console.error);

function arrayify(val) {
  if (!val) return [];
  if (Array.isArray(val)) return val;
  return [val];
}

run with

node rolldown.js [src/index.js]

by defaults tries index.js, src/index.js, src/index.mjs and src/index.ts, works with TypeScript out of the box and generates CJS and ESM bundles with bundled deps.

more API

rolldown.transform = (source, options) => {
  if (!source) {
    // or something like that
    // (need more strict check for that param)
    return Promise.reject(new TypeError('expect a string'))
  }

  return utils.tmpFile(source).then((file) => {
    options.entry = file.path
    delete options['source']

    // we don't want to (force to not) write to disk
    // but resolve `{ code, map }` object
    delete options['targets']
    delete options['dest']

    return rolldown(options)
  })
}

rolldown.plugin = (plugin, options) => {
  rolldown.plugins.push([plugin, options])
  return rolldown
}

// usage

// { name: 'my-awesome-plugin', transform: (code, id) => {} }
rolldown.plugin(Object)

 // e.g. buble
rolldown.plugin(Function)

// e.g. buble, { target: { node: '4' } }
rolldown.plugin(Function, Object)

// e.g. 'buble'
rolldown.plugin(String)

// e.g. 'buble', { target: { node: '4' } }
rolldown.plugin(String, Object)

rolldown.transform('some source code', {
  plugins: [
    'commonjs',
    ['node-resolve', { jsnext: true }],
    ['buble', { target: { node: '4' } }]
  ]
}).then(({ code, map }) => {})

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.