Import functions from another js file. Javascript

前端 未结 5 927
臣服心动
臣服心动 2020-12-02 23:02

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

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


        
相关标签:
5条回答
  • 2020-12-02 23:24

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

    models/course.js

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

    models/student.js

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

    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>
    
    0 讨论(0)
  • 2020-12-02 23:26
    //In module.js add below code
    
    export function multiply() {
        return 2 * 3;
    }
    

    // Consume the module in calc.js

    import { multiply } from './modules.js';
    
    const result = multiply();
    
    console.log(`Result: ${result}`);
    

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

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

    0 讨论(0)
  • 2020-12-02 23:35

    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.

    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.

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

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

    0 讨论(0)
  • 2020-12-02 23:41

    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

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

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

    For more details please check ES6 modules

    0 讨论(0)
  • 2020-12-02 23:43

    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'

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

    0 讨论(0)
提交回复
热议问题