@alauda/code-editor
v5.2.1
Published
## 安装依赖
Downloads
249
Maintainers
Keywords
Readme
如何在项目中使用代码编辑器?
安装依赖
安装 monaco-editor 依赖: yarn add monaco-editor ng-monaco-editor
额外依赖
假如你想使用 monaco-yaml 以增加对于 yaml 的格式检查,你还需要安装:
yarn add monaco-languages monaco-yaml
配置运行时需要载入的 monaco-editor 库文件
将 monaco-editor 的 monaco-editor/min 目录拷贝到项目 assets 下面。
Angular CLI 项目:
对于 Angular CLI 配置的项目,你可以增加一条配置
{
"projects": {
"app": {
// 省略无关选项
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"assets": [
{
"glob": "**/*",
"input": "node_modules/monaco-editor/min/vs",
"output": "/lib/vs"
},
// 假如你需要支持 YAML 格式检查,你还需要以下依赖:
{
"glob": "**/*",
"input": "node_modules/monaco-languages/release/min",
"output": "/lib/vs/basic-languages"
},
{
"glob": "**/*",
"input": "node_modules/monaco-yaml/min",
"output": "/lib/vs/language/yaml"
}
// ...
配置 AppModule, 载入 CodeEditorModule
模块:
在 Angular 的根模块配置并载入 CodeEditorModule
。以下为参考配置:
const DEFAULT_MONACO_OPTIONS: monaco.editor.IEditorConstructionOptions = {
fontSize: 12,
folding: true,
scrollBeyondLastLine: false,
minimap: { enabled: false },
mouseWheelZoom: true,
scrollbar: {
vertical: 'visible',
horizontal: 'visible',
},
fixedOverflowWidgets: true,
};
@NgModule({
imports: [
CodeEditorModule.forRoot({
baseUrl: 'lib',
defaultOptions: DEFAULT_MONACO_OPTIONS,
}),
],
providers: [
// 可选配置,稍后会解释
{
provide: MonacoProviderService,
useClass: CustomMonacoProviderService,
},
],
})
export class AppModule {}
如上配置中还提供了用户自己的 MonacoProviderService
。以下为实现了几个默认不支持的代码编辑器功能:
- 记住用户选择的主题色
- 加载 monaco-yaml,增加对于 yaml 文件的语法检查
import { Injectable } from '@angular/core';
import { MonacoProviderService } from 'alauda-ui';
const CODE_EDITOR_THEME_KEY = 'code-editor-theme';
/**
* Custom monaco provider to do some customizations.
*/
@Injectable()
export class CustomMonacoProviderService extends MonacoProviderService {
async initMonaco() {
await super.initMonaco();
// Load custom yaml language service:
await this.loadModule([
// YAML language services are currently managed manually in thirdparty_lib
'vs/basic-languages/monaco.contribution',
'vs/language/yaml/monaco.contribution',
]);
this.configYaml();
this.changeTheme(localStorage.getItem(CODE_EDITOR_THEME_KEY));
}
changeTheme(theme: string) {
super.changeTheme(theme);
localStorage.setItem(CODE_EDITOR_THEME_KEY, theme);
}
private configYaml() {
monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
validate: true,
schemas: [
{
uri: undefined,
fileMatch: ['*'],
schema: {
description: 'YAML',
type: 'object',
},
},
],
});
}
}