繁体   English   中英

用纯 JS 将一个 JS 文件导入另一个

[英]Import one JS file into another in plain JS

所以让我们假设我有两个 js 脚本

script1.js

export default function Hello() {
     return "Hello buddy!";
}

script2.js

import { Hello } from './script1.js';

function print(){
     let val = Hello;
     console.log(val);
}

当我在浏览器中运行打印功能时,出现以下错误

Uncaught SyntaxError: Cannot use import statement outside a module

Unexpected token 'export' 

我做了一些调查,通过向 script2.js 添加类型模块来解决这个问题。 但问题是。 我没有 HTML 来更改脚本。 我用香草 javascript 做所有事情。 那么,是通过 ID 获取脚本并将 script2.js 的类型从 text/javascript 更改为模块的解决方案吗?

有没有其他方法可以将 script2.js 更改为模块?

您可以添加一个.mjs文件。

例子

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM