简体   繁体   English

允许用户管理npm模块的依赖版本

[英]Allow users to manage dependency version of an npm module

I'm building a module that will have THREE.js as a dependency. 我正在构建一个将THREE.js作为依赖项的模块。 I'm trying to work out the best way to include THREE as a dependency and make it accessible to the module and users of the module (users will need access to the THREE library within their projects). 我正在尝试找出将三作为依赖项并使其可供模块和模块用户访问的最佳方法(用户将需要在其项目中访问三库)。 There are two ways I have figured out of making this work: 我想出了两种方法可以完成这项工作:

One: 一:

Add THREE as a dependency of the module, import the whole library in the module and add it as a global variable like so: 添加三个作为模块的依赖项,将整个库导入模块,然后将其添加为全局变量,如下所示:

import * as THREE from 'three'; 
window.THREE = THREE;

The disadvantage here is that I am responsible for what version of THREE is used, and also that the whole library is imported (THREE has recently switched to a modular build so it is no longer neccessary to include the whole library). 这里的缺点是我要负责使用哪个版本的THREE,还要负责导入整个库(THREE最近已切换到模块化构建,因此不再需要包括整个库)。

Two: 二:

Add THREE as a dependency of the module and require users to add it as a dependency of their project. 将三个添加为模块的依赖项, 要求用户将其添加为项目的依赖项。 The idea here is that I can now import only what I need from the project: 这里的想法是,我现在只能导入项目中需要的内容:

import { Scene, Camera } from 'three'; 

And users can import what they need in their project, resulting in smaller file size. 用户可以在项目中导入所需的文件,从而减小文件大小。

The problem here is that now there are two copies of THREE installed, which are potentially different and incompatible versions. 这里的问题是,现在安装了两个THREE的两个副本,它们可能是不同的且不兼容的版本。 Is there any way to point my module to the top level module so that they can manage the version of THREE that is installed? 有什么办法可以将我的模块指向顶层模块,以便他们可以管理已安装的THREE的版本?

The way I ve seen it done is similar to this, but I never had to do something like it in production, so I do not know personally of its strength: 我所看到的完成方式与此类似,但是在生产中我从来不需要做类似的事情,因此我个人不知道它的优势:

main.js: main.js:

'use strict';
const three = require('three'),
    mod = require('yourModule');

mod.init(three);
//...

yourModule.js: yourModule.js:

'use strict';
let three = {};
function init(t) {
    three = t;
}
//...
modules.export = {
    init: init
    //...
};

Or 要么

main.js: main.js:

'use strict';
const three = require('three'),
    mod = require('yourModule')(three);

yourModule.js: yourModule.js:

'use strict';
module.exports = (three) => {
    //...
};

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

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