Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Facebook JS SDK in a Module (webpack)

I'm using webpack to keep my JavaScript code organized in modules but I'm running into a problem trying to load the Facebook JS SDK. I've tried using the externals option of webpack but since the library is loaded asynchronously I don't think it will provide the answer I am looking for.

There was an issue for webpack that addressed this problem. However, I don't think it works any longer. https://github.com/webpack/webpack/issues/367

What would be a good approach to this problem? Should I just load the SDK synchronously?

like image 477
adam-beck Avatar asked Jan 20 '26 03:01

adam-beck


1 Answers

As webpack is just a module bundler you should use a module loader to do the job, as RequireJS if you want to use AMD modules or simply use this lib script.js that you can do like that.

import $script from "scriptjs";

$script("//url/thescript.js", () => {
  // ...
});

EDIT: Wrapping in something more simple to use:

import $script from "scriptjs";

export default function importAsync(url) {
  return new Promise((resolve, reject) => {
    $script(url, resolve); //just a simple, version. You should treat the reject case
  });
});

And then simply use it like:

//...
importAsync("//url.to/script.js").then(module => {
  //...
})

This way will be much more simple if you want to change your module loader in the future :)

like image 57
Rubens Pinheiro Avatar answered Jan 21 '26 19:01

Rubens Pinheiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!