Import react components with absolute path

百般思念 提交于 2019-12-25 08:34:05

问题


Here is my test file

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

and the main.js has

// /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'

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

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


回答1:


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"
      }
    }]
  ]
}

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.




回答2:


Another solution is to create an .env file within the root directory of your project.

Within it you will add NODE_PATH=src/

Thats all

Save the file and restart your dev environment in terminal.

Afterwards, you will go through your project and update some import statements accordingly.




回答3:


Better way to solve relative path import issue, is by creating jsconfig.json file adjacent to package.json file.

{
  "compilerOptions": {
    "baseUrl": "imports"
  }
}

then import { action1 } from "actions/myAction"; will work



来源:https://stackoverflow.com/questions/41993461/import-react-components-with-absolute-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!