How to import "old" ES5 code in ES6
Asked Answered
S

2

28

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?

Sextans answered 18/4, 2016 at 7:21 Comment(6)
Try doing import * as riveted from 'riveted'Ceporah
Are you trying to run this in a browser?Carious
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.Sextans
@wnstnsmth Looks like you need to use the exports-loader to shim the module as it's not properly exportedNarthex
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.Carious
did you tried with import { default as es6Module } from 'es5Module'; ?Eisenstein
A
26

You can use the webpack exports loader:

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

See the shiming modules overview for details

Ares answered 18/4, 2016 at 7:59 Comment(1)
this was a HUGE help to me in a project. thank you so much.Carper
N
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.

Neurogenic answered 30/8, 2022 at 2:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.