首页 > 其他分享 >Blazor中使用npm、ts、scss、webpack且自动导入到html

Blazor中使用npm、ts、scss、webpack且自动导入到html

时间:2024-02-02 17:56:59浏览次数:29  
标签:导入到 npm ts js webpack scss loader css common

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

标签:导入到,npm,ts,js,webpack,scss,loader,css,common
From: https://www.cnblogs.com/qwfy-y/p/18003596

相关文章

  • nvm安装Nodejs时报错,Could not retrieve https://npm.taobao.org/mirrors/node/latest
    1.首先要使用管理员运行命令2.在安装nvm的目录下找到settings.txt,没有就手动增加一个node_mirror:https://npm.taobao.org/mirrors/node/npm_mirror:https://npm.taobao.org/mirrors/npm/这个地方有点奇怪,安装18的时候把上面的Https://去掉以后就下载成功了3.安装19以及......
  • npm证书过期:npm ERR! request to https://registry.npm.taobao.org/element-ui failed
    场景:使用淘宝源安装element-ui时npm证书过期报错信息如下:npmERR!codeCERT_HAS_EXPIREDnpmERR!errnoCERT_HAS_EXPIREDnpmERR!requesttohttps://registry.npm.taobao.org/element-uifailed,reason:certificatehasexpirednpmERR!Acompletelogofthisrun......
  • npm disturl 是做什么用的?
    npmdisturl是做什么用的?npmdisturl是一个配置项,用于设置npm下载tarball包(通常是Node.js的二进制文件或者一些带有平台相关编译内容的npm模块)时的基础URL。当npm需要从源代码构建依赖项,并且这些依赖项包含需要从特定位置下载的预编译二进制文件时,它会使用这个disturl来定位和......
  • npm包(npm install --legacy-bundling) 通过npm-pack-all 打包tgz,放到内网(不联网)nexus
    npm包(npminstall--legacy-bundling)通过npm-pack-all打包tgz,放到内网(不联网)nexus发布(npmpublish)需求内网不联网,安装指定npm包,装不上,还要支持CI的测试打包,所以要将外网的npm包放到内网的nexus私服上举例安装quill@1.3.7外网机器桌面建立目录needPackage(目录名随便,但......
  • npm编译vue出错:Error code CERT_HAS_EXPIRED
    [Error]Theerrormessageisabouttheregistryhttps://npm.sap.com/youused.npmERR!codeCERT_HAS_EXPIREDnpmERR!errnoCERT_HAS_EXPIREDnpmERR!requesttohttps://npm.sap.com/@sap%2fcdsfailed,reason:certificatehasexpired[Solution]runcommand......
  • dockerfile安装jenkins 并配置构建工具(node、npm、maven、git)
    dockerfile安装jenkins并配置构建工具(node、npm、maven、git):https://blog.csdn.net/weixin_39660224/article/details/88775707?ops_request_misc=&request_id=&biz_id=102&utm_term=dockerfile%20%E5%88%9B%E5%BB%BAjenkins&utm_medium=distribute.pc_search_result.......
  • 【NodeJS】- 使用NVM安装npm失败后,手动安装npm
    安装NVM之后,我们通常会配置镜像,在setting文件中,添加镜像路径node_mirror:https://npm.taobao.org/mirrors/nodenpm_mirror:https://npm.taobao.org/mirrors/npm但是这两天镜像突然炸了,于是我删掉了镜像地址,使用官方直接下载。但是npm下载非常困难,而且高版本的npm还存在wo......
  • scss 走马灯效果(兼容微信小程序)
    <template><viewclass="marquee"><viewclass="marquee-inner"><spanv-for="(item,index)oftextList":key="index">{{item.text}}</span><!--复制一份内容-->......
  • 我的npmrc配置
    前言经常需要新开项目,有些时候,安装依赖时很慢,所以都得配置一下镜像源,但是每次新开项目都配置以便,很麻烦,也记不全,这里特别开一个新帖,记录一下自己的一些依赖包用的镜像正文完整配置,持续更新中:registry=https://registry.npmmirror.comsass_binary_site=https://npmmirror.com/......
  • 解决“yarn : 无法加载文件 C:\Users\quber\AppData\Roaming\npm\yarn.ps1,因为
    1、......