eternalStudent
eternalStudent

Reputation: 484

CORS-cross-origin error on dynamic load of resource

I face the error:

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.

at runtime when the page loads in browser and tries to dynamically import a json file.

The piece of code:

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

which is loaded by the html template:

#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>

When I was doing the same from another source file which imports the JSON statically, everything was fine with no CORS issue. But, since I changed it to use rollup to try to dynamically load the resource file at runtime, I'm facing this error.

I post the whole setup in case I miss something there. Not sure where this CORS comes from.

Using:

"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 is setup with:

{
  "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"]
}

And rollup:

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",
    },
}

Upvotes: 7

Views: 4313

Answers (2)

MarcusOtter
MarcusOtter

Reputation: 1273

I encountered the same problem with dynamic imports. The error specifically only occurred when I refreshed the page with cache disabled, and only in Chrome.

In the proposal document for this issue (linked by Sideshowbarker in their comment) we see that dynamic imports work the correct (old) way again for:

  • same-origin classic <script>
  • cross-origin classic <script>s with crossorigin="" attribute set, or
  • module <script>

In my case, I added type="module" and this error went away. Setting the crossorigin attribute should also work.

Upvotes: 1

Z Johnson
Z Johnson

Reputation: 11

When accessing files using the "file://" protocol directly in the browser, you may encounter a CORS (Cross-Origin Resource Sharing) error. This error occurs because the browser enforces the same-origin policy, which restricts interactions between resources loaded via the "file://" protocol and resources from different origins. You can use a local server: Set up a local server (e.g., using Node.js or Python's SimpleHTTPServer) and serve your files from there. By accessing your files through the local server's URL (e.g., "http://localhost:8000"), you can avoid the CORS error.

Recommend: https://github.com/JacksonTian/anywhere

Upvotes: 1

Related Questions