Import react components with absolute path

2019-09-17 21:30发布

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/...)?

3条回答
闹够了就滚
2楼-- · 2019-09-17 21:53

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楼-- · 2019-09-17 22:09

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.

查看更多
来,给爷笑一个
4楼-- · 2019-09-17 22:10

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

查看更多
登录 后发表回答