I'm constructing a simple ASP.NET Core application that uses npm and TypeScript. The structure of my project looks as follows:
/ root
| wwwroot
| js
| AutoGenerated // <-- TS output goes here
| view
| index.html // <-- imports app.js from "AutoGenerated"
| scripts
| app.ts
| node_modules
| ..
| ..
| package.json
| tsconfig.json
| Startup.cs
| Program.cs
tsconfig
is set to "moduleResolution":"Node"
. All the other configuration is pretty standard so for now I won't include it here so as not to clutter the big picture.
In my app.ts
I want to refer to one of the packages downloaded via node, so I added the following line:
import { SomeClass } from "@module/downloadedModule";
The import above gets resolved to "/node_modules/@module/downloadedModule"
, which is exactly what I need. The whole project compiles and produces an app.js
file under /wwwroot/js/AutoGenerated/
as expected.
The problem is that the resulting JS file still contains the reference to node_modules:
import { SomeClass } from "@module/downloadedModule";
which doesn't make sense, as only the files under wwwroot
are served by my application.
I found a similar question on SO: Cannot import libraries from Node_Modules to ASP.NET CORE APP and the author suggests extending the static files handler in order to include "node_modules", but I don't want to do this in my application.
Potential solutions that come to my mind (though I'm not sure if they are applicable):
1.) Mapping required files from node_modules to e.g. /wwwroot/dependencies
and modifying the import path in JS file during TS compilation.
2.) Bundling my TS files and required node_modules dependencies into a single, self-contained JS file.
3.) Anything else that allows me to use app.js from my html and doesn't require tons of packages.
question from:
https://stackoverflow.com/questions/66052156/refering-to-node-modules-from-typescript-in-an-asp-net-core-app 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…