首页 > 解决方案 > 如何让导入/导出适用于 chrome 浏览器?

问题描述

我对学习 HTML、CSS 和 JS 非常非常陌生。我正在尝试编写我的第一页,我的“main.js”文件从我的“utils.js”文件中导入一个函数以在我的“index.html”文件中使用。我的浏览器是 google chrome 版本 85.0.4183.121 (Official Build) (64-bit),我在 Windows 10 的操作系统上运行。

我要学习的教程是:(在 youtube.com 上)
“带有导入/导出语法(ES6)的 JavaScript 模块 - JavaScript 教程”
频道是:
“dcode”
网址:
https ://youtu.be/s9kNndJLOjg

下面是我所做的一切的表示。

My folder/file tree looks like below: (on Desktop)

HTML_folder-
            |-js_folder-
            |           |-main.js
            |           |-utils.js
            |
            |-index.html

我的 index.html 文档如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=10.0">
  <title>Chrome Dino Replica</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    canvas {
      display: block;
    }
  </style>
</head>
<body>
  <canvas id="game" width="640" height="400"></canvas>
  <script type="module" src="./js_folder/main.js"></script>
</body>
</html>

我的 main.js 文档如下所示:

import {double} from './utils.js';

console.log(double(5));

const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

// Variables
let score;
let scoreText;
let highscore;
let highscoreText;
let player;
let gravity;
let obstacles = [];
let gameSpeed;
let keys = {};

// Event Listeners
document.addEventListener('keydown', function (evt) {
  keys[evt.code] = true;
});
document.addEventListener('keyup', function (evt) {
  keys[evt.code] = false;
});

class Player {
  constructor (x, y, w, h, c) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.c = c;

    this.dy = 0;
    this.jumpForce = 15;
    this.originalHeight = h;
    this.grounded = false;
    this.jumpTimer = 0;
  }

  Animate () {
    // Jump
    if (keys['Space'] || keys['KeyW']) {
      this.Jump();
    } else {
      this.jumpTimer = 0;
    }

    if (keys['ShiftLeft'] || keys['KeyS']) {
      this.h = this.originalHeight / 2;
    } else {
      this.h = this.originalHeight;
    }

    this.y += this.dy;

    // Gravity
    if (this.y + this.h < canvas.height) {
      this.dy += gravity;
      this.grounded = false;
    } else {
      this.dy = 0;
      this.grounded = true;
      this.y = canvas.height - this.h;
    }

    this.Draw();
  }

  Jump () {
    if (this.grounded && this.jumpTimer == 0) {
      this.jumpTimer = 1;
      this.dy = -this.jumpForce;
    } else if (this.jumpTimer > 0 && this.jumpTimer < 15) {
      this.jumpTimer++;
      this.dy = -this.jumpForce - (this.jumpTimer / 50);
    }
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.fillRect(this.x, this.y, this.w, this.h);
    ctx.closePath();
  }
}

class Obstacle {
  constructor (x, y, w, h, c) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.c = c;

    this.dx = -gameSpeed;
  }

  Update () {
    this.x += this.dx;
    this.Draw();
    this.dx = -gameSpeed;
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.fillRect(this.x, this.y, this.w, this.h);
    ctx.closePath();
  }
}

class Text {
  constructor (t, x, y, a, c, s) {
    this.t = t;
    this.x = x;
    this.y = y;
    this.a = a;
    this.c = c;
    this.s = s;
  }

  Draw () {
    ctx.beginPath();
    ctx.fillStyle = this.c;
    ctx.font = this.s + "px sans-serif";
    ctx.textAlign = this.a;
    ctx.fillText(this.t, this.x, this.y);
    ctx.closePath();
  }
}

// Game Functions
function SpawnObstacle () {
  let size = RandomIntInRange(20, 70);
  let type = RandomIntInRange(0, 1);
  let obstacle = new Obstacle(canvas.width + size, canvas.height - size, size, size, '#2484E4');

  if (type == 1) {
    obstacle.y -= player.originalHeight - 10;
  }
  obstacles.push(obstacle);
}


function RandomIntInRange (min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

function Start () {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  ctx.font = "20px sans-serif";

  gameSpeed = 3;
  gravity = 1;

  score = 0;
  highscore = 0;
  if (localStorage.getItem('highscore')) {
    highscore = localStorage.getItem('highscore');
  }

  player = new Player(25, 0, 50, 50, '#FF5858');

  scoreText = new Text("Score: " + score, 25, 25, "left", "#212121", "20");
  highscoreText = new Text("Highscore: " + highscore, canvas.width - 25, 25, "right", "#212121", "20");

  requestAnimationFrame(Update);
}

let initialSpawnTimer = 200;
let spawnTimer = initialSpawnTimer;
function Update () {
  requestAnimationFrame(Update);
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  spawnTimer--;
  if (spawnTimer <= 0) {
    SpawnObstacle();
    console.log(obstacles);
    spawnTimer = initialSpawnTimer - gameSpeed * 8;
    
    if (spawnTimer < 60) {
      spawnTimer = 60;
    }
  }

  // Spawn Enemies
  for (let i = 0; i < obstacles.length; i++) {
    let o = obstacles[i];

    if (o.x + o.w < 0) {
      obstacles.splice(i, 1);
    }

    if (
      player.x < o.x + o.w &&
      player.x + player.w > o.x &&
      player.y < o.y + o.h &&
      player.y + player.h > o.y
    ) {
      obstacles = [];
      score = 0;
      spawnTimer = initialSpawnTimer;
      gameSpeed = 3;
      window.localStorage.setItem('highscore', highscore);
    }

    o.Update();
  }

  player.Animate();

  score++;
  scoreText.t = "Score: " + score;
  scoreText.Draw();

  if (score > highscore) {
    highscore = score;
    highscoreText.t = "Highscore: " + highscore;
  }
  
  highscoreText.Draw();

  gameSpeed += 0.003;
}

Start();

我的 utils.js 文档如下所示:

export function double (n) {
    return n * 2;
}

在控制台中返回的错误:

Error 1:
Access to script at 'file:///C:/Users..../HTML/js_folder/main.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.                                                  index.html:1

Error 2:
Failed to load resource: net::ERR_FAILED                                                        main.js:1

如果我从'main.js'中删除(下面的行),它会起作用..

import {double} from './utils.js';

console.log(double(5));

但是,这并没有拉入我的“utlis.js”文件,而且我不知道(如何、什么或为什么)我无法加载为我的文档制作的 js 模块。

"I've tried...
google searching error
  |-- run cmd command 'chrome.exe --allow-running-insecure-content' with the 'index.html' file
  |-- look at multiple 'stackoverflow.com' & 'superuser.com' search queries of this problem and tried the
  |   solutions
  |-- watched a lot of 'youtube.com' on how to use import/export js files

rewriting the string to locate the folder multiple times"

我很困惑..而且我不明白 chrome 似乎有这个问题,所以请解释这一切的原因以及如何纠正它。我将不胜感激,感谢您的宝贵时间。

标签: javascriptgoogle-chromewindows-10es6-modules

解决方案


此 ES6 模块内容不适用于使用该file://协议直接从您自己机器的文件系统加载的本地 html 和 Javascript 文件。阅读此https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

您必须使用本地 Web 服务器来使用这种导出/导入模块方法开发代码。因为网络蠕虫。

此处为 Chrome 浏览器添加了一个简单的网络服务器https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en

或者,您可以在 Windows 上使用内置的 IIS Web 服务器。有很多关于设置开发的教程。


推荐阅读