简体   繁体   English

使用 NodeJS 别名模块

[英]Aliasing modules using NodeJS

Some context here: It's not that I cannot use Webpack, it's that I do not want to use Webpack .这里有一些上下文:不是我不能使用 Webpack,而是我不想使用 Webpack I would like to keep everything as "vanilla" as possible.我想尽可能保持一切“原汁原味”。

Currently when creating modules in a project you have to require them using either a relative or absolute path, for example in the following directory..当前在项目中创建模块时,您必须使用相对或绝对路径来要求它们,例如在以下目录中..

project/
├── index.js
├── lib/
│   ├── network/
│   │      request.js
│   │      response.js
├── pages/
│   ├── foo.js

Considering we're in index.js we would import request via考虑到我们在 index.js 中,我们将通过

var networkRequest = require('./lib/network/request.js')

and if we're in foo.js we would import request via如果我们在 foo.js 中,我们将通过

var networkRequest = require('../lib/network/request.js')

What I'm wondering is that if there's any way to perhaps, set a local alias in Package.json or anywhere else like so:我想知道的是,如果有任何方法可以在Package.json或其他任何地方设置本地别名,如下所示:

localPackages = [
    { name: 'network-request', path: './lib/network/request.js' }
];

In which you could just do你可以做的

var networkRequest = require('network-request')

From any file and it will provide the correct path.从任何文件,它将提供正确的路径。

Yep, that's what npm link is for.是的,这就是npm link的用途。 Native and out of the box.本机和开箱即用。

You can also set local paths in package.json您还可以在 package.json 中设置本地路径

{
  "name": "baz",
  "dependencies": {
    "bar": "file:../foo/bar"
  }
}

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

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