问题
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