two.js: `var root = this` breaks in bundlers.

Using var root = this seems to be breaking Rollup.js bundle. The resulting bundle looks something like

(function() {
"use strict"
commonjsGlobal.Two = (function() {
// Inside here it Two.js code...

var root = this // but this is not window

// ...

})()

})()

The issue is here: https://github.com/jonobr1/two.js/blob/e791c2c57cc799522d8795fdb5d9c3bbb12005e6/src/two.js#L3

My Rollup bundle is importing Two from the two.js npm package.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 18 (12 by maintainers)

Most upvoted comments

I’m trying to bundle it with Rollup. It’s the same use case as @trusktr.

Here’s the config.

import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
import camelCase from 'lodash.camelcase';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';

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

const libraryName = pkg.name;

export default {
  input: `src/${libraryName}.test.js`,
  output: [
    { file: pkg.main, name: camelCase(libraryName), format: 'umd' },
    { file: pkg.module, format: 'es' },
  ],
  sourcemap: true,
  // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
  external: [],
  watch: {
    include: 'src/**',
  },
  plugins: [
    // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
    commonjs(),
    // Allow node_modules resolution, so you can use 'external' to control
    // which external modules to include in the bundle
    // https://github.com/rollup/rollup-plugin-node-resolve#usage
    resolve(),

    // Resolve source maps to the original source
    sourceMaps(),

    serve({
      contentBase: ['dist', 'src', 'node_modules/mocha'],
    }),

    livereload()
  ],
};

Is this fixed? I’m still getting the error.

There’s actually a more standard way to reference the global context: self

After doing that, I am able to import Two in Rollup-bundled code.