Javascript module not working in browser?

前端 未结 8 1826
半阙折子戏
半阙折子戏 2020-12-10 11:35

Alright, I have looked on this site and have found several different answers, none of which have worked for me. Basically had a js file that had many functions in it along

相关标签:
8条回答
  • 2020-12-10 12:07

    You might want to use broswerify instead. It allows you to write NodeJS-style modules and then compiles them into a single browser-friendly JavaScript file, allowing you to get all the performance benefits of loading only a single file. It also means you can easily use the same code both server side and client side.

    If you want to stick with separate files, it looks like you are well on your way. Unlike regular JavaScript files, modules are subject to Cross-Origin Resource Sharing (CORS) restrictions. They have to be loaded from the same origin, and cannot be loaded from the local filesystem. If you are loading them from the local file system, move them to a server. If you are already hosting them on a server, add the Access-Control-Allow-Origin: * header to the response that serves the module file.

    Lots more gotchas and solutions here and here.

    0 讨论(0)
  • 2020-12-10 12:09

    Using JS modules in the browser On the web, you can tell browsers to treat a element as a module by setting the type attribute to module.

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

    More on https://developers.google.com/web/fundamentals/primers/modules

    0 讨论(0)
  • 2020-12-10 12:13

    If you're using webpack and babel and want to import the code into your bundle, I guess it should be one of the following:

    export default function show_message(){
        alert("Hello");
    }
    

    and then in your code:

    import show_message from 'path/to/show_message.js'
    // or 
    import { default as someOtherName } from 'path/to/show_message.js'
    

    Or if you'd like to export several functions:

    const show_message = function(){
        alert("Hello");
    }
    export { show_message };
    

    and then in your code:

    import { show_message } from 'path/to/show_message.js'
    // or 
    import { show_message as someOtherName } from 'path/to/show_message.js'
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-10 12:16

    Consider going through this url some extension might be causing an issue with the loading of modules:

    This blog might be an answer to what you're expecting.

    You should first check if browser accepts type="module" and use fallback if it doesn't like this:

    <script type="module" src="module.mjs"></script>
    <script nomodule src="fallback.js"></script>
    

    This might be the main reason for the CORS error as written here:

    Unlike regular scripts, module scripts (and their imports) are fetched with CORS. This means cross-origin module scripts must return valid CORS headers such as Access-Control-Allow-Origin: *

    So you need to add CORS header to the module file

    Consider this blog for CORS issue. You should add CORS header ie. Access-Control-Allow-Origin: * to the server config most probably.

    0 讨论(0)
  • 2020-12-10 12:17

    1. The basics

    I tried some simple HTML code as follows:

    <!-- demo.html - minimal HTML to keep it simple -->
    <html><head>
      <meta charset="UTF-8" />
      <link rel="shortcut icon" href="#">
    </head>
    <body>
      <h1>Hello world!</h1>
      <p>Experimenting with JavaScript modules.</p>
      <script type="module" src="js/functions.js"></script>
    </body></html>
    

    And the JavaScript code is just one line - not counting the comment:

    // js/functions.js
    alert("Hello");
    

    My web browser shows the following. Notice how the JavaScript code is not running:

    A recommended action for an issue like this, is to open the browser's development tools, typically by hitting F12 on the keyboard. Here is what Firefox 77 says:

    In text: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/stackexchange/reproduce/jsModule/RobotMan/basics/js/functions.js. (Reason: CORS request not http).

    A cheating "solution" is to (temporarily) remove type="module" from the HTML code.
    The alert then displays as intended - without errors.


    But I want to run the JavaScript as a module, so I put back type="module" into the HTML file.

    Actually, to run it as a module, it needs to run on a web server. Thus, if you want to run the code on your own computer, you will need to (install and) start a local web server. One currently popular alternative is live-server.
    Here is what worked for me.

    • Open a terminal. (On Windows: cmd.)
    • Type npm and hit Enter to see if Node.js is installed.
    • If you get command not found, download at https://nodejs.org/en/download/ and install.
    • Install live-server: npm install -g live-server (per-user installation).
    • Change directory to where your page lives: cd <path-to-demo.html>.
    • Start the server: live-server demo.html
      (Should open localhost:8080 in your default browser and show the alert. See below.)

    Note 1: I am on Windows 10, but the above instructions should work fine on Linux and macOS too.
    Note 2: I have used Firefox 77.0 above, but I tried Google Chrome 83.0 as well. The only notable difference is the CORS error message, which in Chrome reads: Access to script at 'file:///C:/stackexchange/reproduce/jsModule/RobotMan/basics/js/functions.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

    2. Exporting and importing

    Create a new folder modules containing the following demo2.html:

    <!-- demo2.html - even shorter HTML for simplicity -->
    <body>
      <h1>Hello world!</h1>
      <p>Javascript modules.</p>
      <script type="module" src="js/main.js"></script>
    </body>
    

    Also create the following three JavaScript files in the sub-folder js:

    // js/module1.js
    export function hi() {console.log("Hi from module 1.");}
    

    and

    // js/module2.js
    export function howdy() {console.log("Howdy from module 2!");}
    

    and

    // js/main.js
    import {hi} from './module1.js';
    import {howdy} from './module2.js';
    hi();
    howdy();
    

    Run live-server from the terminal in the folder where demo2.html resides. This time start it by typing live-server --port=1234 --entry-file=demo2.html and hitting Enter. Expect to see something like:

    References:
    https://gist.github.com/donmccurdy/20fb112949324c92c5e8
    https://javascript.info/import-export
    https://stackoverflow.com/questions/39578877/live-server-cant-find-the-file-specified#43717740

    0 讨论(0)
  • 2020-12-10 12:26

    On the script tag you are using to load the js in the browser you need to add the attribute

    type="module"

    It will look like the following:

    <script type="module">
      import {addTextToBody} from './utils.mjs';
    
      addTextToBody('Modules are pretty cool.');
    </script>
    

    utils.mjs:

    export function addTextToBody(text) {
      const div = document.createElement('div');
      div.textContent = text;
      document.body.appendChild(div);
    }
    

    This is if you are not using a bundler like webpack and working directly in the browser.

    Source of code: https://jakearchibald.com/2017/es-modules-in-browsers/

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