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

时间:2015-06-26 08:43:24

标签: ecmascript-6 babeljs

我正在使用babel transpiler编写一个带有es6的节点应用程序。

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

- index.js
- my-module.js

MY-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!!!

但如果我在导入my-module时删除了点:

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

我收到错误:

Error: Cannot find module '/my-module'

为什么我无法使用绝对路径导入模块?无论如何改变.babelrc配置来支持它吗?

由于

3 个答案:

答案 0 :(得分:56)

像(几乎)任何工具'/ 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';

脚本/巴别-插件项目相对-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');

答案 1 :(得分:40)

来自FakeRainBrigand / Gavriguy的解决方案很好并且效果很好。 所以我决定开发一个插件,你可以用npm轻松安装并使用一个简单的Babel-Plugin。

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

希望这会有所帮助......

答案 2 :(得分:8)

First of all, Babel is just a transpiler from ES2015 to ES5 syntax. Its job is to transpile this:

import {myFunc} from '/my-module'

into this:

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

Actual module requiring performed by Node, and how Node does it you can read in details here: https://nodejs.org/api/modules.html#modules_file_modules

To summary, ./module means path to module relative to local directory, /module is an absolute path to module, module triggers Node to look for module in local node_modules directory and all ascending.

相关问题