使用Webpack将库打包为包管理

huangapple go评论72阅读模式
英文:

Packaging libraries as package management using Webpack

问题

你好,

我有一个依赖许多库(jQuery、moment.js、underscore 等)的遗留应用程序。这些库曾经是手动组装的并添加到仓库中,它们之间松散耦合。我的愿望是将其迁移到现代包管理器,比如 npm 或 yarn,以避免在需要更新版本时手动管理大量依赖项。

我尝试过使用 webpack,但不知何故无法以一种使它们在全局范围内可用的方式捆绑这些库(我知道这是一种反模式,但我没有资源来重写遗留代码)。

是否有可能这样做?

即定义一个 dependencies.js 文件,其中包含 require(xx) 行,然后将其作为脚本加载到浏览器中,以使库在全局范围内可用,而不是从本地源分别加载每个库?

英文:

Good day,

I have a legacy application, dependant on many libraries (jQuery, moment.js, underscore...). The libraries were once assembled manually and added to the repo, and are loosely coupled. My wish is to port this to a modern package manager, such as npm or yarn, to avoid manually managing a bunch of dependencies when a version update is due.

I've tried using webpack, but am somehow unable to bundle these libraries in a way the they would be globally available (I am aware that this is an anti-pattern, but I do not have the resources to rewrite the legacy code).

Is it possible to do so?

IE define a dependencies.js file with require(xx) lines, and load that as a script in the browser, making the libs available globally instead of loading each one separately from a local source?

答案1

得分: 0

使用webpack,在您的入口点文件中,您可以导入所有库并将它们添加到全局作用域。然后,您可以通过动态导入来调用您的旧代码,从而设置全局变量。

import $ from "jquery"
import _ from "lodash"
import moment from "moment"

window.$ = $
window._ = _
window.moment = moment

import("./yourOldCode")
英文:

With webpack, in your entry point file you can import all librairies and add them to the global scope. Then you can call your old code in a dynamic import, so global variables will be set.

import $ from "jquery"
import _ from "lodash"
import moment from "moment"

window.$ = $
window._ = _
window.moment = moment

import("./yourOldCode")

huangapple
  • 本文由 发表于 2023年6月19日 19:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定