Javascript模块在浏览器中不起作用? [英] Javascript module not working in browser?

查看:97
本文介绍了Javascript模块在浏览器中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我浏览了这个网站,发现了几个不同的答案,但没有一个对我有用. 基本上有一个js文件,其中包含许多功能以及该应用程序的主要代码.我想将所有功能移到另一个js文件中,以便可以稍微整理一下代码.我对js还是很陌生,但是我知道在python中它就像说从(路径)导入(模块)为(昵称)"一样简单

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 with the main code for the app. I wanted to move all my functions to another js file so that I could clean up my code a little. I am fairly new to js but I know in python it was as simple as saying "import (module) as (nickname) from (path)"

无论如何,我在functions.js模块中有一个名为show message的函数.

anyways let's say I have a function named show message in my functions.js module.

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

然后我在main.js文件的顶部

and then I at the top of my main.js file I did

import { show_message } from './functions.js'
//I have also tried to import like this:
import * as func from './functions.js'

//And then I call it
show_message();
//I have also tried
func.show_message();

我知道这很简单,但是正如我在各处所看到的那样,我看到了不同的答案,但没有一个对我有用.我正在使用Firefox.我还在控制台中收到一条错误消息,说我的导入声明需要放在模块的顶部,我通过在HTML链接中指定类型(脚本src ="/static/main.js" type =模块") 错误消失了,但是现在却说:相同的源策略禁止读取文件(路径)上的远程资源(原因:CORS请求不是HTTP)."

I know this is something simple, but as I said everywhere I have looked I have seen different answers, none of which work for me. I am using Firefox btw. I am also getting an error in the console saying that my import declarations need to be at the top of my module, I fixed that by specifying the type in my HTML link (script src="/static/main.js" type="module") The error went away but is now saying "same origin policy disallows reading the remote resource at the file (path) (reason: cors request not HTTP)."

另一个错误是此文档中不允许使用模块源URI".

And the other error says "module source URI is not allowed in this document".

这让我觉得也许我的导入语法正确,而错误出在我的HTML代码中?

which makes me think maybe my syntax for importing is right and the error is in my HTML code?

感谢您的帮助.

推荐答案

在用于在浏览器中加载js的脚本标签上,您需要添加属性

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

type ="module"

type="module"

如下所示:

<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);
}

这是如果您没有使用webpack之类的捆绑软件,而是直接在浏览器中工作.

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

代码源: https://jakearchibald.com/2017/es-浏览器模块/

这篇关于Javascript模块在浏览器中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆