从另一个 js 文件导入函数。Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48211891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:02:53  来源:igfitidea点击:

Import functions from another js file. Javascript

javascriptimport

提问by Samy Sammour

I have a question about including a file in javascript. I have a very simple example:

我有一个关于在 javascript 中包含文件的问题。我有一个非常简单的例子:

--> index.html
--> models
      --> course.js
      --> student.js

course.js:

课程.js:

function Course() {
    this.id = '';
    this.name = '';
}

A student has a course property. like this:

学生有一个课程属性。像这样:

import './course';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}

and the index.html is like:

和 index.html 是这样的:

<html>
    <head>
        <script src="./models/student.js" type="text/javascript"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>

But I am getting an error on the line "var x = new Student();":

但是我在“var x = new Student();”行上收到一个错误:

Student is not defined

学生未定义

When I remove the import from Student, I don't receive the error anymore. I have tried to use (require, import, include, create a custom function, export) and none has worked for me.

当我从 Student 中删除导入时,我不再收到错误消息。我曾尝试使用(需要、导入、包含、创建自定义函数、导出),但没有一个对我有用。

Anybody knows why? and how to fix that?

有谁知道为什么?以及如何解决这个问题?

P.S. the path is correct, it comes from the autocomplete in VS Code

PS路径是正确的,它来自VS Code中的自动完成

采纳答案by Chris G

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

以下在 Firefox 和 Chrome 中对我有用。在 Firefox 中,它甚至可以从file:///

models/course.js

模型/course.js

export function Course() {
    this.id = '';
    this.name = '';
};

models/student.js

模型/student.js

import { Course } from './course.js';

export function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
};

index.html

索引.html

<div id="myDiv">
</div>
<script type="module">
    import { Student } from './models/student.js';

    window.onload = function () {
        var x = new Student();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

回答by Bablu Ahmed

You can try as follows:

您可以尝试如下:

//------ js/functions.js ------
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

You can also import completely:

您还可以完全导入:

//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5

Normally we use ./fileName.jsfor importing own js file/moduleand fileName.jsis used for importing package/librarymodule

通常我们./fileName.js用于导入自己的js file/modulefileName.js用于导入package/library模块

When you will include the main.js file to your webpage you must set the type="module" attribute as follows:

当您将 main.js 文件包含到您的网页时,您必须按如下方式设置 type="module" 属性:

<script type="module" src="js/main.js"></script>

For more details please check ES6 modules

有关更多详细信息,请查看ES6 模块

回答by samanime

By default, scripts can't handle imports like that directly. You're probably getting another error about not being able to get Course or not doing the import.

默认情况下,脚本不能直接处理这样的导入。您可能会收到另一个关于无法获取 Course 或不进行导入的错误。

If you add type="module"to your <script>tag, and change the import to ./course.js(because browsers won't auto-append the .js portion), then the browser will pull down course for you and it'll probably work.

如果您添加type="module"到您的<script>标签,并将导入更改为./course.js(因为浏览器不会自动附加 .js 部分),那么浏览器将为您拉下路线,它可能会起作用。

import './course.js';

function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
}


<html>
    <head>
        <script src="./models/student.js" type="module"></script>
    </head>
    <body>
        <div id="myDiv">
        </div>
        <script>
        window.onload= function() {
            var x = new Student();
            x.course.id = 1;
            document.getElementById('myDiv').innerHTML = x.course.id;
        }
        </script>
    </body>
</html>


If you're serving files over file://, it likely won't work. Some IDEs have a way to run a quick sever.

如果您通过 提供文件file://,它可能无法正常工作。一些 IDE 可以运行快速服务器。

You can also write a quick expressserver to serve your files (install Node if you don't have it):

您还可以编写一个快速express服务器来为您的文件提供服务(如果您没有,请安装 Node):

//package.json
{
  "scripts": { "start": "node server" },
  "dependencies": { "express": "latest" }
}

// server/index.js
const express = require('express');
const app = express();

app.use('/', express.static('PATH_TO_YOUR_FILES_HERE');
app.listen(8000);

With those two files, run npm install, then npm startand you'll have a server running over http://localhost:8000which should point to your files.

使用这两个文件,运行npm install,然后npm start您将有一个服务器运行,http://localhost:8000该服务器应该指向您的文件。

回答by Rohan Patil

//In module.js add below code

export function multiply() {
    return 2 * 3;
}

// Consume the module in calc.js

// 使用 calc.js 中的模块

import { multiply } from './modules.js';

const result = multiply();

console.log(`Result: ${result}`);

// Module.html

// 模块.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Module</title>
</head>
<body>

  <script type="module" src="./calc.js"></script>
</body>
</html>

Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error

它的设计模式相同的代码可以在下面找到,请使用实时服务器进行测试,否则您将收到 CORS 错误

https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

回答by Cristian Thompson

From a quick glance on MDN I think you may need to include the .jsat the end of your file name so the import would read import './course.js'instead of import './course'

从 MDN 上快速浏览一下,我认为您可能需要.js在文件名末尾包含 ,以便导入读取 import './course.js'而不是import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

参考:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import