JavaScript打包项目出现Uncaught SyntaxError: Unexpected token '<'错误求助
bundle.js:1 Uncaught SyntaxError: Unexpected token '<' Hey there! Let’s work through this frustrating error you’re hitting. That Unexpected token '<' message basically means your browser tried to load bundle.js as JavaScript, but instead got HTML content (usually your index.html file) back. Let’s walk through the most common fixes tailored to your bundler practice project:
Common Causes & Fixes
1. Mismatched File Paths Between HTML and Bundle Output
First, double-check where your bundler saves bundle.js and how your HTML references it:
- Open your project’s build/output settings (like
webpack.config.jsor your custom bundler script) to confirm the output directory forbundle.js(e.g.,dist/or the root folder). - Then look at your HTML file’s
<script>tag: ifbundle.jslives indist/, your tag should look like<script src="./dist/bundle.js"></script>. A wrong path here will make the server return a 404, and many dev servers fall back to serving index.html instead—hence the HTML in your JS file.
2. Dev Server Routing Fallback Issues
If you’re using a local dev server (like Webpack Dev Server), it might be configured to serve index.html for any unknown routes (a common setup for single-page apps). If your bundle.js path is incorrect, the server will send index.html instead of the JS file:
- Check your server config: make sure static assets are served from the correct directory. For example, in Webpack Dev Server, set
static(orcontentBasein older versions) to the folder where yourbundle.jslives. - Test by requesting
bundle.jsdirectly in your browser—if you see HTML instead of JS, this fallback is the culprit.
3. Accidental HTML in Your Bundle
If you open the generated bundle.js file and actually see HTML code inside it, your bundler is incorrectly including HTML files in the JS bundle:
- Verify your bundler’s entry points: make sure you’re only targeting JavaScript files (e.g.,
src/index.js) and not accidentally adding an HTML file as an entry. - If you built a custom bundler, check your file processing logic: ensure you’re filtering out non-JS files or handling them properly instead of dumping their content into
bundle.js.
Next Steps
If none of these fixes work, share snippets of your bundler configuration file (like webpack.config.js) or your custom bundler code, and we can dive deeper into the specific setup.
内容的提问来源于stack exchange,提问作者FEDEIZ




