Using RequireJS with legacy code

拈花ヽ惹草 提交于 2019-12-05 16:35:59

I don't know if I fully grasp the problem at hand, but I think a the shim or map functions of RequireJS will help you out.

Extract the parts you want in a new module from your huge javascript file. Then tell RequireJS that your huge javascript file is a dependecy for this new module using shim. Something like:

requirejs.config({
    shim: {
        'new-module': {
            deps: ['huge-javascript-file'],
            exports: 'NewModule'
    }
});

Shim documentation: http://requirejs.org/docs/api.html#config-shim

The map function might be useful when only portions of your new code have to use your old huge file. Check out this documentation: http://requirejs.org/docs/api.html#config-map

I don't think there is One True Way to achieve this, but I've approached a similar problem by defining module "facades" around the globally scoped code. Let's say your legacy scripts define a global variable called foo. You can define a AMD module and export that variable from it:

//foo.js
define(function() {
  return window.foo;
});

//bar.js
define(['foo'], function(foo) {
  //do something with foo
});

This way you only need to write a single-line facade every time you need to use a new piece of the existing, globally defined code, without breaking existing code which expects the same code to be globally defined. Over time you can move and refactor the actual implementation into the module without breaking consumer code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!