Home > Back-end >  Javascript regex to select import statements in react project
Javascript regex to select import statements in react project

Time:06-30

I want to search for the import statements of npm packages, but not the local imports,

for eg: I want to search for these types of strings:

import axios from 'axios';
import ApolloLinkTimeout from 'apollo-link-timeout';
import { RestLink } from 'apollo-link-rest';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { one rror } from 'apollo-link-error';

but NOT these:

import { getAllAccounts } from '../../store/actions/actions';
import { CREATE_ACCOUNT_QUERY } from '../queries/AccountsQuery';
import UserContext from '../UserContext';

is this possible using Regex or any other way in javascript I have tried import {[^}]*}.*'foo-bar' but this is not working as expected.

Edit: as per the comments,

^import\s (?:\{\s*\w \s*\}|\w )\s from\s ['"]([^\/] ?)['"];?$

is working better, but not for the following cases:

import React, { useEffect, useState } from 'react';
import { Col, Modal, ModalHeader, Row } from 'reactstrap';
import { useLazyQuery } from '@apollo/react-hooks';

CodePudding user response:

^import\s.*?\sfrom\s ['"](@[\w\/\-] |[^.] ?)(?:\/.*?)?['"];?$

Explanation

  • ^ Start of a string
  • import\s.*?\s Match string that starts with import keyword then module default or exports after a space character till to from
  • from\s Match from keyword and one or more spaces
  • ['"] Match ' (single quote) or " (double quote) characters
  • ( Capturing group
    • @[\w\/\-] Package name should start with @ and can contain word characters (letters, numbers, underscore), / and - characters
    • | Or
    • [^.] ? Package name should contain any character except . (dot)
  • ) Close group
  • (?:\/.*?)? Match package subpaths without capturing (this can exist or not)
  • ['"];? Match close quote and optional ; at the end
  • $ End of a string

See the regex demo and please attention to the last line, it captures only the package name.

  • Related