简体   繁体   English

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

[英]Import functions from another js file. Javascript

I have a question about including a file in javascript.我有一个关于在 javascript 中包含文件的问题。 I have a very simple example:我有一个非常简单的例子:

--> 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.当我从 Student 中删除导入时,我不再收到错误消息。 I have tried to use (require, import, include, create a custom function, export) and none has worked for me.我曾尝试使用(要求、导入、包含、创建自定义 function、导出),但没有一个对我有用。

Anybody knows why?有人知道为什么吗? and how to fix that?以及如何解决这个问题?

PS the path is correct, it comes from the autocomplete in VS Code PS路径是正确的,它来自VS Code中的自动完成

The following works for me in Firefox and Chrome. 以下适用于Firefox和Chrome。 In Firefox it even works from file:/// 在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 的index.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>
//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 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. 您可能会收到另一个关于无法获取课程或未执行导入的错误。

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. 如果将./course.js 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. 如果您通过file://提供文件,则可能无法正常工作。 Some IDEs have a way to run a quick sever. 有些IDE可以运行快速服务器。

You can also write a quick express server to serve your files (install Node if you don't have it): 你也可以写一个快速的express服务器提供文件(安装节点,如果你没有的话):

//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 start and you'll have a server running over http://localhost:8000 which should point to your files. 使用这两个文件,运行npm install ,然后npm start ,你将有一个运行在http://localhost:8000的服务器,它应该指向你的文件。

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.js for importing own js file/module and fileName.js is used for importing package/library module 通常我们使用./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模块

From a quick glance on MDN I think you may need to include the .js at 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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