问题描述
好吧,我查看了这个网站并找到了几个不同的答案,但没有一个对我有用.基本上有一个 js 文件,其中包含许多功能以及应用程序的主要代码.我想将我的所有函数移动到另一个 js 文件,以便我可以稍微清理我的代码.我对js相当陌生,但我知道在python中它就像说从(路径)导入(模块)作为(昵称)"一样简单
无论如何,假设我的 functions.js 模块中有一个名为 show message 的函数.
导出函数 show_message(){警报(你好");}
然后我在 main.js 文件的顶部我做了
import { show_message } from './functions.js'//我也试过这样导入:import * as func from './functions.js'//然后我调用它显示消息();//我也试过func.show_message();
我知道这很简单,但正如我所说的,我所看到的所有地方都看到了不同的答案,但没有一个对我有用.顺便说一句,我正在使用 Firefox.我也在控制台中收到一个错误,说我的导入声明需要在我的模块的顶部,我通过在我的 HTML 链接中指定类型来解决这个问题(script src="/static/main.js" type="模块")错误消失了,但现在说同源策略不允许读取文件(路径)中的远程资源(原因:cors 请求不是 HTTP)."
另一个错误是本文档中不允许使用模块源 URI".
这让我觉得我的导入语法可能是正确的,而错误出在我的 HTML 代码中?
感谢任何帮助.
0.简短的回答
您需要安装并运行本地 Web 服务器.- 有关如何的建议,继续阅读.
1.基础知识
我尝试了一个简单的 HTML 文件——index.html
——如下:
<!-- index.html - 保持简单的最小 HTML -->
在子文件夹 js
中,我放置了 JavaScript 文件 functions.js
:
//js/functions.jsalert('你好');
双击 index.html
时,我的默认网络浏览器 – Firefox 89.0(64 位) - 按 后显示以下内容.请注意 JavaScript 代码如何未运行:
错误信息:跨源请求被阻止:同源策略不允许读取位于 file:///C:/stackexchange/reproduce/jsModule/moduleNW/basics/js/functions.js 的远程资源.(原因:CORS 请求不是 http).
作弊的解决方案"是(暂时)从 HTML 中删除 type="module"
代码.
警报随后会正确显示.
但我想要将 JavaScript 代码作为模块运行,所以我放回了type="module"
在 HTML 中.
2.安装并运行本地 Web 服务器
要将其作为模块运行,它需要在 Web 服务器上运行.因此,如果您想在自己的计算机上运行代码,则需要(安装并)启动本地 Web 服务器.
目前流行的一种替代方法是 live-server.这对我有用.
- 打开一个终端.(在 Windows 上:
cmd.exe
.) - 输入
npm
并按 查看是否安装了 Node.js. - 如果您收到
command not found
,请从注意 1.我使用的是 Windows 10,但上述说明在 Linux 和macOS 也是.
注意 2.在这里我使用了 Firefox 89.0,但我也尝试过 Google Chrome 91.0.唯一显着的区别是 CORS 错误消息,在 Chrome 中显示为:从源 'null' 访问位于 'file:///C:/stackexchange/reproduce/jsModule/basics/js/functions.js' 的脚本已被 CORS 策略阻止:仅协议支持跨源请求方案:http、数据、chrome、chrome-extension、chrome-untrusted、https.
3.导出和导入
接下来我创建一个新文件夹
demo2
,其中包含以下demo2.html
:<!-- demo2.html - 为了简单起见,甚至更短的 HTML --><身体><h1>你好世界!</h1><p>Javascript 模块.</p><脚本类型=模块"src=js/main.js"></script>
我还在子文件夹
js
中创建了以下三个 JavaScript 文件://js/module1.jsexport function hi () { console.log('Hi from module 1.');}
和
//js/module2.jsexport function howdy () { console.log('Howdy from module 2!');}
和
//js/main.js从'./module1.js'导入{你好};从'./module2.js'导入{你好};你好();你好();
现在我从终端在
demo2.html
所在的文件夹中运行 live-server居住.这次我从输入开始live-server --port=1234 --entry-file=demo2.html
并按 .截图:参考:
在 Windows 10 上,我曾经需要修复安装.
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)"
anyways let's say I have a function named show message in my functions.js module.
export function show_message(){ alert("Hello"); }
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();
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)."
And the other error says "module source URI is not allowed in this document".
which makes me think maybe my syntax for importing is right and the error is in my HTML code?
Any help is appreciated.
解决方案0. The short answer
You need to install and run a local web server. - For a suggestion on how,read on.
1. The basics
I tried a simple HTML file –
index.html
– as follows:<!-- index.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>
In the subfolder
js
I put the JavaScript filefunctions.js
:// js/functions.js alert('Hello');
When double-clicking
index.html
, my default web browser – Firefox 89.0(64-bit) – shows the following, after pressing .Notice how the JavaScript code is not running:The error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/stackexchange/reproduce/jsModule/moduleNW/basics/js/functions.js. (Reason: CORS request not http).
A cheating "solution" is to (temporarily) remove
type="module"
from the HTMLcode.
The alert then displays without errors.But I want to run the JavaScript code as a module, so I put back
type="module"
in the HTML.2. Install and run a local web server
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.exe
.) - Type
npm
and hit to see if Node.js is installed. - If you get
command not found
, download at https://nodejs.org/en/download/and install.
(On Ubuntu, you can trysudo apt install -y nodejs
.) - Install live-server:
npm install live-server -g
. - Change directory to where your page lives:
cd <path-to-index.html>
. - Start the server:
live-server .
(Should openlocalhost: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 andmacOS too.
Note 2.Here I used Firefox 89.0, but I have tried Google Chrome 91.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/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, chrome-untrusted, https.
3. Exporting and importing
Next I create a new folder
demo2
containing the followingdemo2.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>
I also create the following three JavaScript files in the subfolder
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();
Now I run live-server from the terminal in the folder where
demo2.html
resides.This time I start by typinglive-server --port=1234 --entry-file=demo2.html
and hitting . Screenshot:References:
- Installing Node.js live-server
- The live-server docs
- Live-server can't find the file specified
- Export and Import
On Windows 10, I once needed torepair the installation.
这篇关于Javascript 模块在浏览器中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- Open a terminal. (On Windows: