Skip to content

Instantly share code, notes, and snippets.

@manekinekko
Last active July 2, 2024 12:37
Show Gist options
  • Save manekinekko/7e58a17bc62a9be47172 to your computer and use it in GitHub Desktop.
Save manekinekko/7e58a17bc62a9be47172 to your computer and use it in GitHub Desktop.
A regular Expression to parse ECMAScript6 import syntax
let regex = `import
(?:
["'\s]*
([\w*{}\n, ]+)
from\s*
)?
["'\s]*
([@\w/_-]+)
["'\s]*
;?
`;
// Matches...
/*
import {
Component
} from '@angular2/core';
import defaultMember from "module-name";
import * as name from "module-name ";
import { member } from " module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , member3 as alias3 } from "module-name";
import defaultMember, { member, member } from "module-name";
import defaultMember, * as name from "module-name";
import "module-name";
*/
@marcelometal
Copy link

Hi @manekinekko,
Thank you to share this regex!

I found a bug, the regex doesn't match the entire line. See here: https://regex101.com/r/giqmTO/2

Fixed: https://regex101.com/r/giqmTO/3

import(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s]*([@\w/_-]+)["'\s].*

@marcelometal
Copy link

Another bug: https://regex101.com/r/giqmTO/4

Fixed: https://regex101.com/r/giqmTO/5

import(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s].*([@\w/_-]+)["'\s].*

@jamonholmgren
Copy link

Awesome, thanks for sharing this.

@Itee
Copy link

Itee commented Jan 19, 2018

Doesn't handle multiline imports: https://regex101.com/r/giqmTO/7

Fixed: https://regex101.com/r/giqmTO/8

import(?:["'\s]*([\w*{}\n\r\t, ]+)from\s*)?["'\s].*([@\w/_-]+)["'\s].*

@omkadiri
Copy link

omkadiri commented May 8, 2018

@KeithHenry
Copy link

@Itee, @omkadiri both of those reduce the 2nd group to just the last char.

They also fail to find explicit relative references like import * from './module.js'

@Justez
Copy link

Justez commented Jan 19, 2019

removed / slash at the end of pattern so the fits well in JS code. All cases mentioned above works.

https://regex101.com/r/xA9kG3/175

@btopro
Copy link

btopro commented May 14, 2019

this is great! Is there any way this could be extended to handle dynamic imports as well as they are now stable in most ES6 browsers (everyone not firefox).

@btopro
Copy link

btopro commented May 14, 2019

import\((?:["'\s]*([\w*{}\n\r\t, ]+)\s*)?["'\s].*([@\w_-]+)["'\s].*\);$

can be used to target JUST import("whatever.js");

@btopro
Copy link

btopro commented May 14, 2019

Here's the two I landed on for import pattern matching (providing a group for the resource found)

  const patternImport = new RegExp(/import(?:["'\s]*([\w*${}\n\r\t, ]+)from\s*)?["'\s]["'\s](.*[@\w_-]+)["'\s].*;$/, 'mg')
  const patternDImport = new RegExp(/import\((?:["'\s]*([\w*{}\n\r\t, ]+)\s*)?["'\s](.*([@\w_-]+))["'\s].*\);$/, 'mg')

I used this to rewrite paths manually in a roll up to match a modular build routine

@kylemh
Copy link

kylemh commented Apr 15, 2020

I'm sure it has issues, but I used this to find a specific named module (useful for finding one component from a ESM import pattern of a component library):

import\s?\{[\s\w,]*Modal,?[\s\w,]*\}\s?from\s*["'\s].*([@\w_-]+)["'\s].*;$

@jnath
Copy link

jnath commented May 25, 2022

some fix if you want

https://regex101.com/r/oCa14q/1

import(?:[\s*]([\w*{}\n\r\t, ]+)[\s*]from)?[\s*](?:["'](.*[\w]+)["'])?

@JB-CHAUVIN
Copy link

Another bug: https://regex101.com/r/giqmTO/4

Fixed: https://regex101.com/r/giqmTO/5

import(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s].*([@\w/_-]+)["'\s].*

Thanks !

Here is a fix to have the module as the second matching group :

import(?:["'\s]*([\w*{}\n, ]+)from\s*)?["'\s](.*[@\w/_-]+)["'\s].*

@ganeshkbhat
Copy link

ganeshkbhat commented Oct 27, 2022

thank you for sharing this publically. is there a final version of the expression. I see all links have some or the other bug and has been worked on for many use cases but there is one of the other bug. i feel a duh here. i accumulated all the use cases now of the links.


/**

import {
  Component
} from '@angular2/core';
import defaultMember from "module-name";
import   *    as name from "module-name  ";
import   {  member }   from "  module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , member3 as alias3 } from "module-name";
import {
  Component
} from '@angular2/core';
import defaultMember from "$module-name";
import defaultMember, { member, member } from "module-name";
import defaultMember, * as name from "module-name";

import   *    as name from "module-name  "
import   {  member }   from "  module-name"
import { member as alias } from "module-name"
import { member1 , member2 } from "module-name"
import { member1 , member2 as alias2 , member3 as alias3 } from "module-name"
import {
  Component
} from '@angular2/core'
import defaultMember from "$module-name"
import defaultMember, { member, member } from "module-name"
import defaultMember, * as name from "module-name"

import "module-name";
import React from "react"
import { Field } from "redux-form"
import "module-name";

import {
	PlaneBufferGeometry,
	OctahedronGeometry,
	TorusBufferGeometry
} from '../geometries/Geometries.js';

import {
	PlaneBufferGeometry,
	OctahedronGeometry,
	TorusBufferGeometry
} from '../geometries/Geometries.js'

import("whatever.js");
import("whatever.js")

import { Field } from "redux-form";
import MultiContentListView from "./views/ListView";
import MultiContentAddView from "./views/AddView";
import MultiContentEditView from "./views/EditView";

import { Field } from "redux-form"
import MultiContentListView from "./views/ListView"
import MultiContentAddView from "./views/AddView"
import MultiContentEditView from "./views/EditView"


<MenuItem value="^$" primaryText="Não exibir importados" />
<MenuItem value="\\w+" primaryText="Exibir importados" />

// *Add all needed dependency to this module
// *app requires those import modules to function


*/

/**
* 
 *Add all needed dependency to this module
 *app requires those import modules to function
 * 
**/

let modules = [];




i wish to get the ---objects--- and ---modules--- from the following as a final match access:

import ---objects--- from "---modules---"
let variable = import("---modules---")


The regex /import(?:[\s.*]([\w*{}\n\r\t, ]+)[\s*]from)?[\s*](?:["'](.*[\w]+)["'])?/gm matches all https://regex101.com/r/QtftIb/1 other than:


// following not matched
import("whatever.js");
// following not matched
import("whatever.js")



//
// following import key matched
//

// *Add all needed dependency to this module
// *app requires those import modules to function



//
// following import key matched
//

/**
* 
 *Add all needed dependency to this module
 *app requires those import modules to function
 * 
**/

second, can i use this for my intented requirement?

@mrhyde
Copy link

mrhyde commented Feb 1, 2024

Hey everyone,

I wanted to share an optimized regex pattern that can be used to match import statements in JavaScript. This regex will successfully match various types of imports, including side effect imports (e.g., import "module-name";) and dynamic imports. It also handles different types of quotes, multiline import statements, and multiple whitespaces.

Here's the optimized regex pattern:

import\s+(?:{[^{}]+}|.*?)\s*(?:from)?\s*['"].*?['"]|import\(.*?\)

You can check out a live demo and test it using this Regex101 link.

@manekinekko
Copy link
Author

Hey everyone,

I wanted to share an optimized regex pattern that can be used to match import statements in JavaScript. This regex will successfully match various types of imports, including side effect imports (e.g., import "module-name";) and dynamic imports. It also handles different types of quotes, multiline import statements, and multiple whitespaces.

Here's the optimized regex pattern:

import\s+(?:{[^{}]+}|.*?)\s*(?:from)?\s*['"].*?['"]|import\(.*?\)

You can check out a live demo and test it using this Regex101 link.

I love it! Thanks for sharing!

@pavelmickevic
Copy link

pavelmickevic commented Jul 2, 2024

thanks @ganeshkbhat, I used it for the reference. Mine particular case to find occurences of specific import package.

import(?:[\s.*]([\w*{}\n\r\t, ]+)[\s*]from)\s+['"]lodash['"];
                                                  ^^^^^^

https://regex101.com/r/Nkplnn/1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment