Code Monkey home page Code Monkey logo

rollupify's Introduction

rollupify Build Status No Maintenance Intended

Browserify transform to apply Rollup, converting ES6/ES2015 modules into one big CommonJS module.

This tends to result in smaller bundle sizes, due to Rollup's tree-shaking and scope-hoisting capabilities.

⚠️ Maintenance notice: This repo is unmaintained. I consider it largely a hack for migrating existing Browserify/CommonJS projects to Rollup/ESM. Probably you should just use Rollup instead, with plugins like rollup-plugin-commonjs and rollup-plugin-node-resolve, or manually run rollup before browserify.

Usage

npm install rollupify

Then:

browserify -t rollupify index.js > output.js

Or in your package.json:

"browserify": {
  "transform": ["rollupify"]
}

Example

Input:

// index.js
import hello from './hello';
console.log(hello);
export default hello;
// hello.js
export default "hello world";

Output:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
'use strict';

var hello = "hello world";

console.log(hello);

module.exports = hello;
},{}]},{},[1]);

Using alongside other transforms

If you are using other transforms like babelify, make sure you apply the transforms in the right order. rollupify should apply before babelify:

browserify -t rollupify -t babelify index.js > output.js

Or when configuring:

"browserify": {
  "transform": ["rollupify", "babelify"]
}

Details

rollupify only works on ES6/ES2015 modules. Any require() statements will be left untouched, and passed on to Browserify like normal.

Sourcemaps are supported, assuming you pass --debug or {debug: true} into Browserify.

Need more evidence that Rollup and ES6 modules are awesome? See rollup-comparison and A better build system with Rollup.

Need to get started converting your CommonJS codebase into ES6? Try cjs-to-es6.

Customising rollup

Given a rollup.config.js like:

module.exports = {
  plugins: [
    require('rollup-plugin-babel')({
      exclude: 'node_modules/**'
    })
  ]
}

Use it through the command line:

browserify -t [ rollupify --config rollup.config.js ] index.js > output.js

Or in your package.json:

"browserify": {
  "transform": ["rollupify", {"config": "rollup.config.js"}]
}

If you are using Browserify in JavaScript, you can also pass in the config object directly:

var b = browserify('./')
  .transform('rollupify', {
    config: { /* your rollup config goes here */ }
  }).bundle();

rollupify's People

Contributors

drpicox avatar greenkeeperio-bot avatar jpweeks avatar nolanlawson avatar tivac 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

rollupify's Issues

watchify + rollupify generates a weird warning when using a dependency in node_modules

Example repo : https://github.com/DavidBruant/rollupify-bug-example

In this repo, I have this:

$ npm run watch-roll

> [email protected] watch-roll /home/david/projects/rollupify-bug-example
> watchify main.js -t rollupify -o bundle-rollup.js -d -v

'lodash.memoize' is imported by main.js.tmp, but could not be resolved – treating it as an external dependency
47294 bytes written to bundle-rollup.js (0.34 seconds) at 16:59:38

This warning ("but could not be resolved") does not exist when I try to compile with babelify for instance.

Doesn't support JSX

According to docs I've a correct setup of transforms [rollupify, babelify].

In my .babelrc I've:

{
  "presets": [
    "stage-1",
    ["es2015", {"loose": true}],
    "react"
  ]
}

When I try to use rollupify with react, I get a message like:

Error: Unexpected token (39:6) in /home/file.js while parsing file: /home/app.js

Errors are thrown for JSX (return <jsx>) appearances like:

return (
      <DropdownButton />
)

Is there some kind of workaround for this?

require('./...') does not works as expected.

Rollupify does not works exactly as one expect that it should do.

rollupify only works on ES6/ES2015 modules. Any require() statements will be left untouched, and passed on to Browserify like normal.

But it happens that because it concatenates all files into the current one, when browserify process requires it looses the path.

For example:

// index.js
import { Bob } from './people/bob.js';
Bob.wave();
// ./people/bob.js
let text = require('./text.json');
export class Bob {
    wave() { console.log(text.hello); }
}

Does not work:

Error: Cannot find module './text.json' from '/Users/.../rollupify-poc'

but with this change, it works:

// ./people/bob.js
let text = require('./people/text.json');
export class Bob {
    wave() { console.log(text.hello); }
}

Which is not the expected, neither the convenient.

Missing support for direct rollup configuration

It would be nice if I could directly configure rollup from code instead of having to specify my rollup config in a rollup.config.js file.

Right now I have:

builder.transform("rollupify", { config : "./rollup.config.js" });

but I'd really prefer

builder.transform("rollupify", {
    config : {
        plugins : [ ... ]
        onwarn : function() { ... }
    }
});

Is that something you'd be willing to accept a PR for? I almost always write an actual JS file to drive browserify and would prefer to keep the configuration in that same code instead of scattered around.

errors not emitting to browserify

I noticed the issue #10 about rollupify not emitting errors correctly.

In some situations I can confirm this is still happening. When I modify the code like this

.catch(function (err) {
      console.log('error', err); //this prints the error, but it doesn' get seen by browserify
      self.emit('error', err);
    })

that console.log gets hit and does indeed print the correct error. The error does not get printed by the browserify process itself. Usually in this scenario I can also look through my file tree and find the last file the plugin fails on. It will do something like this:

somefile.js
somefile.tmp.js <----leftover after a 'silent' failure

When i log the error I'll get the actual rollup error such as "unexpected token/parser error" or something similar. I see the failing test you have on the PR, and I'm not sure why this is the case. It looks like an adequate test at face value.

so my setup:

I am using the standalone browserify module inside of a gulp task. I am not using the blacklisted gulp plugin, simply calling browserify directly via the js api like this:

 browserify()
    .transform(rollupify)
    .bundle()
    .on('error', function(err){
        console.log(err.message); //this is never called.
        this.emit('end'); 
    })

I hope that helps. Simply logging the error in the .catch() has been good enough to help me find my problems, but I have to modify the package every time I install during development. let me know if you have any questions.

Also jsut so you know: I am also using babelify and uglfyify in my pipeline, but removing and adding them does not seem to affect the behavior I described.

Edit: I'm closing this, looks like its working for me now. Sorry to sound the alarm. Thank you for the great module, too :)

When a project is big enough, watchify + rollupify stops rebuilding on watch

I'm having the problem in this repo https://github.com/dtc-innovation/dataviz-finances-gironde
Install with after clone

npm i 
npm run watch

I get the following output :

> [email protected] watch /home/david/projects/dataviz-finances-gironde
> watchify client/js/main.js -t rollupify -o client/js/browserify-bundle.js -d -v

'redux' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react-dom' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'd3-dsv' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'immutable' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'lodash.memoize' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react-redux' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'immutable' is imported by client/js/finance/hierarchicalAggregated.js, but could not be resolved – treating it as an external dependency
'immutable' is imported by client/js/finance/m52ToAggregated.js, but could not be resolved – treating it as an external dependency
'lodash.memoize' is imported by client/js/objectId.js, but could not be resolved – treating it as an external dependency
'uuid' is imported by client/js/objectId.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/TopLevel.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/M52Viz.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/Sunburst.js, but could not be resolved – treating it as an external dependency
'd3-shape' is imported by client/js/components/Sunburst.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/SunburstSlice.js, but could not be resolved – treating it as an external dependency
'd3-shape' is imported by client/js/components/SunburstSlice.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/AggregatedViz.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/TextualAggregated.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/TextualSelected.js, but could not be resolved – treating it as an external dependency
'immutable' is imported by client/js/components/TextualSelected.js, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/components/RDFISelector.js, but could not be resolved – treating it as an external dependency
2773384 bytes written to client/js/browserify-bundle.js (3.29 seconds) at 17:02:31

Works fine the first time.

When I edit main.js, the output is as follow:

'redux' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react-dom' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'd3-dsv' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'immutable' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'lodash.memoize' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
'react-redux' is imported by client/js/main.js.tmp, but could not be resolved – treating it as an external dependency
Error: Could not load uuid (imported by /home/david/projects/dataviz-finances-gironde/client/js/objectId.js): ENOENT: no such file or directory, open 'uuid' while parsing file: /home/david/projects/dataviz-finances-gironde/client/js/main.js

From various testing (including what I did for #53 ), it looks like rollupify is the changing factor that leads to this problem.

I'm on Ubuntu, @oncletom is on OSX but has met the same problem.

Pass CLI options into Rollup

I'm trying to minify my final bundle and found this tiny plugin that seems to do the job. However, it seems that rollupify is bypassing the CLI options.

This is my current command:

$ browserify source/scripts -t [ rollupify --plugins [ rollup-plugin-uglify ]  ] -t [ babelify --presets [ es2015 ] ] -do public/bundle.js

Am I doing something wrong?

Does not complain on invalid formats

When I pass on an invalid rollupjs format like sadfsdfsdf it does not complain. But should.

Here the gulp task I am using:

gulp.task('browserify', ['clean:js'], function (cb) {
  const entry = path.join(__dirname, '/src/index.js')
  const bundler = browserify({
    entries: [entry],
    basedir: __dirname,
    globals: false,
    debug: !options.minify // enables inline source maps
  })

  pump([
    bundler
      .transform('rollupify', {
        cache: cache,
        format: 'sadfsdfsdf', <------ why is not an error thrown?
        config: {
          format: 'sadfsdf' <------ why is not an error thrown?
        }
      })
      .require(entry, {expose: 'videomail-client'})
      .bundle(),
    source('./src/'), // gives streaming vinyl file object
    buffer(), // required because the next steps do not support streams
    plugins.concat('videomail-client.js'),
    gulp.dest('dist'),
    plugins.if(options.minify, plugins.sourcemaps.init()),
    plugins.if(options.minify, plugins.uglify()),
    plugins.if(options.minify, plugins.rename({suffix: '.min'})),
    plugins.if(options.minify, plugins.sourcemaps.write('/')),
    plugins.if(options.minify, gulp.dest('dist')),
    plugins.connect.reload()
  ], cb)
})

why is `opts.sourceMaps`?

Hell yea, I think I finally got great combo with browserify and rollupify :)

But looking at the code, I don't understand and don't like that opts.sourceMaps thing. Rollup gets sourceMap option. Why not just let Object.assign do its job.

I mean, just remove

var doSourceMap = opts.sourceMaps !== false;

and change to

      return rollup.rollup(Object.assign(config, opts.config || opts, {
        cache: cache,
        entry: tmpfile
      }))

it won't force you to pass sourceMaps, when you have it from rollup config

edit: just don't see sense to override config (the sourceMap prop)

app goes blank with rollupify

Hi, I'm trying to get rollupify into react-css, but simply enabling the transform gives me a blank app. I have a branch to reproduce this - the commit right before HEAD shows rectangles on the screen; after the last commit, which is just to add the transform, the screen goes blank, no errors either. am I doing something wrong? you can reproduce with npm install && npm start, and opening http://localhost:9966 if you'd like. I'll investigate some more, but not sure what to look for yet. Please and thank you!

Why does it remove the require function?

Seeing Uncaught ReferenceError: require is not defined here. Browserify usually adds that function but rollupify seems to remove it?

For reference, here my gulp task:

gulp.task('browserify', ['clean:js'], function (cb) {
  const entry = path.join(__dirname, '/src/index.js')
  const bundler = browserify({
    entries: [entry],
    basedir: __dirname,
    globals: false,
    debug: !options.minify // enables inline source maps
  })

  pump([
    bundler
      .transform('rollupify', {
        cache: cache,
        format: 'cjs'
      })
      .require(entry, {expose: 'videomail-client'})
      .bundle(),
    source('./src/'), // gives streaming vinyl file object
    buffer(), // required because the next steps do not support streams
    plugins.concat('videomail-client.js'),
    gulp.dest('dist'),
    plugins.if(options.minify, plugins.sourcemaps.init()),
    plugins.if(options.minify, plugins.uglify()),
    plugins.if(options.minify, plugins.rename({suffix: '.min'})),
    plugins.if(options.minify, plugins.sourcemaps.write('/')),
    plugins.if(options.minify, gulp.dest('dist')),
    plugins.connect.reload()
  ], cb)
})

Parsing fails when used with `rollup-plugin-json`

Given a file index.js that contains the following:

import {version} from './package.json';
console.log(version);

Running rollup with the rollup-plugin-json plugin works fine:

var rollup = require('rollup')
var json = require('rollup-plugin-json')

rollup.rollup({
  entry: 'index.js',
  format: 'iife',
  plugins: [json()]
}).then(b => console.log(b.generate().code))

But running rollupify with the same config does not:

var rollupify = require('rollupify')
var browserify = require('browserify')
var json = require('rollup-plugin-json')

var b = browserify('index.js')
b.transform(rollupify, {
  format: 'iife',
  plugins: [json()]
})
b.bundle()

It instead rejects a promise as follows:

Error: Unexpected token while parsing file: index.js

Is this somehow related to #55, or am I just doing it wrong?

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.