Relative paths in package.json?

做~自己de王妃 提交于 2019-12-24 01:24:09

问题


I've got a project where src/main/webapp/com/mycompany/frontend/page/index.js depends on target/webjars/log4javascript/1.4.10/log4javascript.js.

I've added package.json alongside index.js with the following contents:

{
    "browser":
        {
            "log4javascript": "../../../../../../../target/webjars/log4javascript/1.4.10/log4javascript.js"
        }
}

I've got many other dependencies in the target directory. Is there a way for me to avoid repeating ../../../../../../../target/ for every dependency?


回答1:


One option is to put the directory that contains your local modules, or a symlink to it, in node_modules, such as node_modules/app and then reference your requires as app/..., e.g. I believe this would work

{
    "browser":
        {
            "log4javascript": "app/target/webjars/log4javascript/1.4.10/log4javascript.js"
        }
}

Or you could structure it however you want, e.g. node_modules/log4javascript (which, if you have symlinks, could point to /whatever/target/webjars/log4javascript).

This makes it so that require() will find it in the same fashion as npm modules, without publishing it to npm. The main drawback to this is that it breaks the ability to programatically configure transforms, e.g. with browserify('app/entry').transform(whatever), app/entry and other files in the dependency graph that are under node_modules will not have the transform applied to them.




回答2:


Check out the section Using Non-Relative Paths in this article.

You can use grunt-browserify's aliasMapping option to specify the root of your app:

aliasMappings: [{
  cwd: 'src',
  dest: 'myApp',
  src: ['**/*.js']
}]

and then you can directly refer to everything from the root path, without having to ever use any dreaded ../'s:

require("myApp/target/webjars/log4javascript/1.4.10/log4javascript.js")

Of course, this doesn't resolve the problem that it's still a very long path.

The article's next paragraph makes a very good point: if you're calling things way over at the other end of your application like that, it's a good sign that things may not be correctly architected.

Can you split the functionality into smaller modules? Perhaps make log4javascript its own module?


Add to my answer, from discussion below:

If log4javascript is in your package.json file as a browser (non-NPM) module, you should just be able to require it with require('log4javascript')



来源:https://stackoverflow.com/questions/28078780/relative-paths-in-package-json

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