导入具有绝对路径的React组件 [英] Import react components with absolute path

查看:122
本文介绍了导入具有绝对路径的React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试文件

// /imports/components/main.test.js
import React from 'react'
import { shallow, mount } from 'enzyme'
import Main from './main'
import TextInput from "/imports/ui/textInput"
...

main.js具有

// /imports/components/main.js
import { action1 } from "/imports/actions/myAction"

但是在运行测试时会抛出错误,说

but it throws an error when I run the test, saying

Cannot find module '/imports/actions/myAction' from 'main.js'

如果我评论import './main',则导入TextInput也会发生相同的情况.我在node_modules中导入模块没有问题.

If I comment the import './main', same thing happen with importing TextInput. I have no issue with importing modules in node_modules.

如何告诉Jest或webpack使用项目目录(即import Foo from /imports/...)中的绝对路径导入组件?

How can I tell Jest or webpack to import the component using absolute path from project directory (i.e import Foo from /imports/...)?

推荐答案

我的文件结构遵循与您的文件结构完全相同的模式.为了教Jest使用以/开头的导入,我使用 babel-plugin-module -resolver 及其方便的root选项.我的Jest .babelrc看起来像这样:

My file structure follows exactly the same pattern as yours. To teach Jest into using imports beginning with a /, I use babel-plugin-module-resolver and its handy root option. My .babelrc for Jest looks like this:

{
  "presets": ["es2015", "meteor"],
  "plugins": [
    "transform-class-properties",
    "transform-react-constant-elements",
    "transform-react-inline-elements",
    "transform-react-remove-prop-types",
      ["module-resolver", {
      "root": ["../"],
      "alias": {
        "react-router-dom": "react-router-dom/umd/react-router-dom.min.js",
        "redux": "redux/dist/redux.min.js",
        "react-redux": "react-redux/dist/react-redux.min.js"
      }
    }]
  ]
}

当我使用自定义根导入的Meteor时,我将Jest的用法和配置隐藏在存储库根目录的.jest目录中,使我可以使用特定的.babelrc而不会冒与Meteor的冲突的风险.

As I'm using Meteor which customized its root imports, I hide my Jest usage and configuration into a .jest directory at the root of my repository allowing me to have a specific .babelrc without risking conflicts with Meteor's one.

这篇关于导入具有绝对路径的React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆