延迟加载MonacoEditor

时间:2018-04-25 08:21:11

标签: angularjs requirejs amd monaco-editor oclazyload

我有以下代码在我的AngularJS网站的index.html中加载MonacoEditor:

<link rel="stylesheet" data-name="vs/editor/editor.main" href="/monaco-editor/min/vs/editor/editor.main.css" />
<script src="/monaco-editor/min/vs/loader.js"></script>
<script src="/monaco-editor/min/vs/editor/editor.main.nls.js"></script>
<script src="/monaco-editor/min/vs/editor/editor.main.js"></script>
<script> 
    require.config({ paths: { 'vs': '/monaco-editor/min/vs' }}) 
    console.log(monaco)
</script>

运行网站会很好地显示monaco,这将在另一个JavaScript文件中使用。

现在,我想通过ocLazyLoad加载MonacoEditor:

    .state('addin', {
        abstract: true,
        template: '<ui-view/>',
        resolve: {
            loadAddinCtrl: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({files: [
                    "/monaco-editor/min/vs/editor/editor.main.css",
                    "/monaco-editor/min/vs/loader.js",
                    "/monaco-editor/min/vs/editor/editor.main.nls.js",
                    "/monaco-editor/min/vs/editor/editor.main.js"
                ]}).then(function () {
                    require.config({ paths: { 'vs': '/monaco-editor/min/vs' }})
                    console.log(monaco)
                })
            }]
        }
    })

上面的代码返回ReferenceError: monaco is not defined。有谁知道为什么会这样?

实际上,我不太了解require.config的目的,似乎使代码的灵活性降低了。有没有人可以替代呢?

1 个答案:

答案 0 :(得分:0)

您已加载依赖项,但尚未加载Monaco。在require.config

后尝试此操作
require.config({ paths: { 'vs': '/monaco-editor/min/vs' }})
require(['vs/editor/editor.main'], function onMonacoLoaded(){
  console.log(monaco);
});