简体   繁体   中英

Nodejs with JEST how to import using ES6 and relative path?

I want to avoid this:

const SomeMethod = require('../shared/SomeMethod')

And instead use something more modern like this:

import { SomeMethod } from '/shared'

(under the hood): the /shared directory includes an index file of course, returning the object with the SomeMethod property which is also includes to a file.

As I am using JEST, I need two things to get around: 1 is that the node installed supports ES6 imports and 2 is that JEST will be familiar with relative path - notice that I have used the **/**shared so it means - go to the src directory and start from there.

But how to achieve this?

You can achieve this using babel . According to the documentation of jest, you need to do the following

yarn add --dev babel-jest @babel/core @babel/preset-env

and then create babel.config.js at the root of your project with the following content

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current',
        },
      },
    ],
  ],
};

You can look into the documentation for more

Here is a step by step process of the same which is addressing the same problem

In order to use absolute path for Jest add the following line in jest.config.js

    module.exports = {
      moduleDirectories: ['node_modules', 'src'],
      ...
    };

here, src is considered as the root. You may need to change this one according to your folder name.

For more information you can follow this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM