Node.js 包管理器
Node.js 包管理器
除了独立使用,gx
打包工具可以配合 npm、pnpm 或者 yarn 等 JavaScript 包管理器使用。前提是安装 glyphix
包:
npm
npm install -D glyphix
pnpm
pnpm i -D glyphix
yarn
yarn add -D glyphix
否则在执行 gx build
时可能会遇到这样的报错:
$ gx build
fatal: glyphix not found, please install it by `npm install -D glyphix' or other package manager.
在 Glyphix 应用的开发中使用 JavaScript 包管理器主要有以下好处:
- 用 TypeScript,而不是 JavaScript 作为开发语言,提供类型安全和更好的开发体验
- 使用 Node.js 生态中适用于嵌入式开发的 JavaScript 库(如算法库、数据处理工具等)
- 使用 ESLint、Prettier 等工具来提升代码质量和开发效率
- 便于团队协作和项目维护
注意
目前仅支持通过包管理器来管理普通的 JavaScript 或 TypeScript 依赖,无法复用 Glyphix 组件。在选择第三方库时,请确保它们适用于嵌入式环境,避免使用依赖 DOM、Node.js 特定 API 或过于庞大的库。
提示
如果 Glyphix.js devtools 是全局安装的,那么可以直接用 gx build
这样的命令来打包,否则要在 package.json
中添加 scripts
配置。
项目配置
package.json
配置
当使用 Node.js 包管理器时,建议在 package.json
中添加必要的脚本和配置:
{
"name": "my-glyphix-app",
"version": "1.0.0",
"scripts": {
"build": "gx build",
"emu": "gx emu",
"clean": "gx clean"
},
"devDependencies": {
"glyphix": "^1.0.41",
"typescript": "^5.8.3"
}
}
tsconfig.json
配置
如果使用 TypeScript,需要在项目根目录创建 tsconfig.json
文件:
{
"compilerOptions": {
"target": "ES2021",
"module": "commonjs",
"baseUrl": "./",
"paths": {
"/*": ["src/*"],
"/assets": ["src/assets/*"]
},
"types": ["glyphix", "node"],
"allowImportingTsExtensions": true,
"checkJs": true,
"declaration": true,
"declarationMap": true,
"emitDeclarationOnly": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true,
"resolveJsonModule": true
},
"include": ["src/**/*.ts", "src/**/*.ux"]
}
相关信息
Glyphix 打包工具自动处理 TypeScript 文件的编译,上述配置主要用于 IDE 的类型检查和代码提示。
使用 TypeScript
Glyphix 框架提供实验性的 TypeScript 支持,让您能够在应用开发中享受类型安全和现代 JavaScript 语法的优势。
基本组件示例
下面是一个使用 TypeScript 编写的组件示例:
<template>
<p on:click="onClick">{{count}}</p>
</template>
<script lang="ts">
import { defineComponent } from "glyphix"
export default defineComponent({
data: {
count: 0
},
onClick() {
this.count++
}
})
</script>
相比于默认的 JavaScript 组件脚本,使用 TypeScript 需要做以下调整:
<script>
标签中使用lang="ts"
标注语言类型为 TypeScript。- 从
glyphix
模块导入defineComponent
函数。 - 待导出的组件对象要作为
defineComponent
的参数,并导出该函数的返回值。
使用 TypeScript 之后,将可以在 IDE 中看到更准确的类型提示和代码补全信息。