1. Description of the problem
When learning the Module part of JavaScript ES6, using the script tag to load ES6, the code reports an error. The error message is as follows:
The test code is as follows:
2. Problem tracing
1. Open the file locally, and the reference module is resource cross-domain caused by the file protocol?
Many blog posts have made the following judgments on this issue. But I thought, usually the external scripts that introduce the file protocol in the HTML file are also executed normally? After searching, I found the answer on MDN , which is described as follows:
2. If I put the reference module script on the server, it can be executed normally?
After testing, it still reports CORS-related errors.
3. If the module script referenced by the remote server is set to be cross-domain, can it be executed normally?
After testing, the imported modules can be executed normally! ! !
4. Setting type="module" for the script tag will cause the resources of the referenced module to be limited by the same-origin policy?
After checking MDN , ECMAScript 2015 specifications and other materials, no relevant instructions were found. I explored all the way and asked questions on Zhihu . With the help of enthusiastic netizens, I finally found the answer. The description document of the V8 engine is as follows:
5. Final conclusion
After looking at the HTML specification at WHATWG , I finally found the relevant instructions. This sentence is a bit confusing. It probably means that the module script requires the loaded module to support CORS
cross-domain .
3. Solutions
1. Project development
Module resource server configuration Access-Control-Allow-Origin
, you can specify a specific domain name, or use *
wildcards .
2. During daily study
The VS Code download Live Server
plug-in helps you set up a static resource server without cross-domain problems.