资源动态加载时出现CORS跨域错误

问题描述 投票:0回答:1

我面临错误:

TypeError: Failed to resolve module specifier '../static/myJson.json'. 
The base URL is about:blank because import() is called from a CORS-cross-origin script.

在运行时,页面在浏览器中加载并尝试动态

import
json
文件。

这段代码:

// myCode.ts
export const MY_JSON_FILEPATH = "";

window.addEventListener("load", async () => {
  try {
    const myData = await import(MY_JSON_FILEPATH); // replaced by rollup-replace
  } catch (error) {
    console.warn(`Unable to load json file`, error);
    return;
  }
}

由html模板加载:

#index.html
<!DOCTYPE html>
<html>
    <head>
        <meta
            name="viewport"
            content="width=device-width, initial-scale=1, user-scalable=no"
            charset="UTF-8"
        />
        <script src="myCode.js"></script>
    </head>
    <body>
    </body>
</html>

当我从另一个静态导入 JSON 的源文件中执行相同操作时,一切都很好,没有 CORS 问题。但是,由于我将其更改为使用汇总来尝试在运行时动态加载资源文件,所以我遇到了此错误。

我发布了整个设置,以防万一我错过了一些东西。 不确定这个 CORS 从哪里来。

使用:

"typescript": "^4.6.3"
"rollup": "^2.60.2",
"rollup-plugin-typescript2": "^0.31.2",
"rollup-plugin-replace": "^2.2.0",
"rollup-plugin-commonjs": "^10.1.0",

Typescript 设置为:

{
  "compilerOptions": {
    "lib": [
      "dom",
      "es6"
    ],
    "target": "es6",
    "outDir": "./dist",
    "rootDirs": ["./src",  "../../../config/*.json"],
    "module": "ESNext",
    "declaration": true,
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "resolveJsonModule": true,
  },
  "include": ["./src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

并汇总:

import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import replace from "@rollup/plugin-replace";
import typescript from "rollup-plugin-typescript2";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import { createBasicConfig } from "@open-wc/building-rollup";
import merge from "deepmerge";
import path from "path";


const pathResolve = (loc) => path.resolve(__dirname, loc);
const externalJsonFile = path.resolve("./static/myJson.json");

const nodeModules = "node_modules/**";

const baseConfig = createBasicConfig();

export default merge(baseConfig, [
    {
        input: pathResolve("src/index.ts"),
        output: [
            {
                file: pathResolve("dist/index.es.js"),
                format: "esm",
            },
            {
                file: pathResolve("dist/index.js"),
                format: "cjs",
            },
        ],
        external: [externalJsonFile],
        plugins: [
            nodeResolve([".ts"], { browser: true }),
            typescript(),
            replace({
                MY_JSON_FILEPATH: `"${externalJsonFile}"`,
            }),
            commonjs({
                include: nodeModules,
                extensions: [".js", ".ts", ".mjs", ".json"],
            }),
        ],
        context: "window",
    },
}
google-chrome cors es6-modules rollupjs javascript-import
1个回答
0
投票

在浏览器中直接使用“file://”协议访问文件时,可能会遇到 CORS(跨域资源共享)错误。出现此错误的原因是浏览器强制执行同源策略,该策略限制了通过“file://”协议加载的资源与来自不同来源的资源之间的交互。 您可以使用本地服务器:设置本地服务器(例如,使用 Node.js 或 Python 的 SimpleHTTPServer)并从那里提供文件。通过本地服务器的 URL(例如“http://localhost:8000”)访问您的文件,您可以避免 CORS 错误。

推荐:https://github.com/JacksonTian/anywhere

© www.soinside.com 2019 - 2024. All rights reserved.