简体   繁体   English

如何动态加载节点模块以进行Browserify转换

[英]How to dynamically load node module for browserify transform

I am working on a browserify transform that I hope will have the ability to have extensions. 我正在开发一个browserify转换,希望它能够具有扩展功能。

//excerpt from package.json of my application that is using my transform and extension
"browserify": {
  "transform": [
    ["mytransform", {"extensions": ["my-extension"] } ]
  ]
}

In the example above, I want the user to be able to specify other node modules that are interpreted within my transform as an extension. 在上面的示例中,我希望用户能够指定在我的转换中解释为扩展的其他节点模块。

Within my transform code, I have the following to load the extensions: 在我的转换代码中,我可以执行以下操作来加载扩展:

//lines 347-349 of mytransform/index.js
var extensions = options.extensions.map(function(extensionId){
                                            return require(extensionId)();
                                          });

When I run my code, I see the following 运行代码时,我看到以下内容

module.js:340
    throw err;
    ^
Error: Cannot find module 'my-extension'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at /Users/pdgreen/Documents/Personal/github/mytransform/index.js:348:52
    at Array.map (native)
    at module.exports (/Users/pdgreen/Documents/Personal/github/mytransform/index.js:347:39)
    at nr (/Users/pdgreen/Documents/Personal/github/myproject/node_modules/browserify/node_modules/module-deps/index.js:231:23)
    at /Users/pdgreen/Documents/Personal/github/myproject/node_modules/browserify/node_modules/resolve/lib/async.js:48:21
    at /Users/pdgreen/Documents/Personal/github/myproject/node_modules/browserify/node_modules/resolve/lib/async.js:127:35

My extension is available to node because if I do require('my-extension') within my application, it loads without issue. 我的扩展名可用于节点,因为如果我在应用程序中确实require('my-extension') ,则它会加载而不会出现问题。 It seems like the resolving code that runs for my transform is too restrictive. 似乎为我的转换运行的解析代码过于严格。 What am I missing? 我想念什么?

It turns out my problem was related to symbolic links. 原来我的问题与符号链接有关。 Since I was still developing my transform and extension, I had created symbolic links from my application to those modules. 由于我仍在开发转换和扩展,因此我创建了从应用程序到这些模块的符号链接。 I guess require was following the symbolic links and jumping out of my application node_modules directory so it couldn't resolve my extension. 我猜require会跟随符号链接并跳出我的应用程序node_modules目录,因此它无法解析我的扩展名。 Once I learned about npm link and started using it instead of standard symbolic links, everything started working. 一旦我了解了npm链接并开始使用它而不是标准的符号链接,一切就开始起作用。

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

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