Get browserify require paths to behave more like requirejs

我们两清 提交于 2019-11-30 06:26:21
eightyfive

You should use the paths option. It is not documented in browserify but in node-browser-resolve (used under the hood):

paths - require.paths array to use if nothing is found on the normal node_modules recursive walk

A great option here is to use the aliasify plugin, available here. Then just add something like this to your package.json, with all paths in the aliasify config being relative to the position of that file:

  "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",
    }
  }

Then, in your files, just do:

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

//My JS code

node_modules

You can put your application code (or a symlink to it, if your platform supports it) under node_modules. E.g.:

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

However, there's an important caveat: this breaks application of transforms specified programmatically via the API, e.g:

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

In browserify there's a concept of "top-level" files that comes into play with transforms. That concept, and the behavior of transforms in general, is poorly explained in the browserify documentation. You can see some discussion of the issue here: substack/node-browserify#993

pathmodify

Another option is my pathmodify browserify plugin. This allows using non-relative paths and programmatic transforms. To enable browserifying code like:

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

You would do something like:

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()
  ...

Combined

Note that pathmodify will only solve the problem for browserify. If you need the paths like base/view to also work in another context, like node, then if you have symlinks available you can combine the two. For example, symlink node_modules/base to /somedir/js/base, and also configure pathmodify as indicated and continue to point browserify to paths outside of node_modules for entry files.

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