27

I have an ES6 application (with Babel 6.5 and Webpack) and it successfully imports my modules like this:

import $ from 'jquery';

I wanted to install https://github.com/robflaherty/riveted/blob/master/riveted.js (a plugin for Google Analytics), but as you can see, the code doesn't have something like module.exports = ..., it only defines a global variable riveted, but it has an apparently valid package.json pointing to riveted.js.

So doing something like

import riveted from 'riveted'
riveted.init();

throws an error:

_riveted2.default.init is not a function

import riveted from 'riveted'
riveted.init();
import 'riveted'
riveted.init();

throws an error:

riveted is not defined

import * as riveted from 'riveted'
riveted.init();

throws an error:

riveted.init is not a function

How can I access riveted's init() function?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
grssnbchr
  • 2,877
  • 7
  • 37
  • 71
  • 2
    Try doing `import * as riveted from 'riveted'` – thomaux Apr 18 '16 at 07:26
  • Are you trying to run this in a browser? – slebetman Apr 18 '16 at 07:34
  • Yes @slebetman. @Anzeo thanks but this gives me a yet slightly different error `riveted.init is not a function`. By the way, `riveted` is correctly "installed" into `node_modules/riveted`. – grssnbchr Apr 18 '16 at 07:54
  • @wnstnsmth Looks like you need to use the [exports-loader](https://github.com/webpack/docs/wiki/shimming-modules#the-file-sets-a-variable-in-the-global-context-with-var-xmodule--) to shim the module as it's not properly exported – CodingIntrigue Apr 18 '16 at 07:57
  • Then just include riveted.js in a script tag before the rest of your script. There is no need to require. It is already browser code, not node.js code that you need to make work in a browser. – slebetman Apr 18 '16 at 08:02
  • did you tried with `import { default as es6Module } from 'es5Module';` ? – Isidro Martínez Aug 11 '16 at 19:29

2 Answers2

26

You can use the webpack exports loader:

var riveted = require("exports?riveted!riveted")

See the shiming modules overview for details

jantimon
  • 36,840
  • 23
  • 122
  • 185
0

Step 1. modify riveted.js

Add some code after line 18.

    // Browser global
    root = !root && typeof self == 'object' ? self : root; // add this line
    root.riveted = factory();

Because the this is undefined when the file is imported by es6, we use self instead.

self is better than window, it works in both main thread and worker.

Step 2. modify your import path

like this:

    import './riveted.js';
    riveted.init();

The ./ or ../ is required for import js file directly.

Examples:

import `./file.js`
import `../file.js`
import `./a/b/file.js`
import `../a/b/file.js`
import `../../a/b/file.js`

Tested in chrome.

cuixiping
  • 24,167
  • 8
  • 82
  • 93