问题:带export 的 js 只能使用import 或 require 引入,
但是 import 或 require 导入的方法或者文件,它是依赖于本地环境的,必须在编译阶段可以解析路径。
所以 import 不允许引入外部链接文件,如果直接引入的话会报错
解决方案:后端返回文件内容作为函数内容,使用立即执行函数调用,需要注意的一点是字符串生成的立即执行函数无法自动地获取到当前文件里的变量,因此需要手动地在立即执行函数中传递所需变量
// 获取g4生成的js文件 getG4File() { let fileData = JSON.parse(sessionStorage.getItem("treeSelect")) // BasicLexer let data = { spaceName: fileData.spaceName, projectName: fileData.projectName, type: "js", name: "BasicLexer" } readResource(data).then((response) => { // console.log("获取g4生成的js文件", response) if( response.code == 200 ){ let content = response.data.content.replace("import antlr4 from 'antlr4';", "") content = content.replace("export default ", "") content = content + "that.LExprLexer = BasicLexer" new Function('antlr4', 'that', content)(antlr4, this) } }) // BasicParser data = { spaceName: fileData.spaceName, projectName: fileData.projectName, type: "js", name: "BasicParser" } readResource(data).then((BasicParserRes) => { if( BasicParserRes.code == 200 ){ let BasicParser = BasicParserRes.data.content // BasicListener let data = { spaceName: fileData.spaceName, projectName: fileData.projectName, type: "js", name: "BasicListener" } readResource(data).then((BasicListenerRes) => { if( BasicListenerRes.code == 200 ){ let BasicListener = BasicListenerRes.data.content // console.log("获取g4生成的js文件_BasicParser_BasicListener", BasicParser, BasicListener) // 处理 BasicParser BasicParser = BasicParser.replace("import antlr4 from 'antlr4';", "") BasicParser = BasicParser.replace("import BasicListener from './BasicListener.js';", "") BasicParser = BasicParser.replace("export default ", "") // 处理 BasicListener BasicListener = BasicListener.replace("import antlr4 from 'antlr4';", "") BasicListener = BasicListener.replace("export default ", "") BasicListener = BasicListener + "that.LExprParser = BasicParser" // 组合 BasicParser 和 BasicListener在一个文件 let contentTwo = BasicParser + BasicListener new Function('antlr4', 'that', contentTwo)(antlr4, this) this.ParseTreeAll(this.orgRule) } }) } }) },
标签:BasicParser,es6,模块化,js,content,BasicListener,antlr4,data From: https://www.cnblogs.com/yan122/p/16998520.html