[英]Import one JS file into another in plain JS
So let's imagine i have two js scripts所以让我们假设我有两个 js 脚本
script1.js script1.js
export default function Hello() {
return "Hello buddy!";
}
script2.js script2.js
import { Hello } from './script1.js';
function print(){
let val = Hello;
console.log(val);
}
When i run the function print in browser i get the following error当我在浏览器中运行打印功能时,出现以下错误
Uncaught SyntaxError: Cannot use import statement outside a module
Unexpected token 'export'
I did some investigation and this is solved by adding type module to script2.js.我做了一些调查,通过向 script2.js 添加类型模块来解决这个问题。 But the question is.
但问题是。 I dont have a HTML to change the script.
我没有 HTML 来更改脚本。 I do everything in vanilla javascript.
我用香草 javascript 做所有事情。 so, is the solution to get the scripts by ID and change the type of the script2.js from text/javascript to module?
那么,是通过 ID 获取脚本并将 script2.js 的类型从 text/javascript 更改为模块的解决方案吗?
Is there any other way to change the script2.js to module?有没有其他方法可以将 script2.js 更改为模块?
You can add an .mjs
file.您可以添加一个
.mjs
文件。
Example例子
// index.js
import otherFile from './otherFile.js';
// otherFile.js
import otherOtherFile from './otherOtherFile.mjs';
export default './otherFile.js';
// otherOtherFile.mjs
export default 'otherOtherFile.mjs';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.