BlackHoleGalaxy
BlackHoleGalaxy

Reputation: 9672

Including all file matching regex razor cshtml

I want to include Angular2 build files in a CSHTML file.

Currently, my include is:

@section scripts {
    <script src="~/dist/main.js" asp-append-version="true"></script>
}

But Angular2 produce, on each prod build, files with different identifiers in the file name.

chunk    {0} main.2e0750e4cb976b8dca8a.bundle.js (main) 15.8 kB {3} [initial] [rendered]
chunk    {1} styles.b64dd2f7c2e3011c4efb.bundle.css (styles) 154 kB {4} [initial] [rendered]
chunk    {2} scripts.e7e62c29938f18f13e86.bundle.js (scripts) 128 kB {4} [initial] [rendered]
chunk    {3} vendor.05b8df0708b580c61647.bundle.js (vendor) 3.42 MB [initial] [rendered]
chunk    {4} inline.1b4aa06545162c1bb581.bundle.js (inline) 0 bytes [entry] [rendered]

I don't want to deactivate (if it's even possible) the fact these identifiers are included (for non-cache purpose). A person answered on a github issue page some regex could be used to make the include:

/(main|styles|scripts|vendor|inline).*.bundle.(map|js|css)/g

But I don't see how to pass it to my C#/cshtml file.

It should result on including all files matching the pattern in a given directory (wwwroot, or ~ as a shortcut).

Any idea on how to achieve this?

Upvotes: 1

Views: 1267

Answers (1)

Tseng
Tseng

Reputation: 64259

You can use the asp-src-include tag helper for scripts and asp-href-include for links (css).

<script asp-src-include="~/dist/main.*.bundle.js" asp-append-version="true"></script>
<link asp-href-include="~/dist/styles.*.bundle.css"/>

However iirc you can't use regex inside it, only globbed path (i.e. dist/**/*.js where ** will look through all child folders too.

If that do not suit your needs, you need to write your own tag helper.

See GitHub for current implementations of LinkTagHelper and ScriptTagHelper.

I wouldn't recommend you to use regex for the main-part anyways, because you have no control on in which order the files are included. So it's best to control this manually and only make the identifier/hashsum variable.

Upvotes: 5

Related Questions