diff --git a/src/Symfony/Component/AssetMapper/Compiler/JavaScriptImportPathCompiler.php b/src/Symfony/Component/AssetMapper/Compiler/JavaScriptImportPathCompiler.php index be81a58027ed..16a325a016cb 100644 --- a/src/Symfony/Component/AssetMapper/Compiler/JavaScriptImportPathCompiler.php +++ b/src/Symfony/Component/AssetMapper/Compiler/JavaScriptImportPathCompiler.php @@ -27,8 +27,31 @@ */ final class JavaScriptImportPathCompiler implements AssetCompilerInterface { - // https://regex101.com/r/qFoeoR/1 - private const IMPORT_PATTERN = '/(?:\'(?:[^\'\\\\]|\\\\.)*\'|"(?:[^"\\\\]|\\\\.)*")|(?:import\s*(?:(?:\*\s*as\s+\w+|[\w\s{},*]+)\s*from\s*)?|\bimport\()\s*[\'"`](\.\/[^\'"`]+|(\.\.\/)*[^\'"`]+)[\'"`]\s*[;\)]?/m'; + /** + * @see https://regex101.com/r/1iBAIb/1 + */ + private const IMPORT_PATTERN = '/ + ^ + (?:\/\/.*) # Lines that start with comments + | + (?: + \'(?:[^\'\\\\]|\\\\.)*\' # Strings enclosed in single quotes + | + "(?:[^"\\\\]|\\\\.)*" # Strings enclosed in double quotes + ) + | + (?: # Import statements (script captured) + import\s* + (?: + (?:\*\s*as\s+\w+|\s+[\w\s{},*]+) + \s*from\s* + )? + | + \bimport\( + ) + \s*[\'"`](\.\/[^\'"`]+|(\.\.\/)*[^\'"`]+)[\'"`]\s*[;\)] + ? + /mx'; public function __construct( private readonly ImportMapConfigReader $importMapConfigReader, @@ -42,7 +65,7 @@ public function compile(string $content, MappedAsset $asset, AssetMapperInterfac return preg_replace_callback(self::IMPORT_PATTERN, function ($matches) use ($asset, $assetMapper, $content) { $fullImportString = $matches[0][0]; - // Ignore enquoted strings (e.g. console.log("import 'foo';") + // Ignore matches that did not capture import statements if (!isset($matches[1][0])) { return $fullImportString; } diff --git a/src/Symfony/Component/AssetMapper/Tests/Compiler/JavaScriptImportPathCompilerTest.php b/src/Symfony/Component/AssetMapper/Tests/Compiler/JavaScriptImportPathCompilerTest.php index e616211b5b9d..aa57145b3ce1 100644 --- a/src/Symfony/Component/AssetMapper/Tests/Compiler/JavaScriptImportPathCompilerTest.php +++ b/src/Symfony/Component/AssetMapper/Tests/Compiler/JavaScriptImportPathCompilerTest.php @@ -177,6 +177,16 @@ public static function provideCompileTests(): iterable 'expectedJavaScriptImports' => ['/assets/other.js' => ['lazy' => false, 'asset' => 'other.js', 'add' => true]], ]; + yield 'commented_import_on_one_line_then_module_name_on_next_is_not_ok' => [ + 'input' => "// import \n './other.js';", + 'expectedJavaScriptImports' => [], + ]; + + yield 'commented_import_on_one_line_then_import_on_next_is_ok' => [ + 'input' => "// import\nimport { Foo } from './other.js';", + 'expectedJavaScriptImports' => ['/assets/other.js' => ['lazy' => false, 'asset' => 'other.js', 'add' => true]], + ]; + yield 'importing_a_css_file_is_included' => [ 'input' => "import './styles.css';", 'expectedJavaScriptImports' => ['/assets/styles.css' => ['lazy' => false, 'asset' => 'styles.css', 'add' => true]],