使用 es6 和 babel-node 从根目录导入节点模块

Importing node modules from root directory using es6 and babel-node

我正在使用 babel 转译器用 es6 编写一个节点应用程序。

我的根目录中有 2 个文件 index.js & my-module.js

- index.js
- my-module.js

我的-module.js

export let myFunc = () => {
  console.log('myFunc was called!!!');
}

index.js

import {myFunc} from './my-module';
myFunc();

如果我 运行 命令行中的以下行一切正常。

$ babel-node index.js >> myFunc was called!!!

但是如果我在导入我的模块时删除了点:

import {myFunc} from '/my-module';
myFunc();

我遇到一个错误:

Error: Cannot find module '/my-module'

为什么我不能使用绝对路径导入模块?无论如何更改 .babelrc 配置以支持它?

谢谢

就像(几乎)任何工具一样,'/x' 在文件系统的根目录中表示 'x'。 Babel 实际上并不查看路径,它只是编译

import {myFunc} from '/my-module';

进入

var _myModule = require('/my-module');

节点实际查找模块。


如果你真的想相对于项目的根导入,你可以使用插件。我建议使用不是很模糊的东西,并确保为下一个阅读你的代码的人记录下来!

这是一个示例,其中我们使用前导 ~ 来表示项目相关。你可以使用任何你喜欢的东西,例如^也不错

示例输入:

import {a} from '~my-module';
import {b} from '/my-module';
import {c} from './my-module';

scripts/babel-plugin-project-relative-require.js

module.exports = function (babel) {
  // get the working directory
  var cwd = process.cwd();

  return new babel.Transformer("babel-plugin-project-relative-require", {
    ImportDeclaration: function(node, parent) {
      // probably always true, but let's be safe
      if (!babel.types.isLiteral(node.source)) {
        return node;
      }

      var ref = node.source.value;

      // ensure a value, make sure it's not home relative e.g. ~/foo
      if (!ref || ref[0] !== '~' || ref[1] === '/') {
        return node;
      }

      node.source.value = cwd + '/' + node.source.value.slice(1);

      return node;
    }
  });
};

.babelrc

{
    "plugins": [
        "./scripts/babel-plugin-project-relative-require.js"
    ]
}

输出(如果 运行 在 /tmp 中):

'use strict';

var _tmpMyModule = require('/tmp/my-module');

var _myModule = require('/my-module');

var _myModule2 = require('./my-module');

首先,Babel 只是一个 ES2015 到 ES5 语法的转译器。它的工作是转译这个:

import {myFunc} from '/my-module'

进入这个:

var _myModule = require('/my-module');

需要由 Node 执行的实际模块,以及 Node 是如何执行的,您可以在此处详细阅读:https://nodejs.org/api/modules.html#modules_file_modules

总结一下,./module表示模块相对于本地目录的路径,/module是模块的绝对路径,module触发Node在本地寻找模块node_modules 目录和所有升序。

FakeRainBrigand/Gavriguy 的解决方案很好并且运行良好。 所以我决定开发一个插件,您可以使用 npm 轻松安装它并使用简单的 Babel-Plugin。

https://github.com/michaelzoidl/babel-root-import

希望这对您有所帮助...