【问题标题】:Cannot import Javascript file in other Javascript file无法在其他 Javascript 文件中导入 Javascript 文件
【发布时间】:2021-01-08 12:33:31
【问题描述】:

对于一个项目,我使用 Django 作为后端,使用 HTML/CSS/JS 作为前端。

对于一个 HTML 页面,我使用了两个 JS 文件:dom_creator.js 和 console_page.js。我想在 console_page 中使用 dom_creator 的功能,但是无论我尝试什么,我都找不到正确的导入语句(许多 ES6 导入语句甚至使我的 console_page.js 停止工作)。

我还有一个模块导入到我的 HTML (console_module.js)。在那个文件中,我没有问题导入 dom_creator.js

import {function1, function2} from "./dom_creator.js"

我如何能够从 console_page.js(不是模块)中的 dom_creator 导入函数?我已经尝试了有关 Stack Overflow 的所有建议,但似乎没有一个有效。

【问题讨论】:

  • 你要导出两个函数吗?你能提供关于dom_creator.js的信息吗?
  • 你不能*从非 es6 模块导入。你有几个选项来完成这个:1 - 使用<script type="module">强制浏览器将你的代码视为模块(注意IE不支持这个)2 - 使用像webpack,browserify,parcel这样的捆绑器将你的代码捆绑成一段代码3 - 公开更新window 对象所需的功能:window.utils = {do: function(){}}

标签: javascript django


【解决方案1】:

要将一个函数导入另一个文件,首先需要将其导出,

因此,如果您使用的是 es5(主要是 NodeJs 中的情况),则需要将其导出如下:

var myfunction = function () {}

module.exports = { myfunction }

在较新的版本 (es6+) 中,您可以像这样使用导出:

var myfunction = function () {}

export myfunction;
// then you can import it like: import {myfuntion} from 'file.js';
// or with another name: import {myfuntion as john} from 'file.js';

// or export it as default like:
export default myfunction;
// then you can import it like import myfuntion from 'file.js';
// or any other custom name: import john from 'file.js';

从你的问题中我唯一无法理解的是 with question 与 Django 的关系?

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 2018-10-19
    • 2021-01-24
    • 1970-01-01
    相关资源
    最近更新 更多