Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何自动格式化代码 #160

Open
UvDream opened this issue Aug 15, 2022 · 7 comments
Open

如何自动格式化代码 #160

UvDream opened this issue Aug 15, 2022 · 7 comments

Comments

@UvDream
Copy link

UvDream commented Aug 15, 2022

求教,这个编辑器如何在初始化的时候格式化代码,而且我发现我这个右键格式化好像也不行是咋肥事,json格式的
image
我初始化格式代码是这样的

 editorDidMount={(editor) => {
          
                editor.getAction('editor.action.formatDocument').run();
              }}

发现没用

@jaywcjlove
Copy link
Member

/**
 * an event emitted when the editor has been mounted (similar to `componentDidMount` of React)
 */
editorDidMount?: (editor: monaco.editor.IStandaloneCodeEditor, monaco: IMonacoEditor) => void;

getAction 方法存在?

@UvDream

@UvDream
Copy link
Author

UvDream commented Aug 15, 2022

不存在,我看官方的那个这样格式化的,后来发现不存在,哈哈

@jaywcjlove
Copy link
Member

@UvDream 应该是用 monaco 这个回调参数的吧

@NIBUSHIYIGEREN
Copy link

同问
该怎么格式化代码呢

@jaywcjlove
Copy link
Member

@zhoujiaxu2014 microsoft/monaco-editor#2664 (comment)

<MonacoEditor
  language="json"
  value={`{"scope":"/build","moduleGenTarget":"commonjs"}`}
  editorDidMount={(editor, monaco) => {
    // 不起作用,这可能需要通过 ref 获取到 editor 对象执行 格式化
+    editor.getAction('editor.action.formatDocument').run();
  }}
  options={{
+    "formatOnPaste": true,
+    "formatOnType": true
  }}
/>  

@UvDream @zhoujiaxu2014

@dc-orz
Copy link

dc-orz commented May 29, 2023

const monaco = useMonaco();
  useEffect(() => {
    if (monaco) {
      monaco.editor.addCommand({
        id: 'editor.action.formatDocument',
        run: () => undefined,
      });
    }
  }, [monaco]);

It works with React 18.0

@xiaopujun
Copy link

const monaco = useMonaco();
  useEffect(() => {
    if (monaco) {
      monaco.editor.addCommand({
        id: 'editor.action.formatDocument',
        run: () => undefined,
      });
    }
  }, [monaco]);

It works with React 18.0

This is great. It solves my problem perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants