Blazor中使用npm、ts、scss、webpack且自动导入到html
1、新建一个BlazorApp项目
2、新建文件夹WebLib,并在终端中打开
执行指令
npm init -y
在WebLib目录下新建tsconfg.json文件
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "ES6",
"outDir": "../wwwroot/js",
"allowSyntheticDefaultImports": true
},
"exclude": [
"node_modules",
"wwwroot",
"Component",
"Pages",
"Layout"
],
"include": [
"**/*"
]
}
执行以下指令
// 安装pnpm,npm国内太慢,所以使用pnpm管理包
npm install -g pnpm
// 安装webpack相关依赖
pnpm install webpack webpack-cli --save-dev
// 安装ts相关依赖
pnpm install --save-dev typescript ts-loader
// 安装css相关依赖
pnpm i -D sass-loader css-loader style-loader sass
// 安装scss相关依赖(不用scss可以不装)
pnpm i -D sass-loader sass
在WebLib目录下新建webpack.config.js文件
const path = require("path");
let commonSetting = {
module: {
rules: [
{
test: /.ts$/,
use: {
loader: "ts-loader",
},
exclude: /node_modules/,
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']//程序会先加载css-loader,然后在加载style-loader文件
},
{
// 增加对 SCSS 文件的支持
test: /\.scss$/,
// SCSS 文件的处理顺序为先 sass-loader 再 css-loader 再 style-loader
use: ['style-loader', 'css-loader', 'sass-loader'],
}
]
},
devtool: "inline-source-map",
// 用来设置引用模块
resolve: {
extensions: [".ts", ".js"],
},
}
module.exports = [
{
entry: {
common: './src/common.ts',
},
output: {
path: path.resolve(__dirname, '../wwwroot/js'),
filename: "[name].js",
library: {
// umd打包出来的js,可以在html引入后直接使用里面的函数
type: 'umd'
},
},
...commonSetting
},
{
entry: {
// BlazorApp1是项目的名称,必须是这个名字
"BlazorApp1.lib.module": "./src/BlazorApp1.lib.module.ts"
},
experiments: {
outputModule: true
},
output: {
path: path.resolve(__dirname, '../wwwroot/js'),
filename: "[name].js",
library: {
// module打包出来,需要import导入后使用
type: 'module'
},
},
...commonSetting
}
];
在WebLib目录下创建src目录,并在src目录下创建common.ts,BlazorApp1.lib.module.ts文件,然后创建css目录,并在css目录下创建common.scss文件,目前目录结构如下
修改common.ts如下
import "./css/common.scss"
export function Sum(a: number, b: number) {
console.log(a+b)
}
修改BlazorApp1.lib.module.ts如下
const moduleJsList: string[] =
[
`./js/common.js`
]
function loadJs() {
for (let i of moduleJsList) {
let el = document.createElement('script');
el.setAttribute('src', i);
document.head.appendChild(el);
}
}
export function beforeWebStart() {
console.log("开始加载js")
loadJs();
}
// 这样做的目的是让common.ts里的方法能够在html里直接调用,而不需要import
修改common.scss如下
.testDiv{
font-size:30px;
font-weight:bolder;
}
修改Components/Pages/Counter.razor如下
@page "/counter"
@inject IJSRuntime jsRuntime;
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<div class="testDiv">
1231
</div>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
await jsRuntime.InvokeVoidAsync("Sum", 1, 2);
}
}
package.json如下
{
"name": "weblib",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --mode production",
"dev": "webpack --mode development"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.10.0",
"sass": "^1.70.0",
"sass-loader": "^14.1.0",
"style-loader": "^3.3.4",
"ts-loader": "^9.5.1",
"typescript": "^5.3.3",
"webpack": "^5.90.1",
"webpack-cli": "^5.1.4"
}
}
最后在终端执行
npm run dev
运行项目,在Counter页面下会呈现如下效果
且点击按钮,控制台会打印3
3、调整项目文件,让其在发布和编译时自动打包
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<JsLibRoot>WebLib\</JsLibRoot>
<DefaultItemExcludes>$(DefaultItmeExcludes);$(JsLibRoot)node_modules\**</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<None Remove="WebLib\src\BlazorApp1.lib.module.ts" />
<None Remove="WebLib\src\common.ts" />
</ItemGroup>
<ItemGroup>
<TypeScriptCompile Include="WebLib\src\BlazorApp1.lib.module.ts" />
<TypeScriptCompile Include="WebLib\src\common.ts" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\js\" />
</ItemGroup>
<ItemGroup>
<Content Update="WebLib\package.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
<Content Update="WebLib\tsconfig.json">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
</Content>
</ItemGroup>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' Or '$(Configuration)' == 'Release' ">
<!-- Ensure Node.js is installed -->
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<Message Importance="high" Text="正在使用pnpm编译脚本js,如果没有pnpm请使用`npm install -g pnpm`命令安装" />
<Exec WorkingDirectory="$(JsLibRoot)" Command="pnpm install" Condition=" !Exists('$(JsLibRoot)node_modules') Or '$(Configuration)' == 'Release' " />
<Exec WorkingDirectory="$(JsLibRoot)" Command="pnpm run build" Condition=" '$(Configuration)' == 'Release' " />
<Exec WorkingDirectory="$(JsLibRoot)" Command="pnpm run dev" Condition=" '$(Configuration)' != 'Release' " />
</Target>
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(JsLibRoot)" Command="pnpm install" />
<Exec WorkingDirectory="$(JsLibRoot)" Command="pnpm run build" />
</Target>
</Project>
项目已上传到Github:https://github.com/PengYuee/BlazorNpmSmple