我试图在使用npm依赖项的Razor类库中创建Blazor组件。在我的wwwroot
中创建了一个package.json
:
{
"name": "mycomponent",
"version": "0.0.1",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "UNLICENSED",
"dependencies": {
"d3": "^5.14.2"
}
}
在我的csproj
中,我有:
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="npm install" WorkingDirectory="$(ProjectDir)wwwroot" />
</Target>
然后我将项目设置为创建.nupkg。
现在运行dotnet publish MyComponent -c Release
时,我得到了MyComponent.1.0.0.nupkg
,但其中的staticwebassets
文件夹中只有wwwroot
的顶级内容。
那么,如何从那里的node_modules
文件夹中获取依赖关系?我是否必须运行某种打包程序才能在根文件夹中生成缩小的程序包,或者我是否缺少其他内容?
答案 0 :(得分:2)
抱歉,Blazor不支持此功能。最好的方法是为使用该库的任何人记录对外部依赖项的要求。
我要指出的是,并不是每个人都使用NPM(我避免像瘟疫一样避开它),并且对客户端软件包使用不同的方法,因此,如果这是“公共”软件包,则可能是规定性太强的要求NPM的方法。如果仅在内部使用是可以的,但是如何处理捆绑和包装由您自己决定。
有an issue跟踪静态资源的处理方式
答案 1 :(得分:2)
我找到了一个将webpack添加到游戏中的解决方案。这是我的操作方式:
package.json
,请在npm init
内运行wwwroot
来生成一个wwwroot
中除package.json
和package-lock.json
之外的所有内容移动到wwwroot/src
安装Webpack和一些加载程序:
npm install --save-dev webpack css-loader file-loader style-loader
添加适当的webpack.config.js
:
var path = require('path');
module.exports = {
mode: 'production',
entry: [ './src/main.js', './src/style.css' ],
module: {
rules: [
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ] },
{ test: /\.(jpe?g|png|gif|svg)$/i, use: 'file-loader' }
]
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.bundle.js',
publicPath: '_content/MyRazorClassLibrary/dist/' // << See note
}
};
注意:publicPath
用于在Blazor中运行时重写路径。 Webpack以所有资产都相对于主JS文件相关的方式打包结果。但是Blazor希望数据位于路径_content/ProjectName
中,这是使用publicPath
来解决的。
csproj
文件中: <Target Name="PreBuild" BeforeTargets="PreBuildEvent">
<Exec Command="npm install" WorkingDirectory="$(ProjectDir)wwwroot" />
<Exec Command="webpack" WorkingDirectory="$(ProjectDir)wwwroot" />
</Target>
<ItemGroup>
<Content Remove="wwwroot\package-lock.json" />
<Content Remove="wwwroot\package.json" />
<Content Remove="wwwroot\src\**" />
<Content Remove="wwwroot\webpack.config.js" />
</ItemGroup>
<ItemGroup>
<None Include="wwwroot\package-lock.json" />
<None Include="wwwroot\package.json" />
<None Include="wwwroot\src\**" />
<None Include="wwwroot\webpack.config.js" />
</ItemGroup>
这将导致src
目录以及npm和webpack特定文件不包含在最终的NuGet软件包中。另外,它将运行npm install
和webpack
。
为此,您必须安装webpack-cli
:
npm install -g webpack webpack-cli
现在,当您运行dotnet build -c Release MyRazorClassLibrary
并将库设置为在构建时生成NuGet软件包时,您将得到一个不错的nupkg
,其中包含了所有内容。