简体   繁体   English

如何动态加载 CommonJs 模块?

[英]How can i dynamically load CommonJs module?

I'am working on app with React , TS and Webpack stack.我正在使用ReactTSWebpack堆栈开发应用程序。

I need to implement feature that allows my app work with client plugins - js files that override existing functionality of some classes.我需要实现允许我的应用程序与客户端插件一起工作的功能 - 覆盖某些类的现有功能的js文件。 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 .它可以从任何地方加载 - 本地文件系统或远程存储库,并且应该在runtime获取,因为我需要有一个选项来在配置中指定新的扩展名,然后只需按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.动态导入不是我的情况,因为据我所知, Webpack至少需要能够粗略地猜测import()意味着引用什么。 Using simple 'get' request might be an option, but how can i use loaded script as CommonJS module in this case?使用简单的“获取”请求可能是一种选择,但在这种情况下我如何使用加载的脚本作为CommonJS模块? And am i correct about dynamic import behavior?我对动态导入行为是否正确?

You can use @paciolan/remote-module-loader to remotely load a common js module.你可以使用@paciolan/remote-module-loader来远程加载一个普通的js 模块。

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如果需要加载 React 组件,请查看@paciolan/remote-component

You may have to take extra steps if you have a Content Security Policy (CSP) set.如果您设置了内容安全策略 (CSP) ,您可能需要采取额外的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM