获取browserify需要path的行为更像requirejs

我发现当移动文件时经常需要重写包含path的文件,这是相对于新文件夹而言的。

我想在我的browserify代码中避免这个问题:

var View = require('../../../../base/view'); 

并且在requirejs里面做更多的事情,它知道我的基本path是js

 var View = require('base/view'); 

你应该使用paths选项。 在browserify中没有logging,但在node-browser-resolve (在引擎盖下)使用:

paths – 如果在正常的node_modulesrecursion步骤中找不到任何东西,则使用require.paths数组

这里最好的select是使用aliasify插件,可以在这里find 。 然后,只需在package.json添加如下内容,其中aliasify config中的所有path都与该文件的位置相关:

  "browserify": { "transform": [ "aliasify" ] }, "aliasify": { "aliases": { "app": "./src/app", "components": "./src/components", "someAlias": "./src/app/some/path/to/a/place", "foobar": "./go/to/a/module/named/foobar", } } 

然后,在你的文件,只是做:

 var foobar = require("foobar"); var sampleComponent = require("components/someSample"); //My JS code 

node_modules

您可以在node_modules下放置您的应用程序代码(或符号链接,如果您的平台支持的话)。 例如:

 node_modules/ +-- app/ +-- js/ +-- base/ +-- view.js +-- a/ +-- b/ +-- c/ +-- somefile.js 
 // somefile.js require("app/js/base/view"); 

但是 ,有一个重要的警告:这会中断通过API以编程方式指定的转换应用程序,例如:

 browserify('app/entry.js') .transform(es6ify) 

在browserify中,有一个“顶级”文件的概念可以在变换中发挥作用。 这个概念以及一般转换的行为在浏览文档中很less被解释。 你可以在这里看到一些关于这个问题的讨论: substack / node-browserify#993

pathmodify

另一个select是我的pathmodify browserify插件。 这允许使用非相对path和编程转换。 要启用浏览代码,如:

 var View = require('base/view'); 

你会做这样的事情:

 var pathmodify = require('pathmodify'); var opts = {mods: [ // Maps require() IDs beginning with "base/" to begin with // "/somedir/js/base/" pathmodify.mod.dir("base", "/somedir/js/base"), ]}; // Give browserify the real path to entry file(s). // pathmodify will transform paths in require() calls. browserify('./js/entry') .plugin(pathmodify, opts) .transform(es6ify) .bundle() ... 

综合

请注意,pathmodify只会解决browserify的问题。 如果你需要像base/view这样的path在另一个上下文中工作,比如节点,那么如果你有符号链接可用,你可以把它们结合起来。 例如,symlink node_modules/base/somedir/js/base ,并且还按照指示configurationpathmodify,并继续将browserify指向node_modules以外的path以获取条目文件。