How can i dynamically load CommonJs module?

Viewed 957

I'am working on app with React, TS and Webpack stack.

I need to implement feature that allows my app work with client plugins - js files that override existing functionality of some classes. It can be loaded from anywhere - local file system or remote repository and should be fetched in the runtime, because i need to have an option to specify new extension in config and just press F5.

Dynamic import is not my case, because as far as i understand Webpack needs to be able to at least guess roughly what an import() is meant to be referencing. Using simple 'get' request might be an option, but how can i use loaded script as CommonJS module in this case? And am i correct about dynamic import behavior?

1 Answers

You can use @paciolan/remote-module-loader to remotely load a common js module.

import { createLoadRemoteModule } from "@paciolan/remote-module-loader"

const main = async() => {
  const loadRemoteModule = createLoadRemoteModule()
  const myModule = await loadRemoteModule("http://fake.url/modules/my-module.js")

  const value = myModule.default()
  console.log({ value })
}

main()

If you need to pass dependencies to the module:

import {
  createLoadRemoteModule,
  createRequires
} from "@paciolan/remote-module-loader"

const dependencies = {
  react: require("react")
}

const main = async() => {
  const requires = createRequires(dependencies)
  const loadRemoteModule = createLoadRemoteModule({ requires })
  const myModule = await loadRemoteModule("http://fake.url/modules/my-module.js")

  const value = myModule.default()
  console.log({ value })
}

main()

If need to load a React Component, check out @paciolan/remote-component

You may have to take extra steps if you have a Content Security Policy (CSP) set.

Related