【问题标题】:Import one JS file into another in plain JS用纯 JS 将一个 JS 文件导入另一个
【发布时间】:2022-06-17 17:04:19
【问题描述】:

假设我有两个 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);
}

当我在浏览器中运行 print 函数时,出现以下错误

Uncaught SyntaxError: Cannot use import statement outside a module

Unexpected token 'export' 

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

有没有其他方法可以把script2.js改成module?

【问题讨论】:

  • 如果你没有 HTML 文件,你是如何在浏览器中运行 JS 的?
  • 我正在使用 Oracle 策略建模。它是一种生成 HTML 的低代码解决方案
  • 代码是如何运行的?在浏览器中还是在不同的运行时环境中?
  • 与当前错误消息无关:import { Hello } from './script1.js'; 不导入默认导出。 import Hello from './script1.js'; 导入默认导出。
  • 在浏览器中。所以 OPM 不支持很多东西,比如手风琴。我只使用 javascript 来制作手风琴并集成到 OPM 中。

标签: javascript


【解决方案1】:

您可以添加一个.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';

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2017-05-02
    • 2021-07-05
    • 1970-01-01
    • 2020-03-31
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多