【问题标题】:How to get Babel to compile using webpack-style 'modulesDirectories'?如何让 Babel 使用 webpack 样式的“modulesDirectories”进行编译?
【发布时间】:2015-12-16 19:56:58
【问题描述】:

在此处遵循此要点 https://gist.github.com/ryanflorence/daafb1e3cb8ad740b346

我能够使用 Webpack 的“resolve.modulesDirectories”为一个非常复杂的应用程序设置一个很酷的文件夹结构 - 我可以通过模块类型导入来引用共享组件:

import MyModule from 'modules/MyModule';

文件在哪里

src/app/modules/Foo/modules/Bar/modules/Baz/component.jsx

MyModule 在

src/app/shared/modules/MyModule

问题是,当我尝试运行测试时

mocha --compilers js:babel-core/register $(find src/app -name *.test.jsx)

Babel 编译器抛出说它在 'modules/MyModule' 中找不到任何东西...

在 Babel 编译器配置中是否有类似 Webpack 的“modulesDirectories”?

【问题讨论】:

    标签: mocha.js webpack babeljs


    【解决方案1】:

    您应该能够使用 Babel 的 resolveModuleSource 选项来实质上重写导入路径,但您需要使用编程 API 来执行此操作。因此,不要使用 Mocha 的 --compilers 选项,而是使用 --require 加载调用 Babel 的 require 钩子并传递 resolveModuleSource 选项的脚本。如果您使用的是 Babel v6,请使用 babel-register 包,它看起来像:

    require("babel-register")({
      resolveModuleSource: function (source, filename) {
        return filename.replace(/^modules\/.+/, "/abs/path/to/src/app/shared/$0");
      },
    });
    

    【讨论】:

    • 当你在不同的地方有n个共享文件夹时,有什么办法可以做到这一点?
    • @Moezalez 我不太确定你在描述什么情况。你能在评论区总结一下吗?如果没有,也许可以更详细地提出它自己的问题。
    • 在此处查看shared 文件夹:gist.github.com/ryanflorence/daafb1e3cb8ad740b346
    • @Moezalez 谢谢。我想您可以自己在resolveModuleSource() 中实现对目录树的搜索,尽管它必须是同步的。一旦严重依赖 Webpack 功能,你最好将测试与 Webpack 捆绑在一起。参见例如gist.github.com/ryanflorence/…。或者,您可以使用 node_modules/ 而不是 shared/ 并依赖 Node 的模块解析。请注意,ES 模块的分辨率如何真正在 Node 中本地工作仍然悬而未决。
    • 或者只添加node-glob
    【解决方案2】:

    你必须使用 webpack 编译你的测试: https://webpack.github.io/docs/testing.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多