无法配置EditorJS:CDN引入下模块导入语句报错求助
问题:EditorJS CDN引入时import语句报错
我在网页中尝试使用EditorJS,HTML代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Button Example</title> <!-- Include Editor.js styles --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest/dist/editor.min.css" /> </head> <body> <div id="starter">Application begins here!</div> <div id="editorjs"></div> <button id="save">Save Article</button> <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script> <script type="module" src="sampler.js"></script> </body> </html>
sampler.js文件代码:
import {EditorJS} from '@editorjs/editorjs'; import {Header} from '@editorjs/header'; const editor = new EditorJS({ holder:"editorjs", tools:{ header:{ class:Header, inlineToolbar:['link'] }, list:{ class:List, inlineToolbar:['link','bold'] } } }) let saveBtn=document.querySelector('button') saveBtn.addEventListener('click',()=>{ editor.save().then((outputData)=>{ console.log(outputData) }) })
运行后触发报错:
Uncaught TypeError: Failed to resolve module specifier "@editorjs/editorjs". Relative references must start with either "/", "./", or "../"
解决方案
浏览器原生模块系统无法识别@editorjs/editorjs这类裸模块标识符,结合CDN使用场景,有两种修复方式:
方式1:使用CDN ES模块地址直接导入
修改sampler.js的import语句,替换为对应工具的ES模块CDN链接,同时补充缺失的List工具导入:
import { EditorJS } from 'https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest/dist/editorjs.esm.js'; import { Header } from 'https://cdn.jsdelivr.net/npm/@editorjs/header@latest/dist/header.esm.js'; import { List } from 'https://cdn.jsdelivr.net/npm/@editorjs/list@latest/dist/list.esm.js'; const editor = new EditorJS({ holder:"editorjs", tools:{ header:{ class:Header, inlineToolbar:['link'] }, list:{ class:List, inlineToolbar:['link','bold'] } } }) let saveBtn=document.querySelector('button') saveBtn.addEventListener('click',()=>{ editor.save().then((outputData)=>{ console.log(outputData) }) })
同时需要删除HTML中原本的<script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script>,因为模块会自行加载依赖。
方式2:使用全局变量(无需import)
如果不想用模块导入,可直接使用EditorJS及工具暴露的全局变量,修改sampler.js去掉import语句:
const editor = new EditorJS({ holder:"editorjs", tools:{ header:{ class:Header, inlineToolbar:['link'] }, list:{ class:List, inlineToolbar:['link','bold'] } } }) let saveBtn=document.querySelector('button') saveBtn.addEventListener('click',()=>{ editor.save().then((outputData)=>{ console.log(outputData) }) })
这种情况下,HTML需要补充所有用到的工具CDN链接,同时sampler.js不需要type="module":
<script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/header@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/list@latest"></script> <script src="sampler.js"></script>
内容的提问来源于stack exchange,提问作者Vatsal A Mehta
相关产品推荐
相关产品推荐

