1、使用 monaco-editor
安装依赖
cnpm install monaco-editor --save
cnpm install monaco-editor-webpack-plugin --save-dev
vue.config.js
const { defineConfig } = require('@vue/cli-service')
const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin')
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack: config => {
config.resolve.symlinks(false)
},
configureWebpack: {
plugins: [
new MonacoWebpackPlugin({
languages: ['typescript', 'javascript']
})
]
}
})
App.vue
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'
console.log('monaco.languages.typescript:', monaco.languages.typescript)
export default {
name: 'App',
mounted() {
monaco.editor.create(this.$refs.editor, {
value: 'const PI = 3.14',
language: 'javascript'
})
}
}
一运行,编辑器是渲染出来了,但没有高亮,没有语法提示。monaco.languages.typescript 打印出来也是 undefined,说明有资源没加载。
2、问题出在 symlinks
经过一圈排查,发现和 vue.config.js 里的 config.resolve.symlinks(false) 有关。简单了解下 symlinks,官方文档这么写的。
Whether to resolve symlinks to their symlinked location.
是否将符号链接(symlink)解析到它们的符号链接位置(symlink location)。
When enabled, symlinked resources are resolved to their real path, not their symlinked location. Note that this may cause module resolution to fail when using tools that symlink packages (like npm link).
启用时,符号链接(symlink)的资源,将解析为其 真实 路径,而不是其符号链接(symlink)的位置。注意,当使用创建符号链接包的工具(如
npm link)时,这种方式可能会导致模块解析失败。
检查一下 node_modules 里的 monaco-editor 依赖,果然,是符号链接。
去掉 config.resolve.symlinks(false) 这个配置就可以了,但项目需要使用 npm link,是需要这个配置的。
3、如何安装依赖
开头我是用 cnpm 安装的,会自动生成符号链接,pnpm 也是类似的。
改用 yarn 安装,就不是符号链接了。
yarn add monaco-editor # monaco-editor-webpack-plugin 会自动一起安装
总结:
需要禁用 symlinks 的时候,安装 monaco-editor 就不要生成符号链接。