Webpack错误 bundle.js:1 Uncaught SyntaxError: Unexpected token <。

17

我在本地主机上运行服务器时出现了错误 bundle.js:1 Uncaught SyntaxError: Unexpected token <。 输出的bundle.js是index.html文件的HTML代码。这是我的webpack.config文件的设置。请问设置有什么问题?

import path from 'path';
import webpack from 'webpack';

export default {
  devtool: 'eval-source-map',
  entry: [
    'webpack-hot-middleware/client',
    path.join(__dirname, '/client/index.js' )
    ],
  output: {
    path: '/',
    publicPath: '/'
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.js$/,
        include: path.join(__dirname, 'client'),
        loaders: ['react-hot-loader', 'babel-loader' ]
      }
    ]
  },
  resolve: {
    extensions: ['.js']
  }    
}

首页

<html>

 <head>
   <meta charset="UTF-8">
   <title>Site</title>
   <meta content="width=device-width, initial-scale=1" name="viewport" />
 </head>

 <body>
   <h1>Hello bla bla bla</h1>
   <div id="app"></div>

   <script src="bundle.js"></script>
 </body>

 </html>

服务器/index.js

import express from 'express';
import path from 'path';

import webpack from 'webpack';
import webpackMiddeleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.config';


let app = express();

const compiler = webpack(webpackConfig);

app.use(webpackMiddeleware(compiler, {
  hot: true,
  publicPath: webpackConfig.output.publicPath,
  noInfo: true
}));
app.use(webpackHotMiddleware(compiler));

app.get('/*', (req, res)=>{
  res.sendFile(path.join(__dirname, './index.html'));
});

app.listen('3000', ()=>{console.log('Running on port 3000')});

客户端/index.js

import React from 'react';
import { render } from 'react-dom';
import App from './components/App';

render(<App/>, document.getElementById('app'));

组件/应用.js

import React from 'react';

class App extends React.Component {
  render(){
    return (
      <h1>Hello</h1>
    );
  }
}

export default App;

package.json:

{
  "name": "xxxxx",
  "version": "1.0.0",
  "description": "xxxxxxxxxx",
  "main": "index.js",
  "scripts": {
    "server": "nodemon --watch server --exec babel-node -- server/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "xxxxxxxxxxxxx"
  },
  "keywords": [
    "
  ],
  "author": "xxxxxxxxx",
  "license": "ISC",
  "bugs": {
    "url": "xxxxxxxxxxxxxxxxxxxxxxx"
  },
  "homepage": "xxxxxxxxxxxxxxxxxxxx",
  "dependencies": {
    "babel-cli": "^6.24.1",
    "express": "^4.15.3",
    "react": "^15.5.4",
    "react-dom": "^15.5.4"
  },
  "devDependencies": {
    "babel-loader": "^7.0.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "nodemon": "^1.11.0",
    "react-hot-loader": "^1.3.1",
    "webpack": "^2.6.1",
    "webpack-dev-middleware": "^1.10.2",
    "webpack-hot-middleware": "^2.18.0"
  }
}

.babelrc

:这是一个用于配置Babel的文件。
{
  "presets": [ "es2015", "react" ]
}

谢谢。


你的 client/index.js 怎么样了? - enapupe
很可能你缺少JSX支持。 - enapupe
3
bundle.js 包含 index.html 文件的代码。 - Stefan Hansch
1
是的,我知道了。我现在使用Google Chrome的开发工具进行了检查,在“源”选项卡中打开bundle.js文件,发现我的index.html文件中有一行代码(<html>)显示错误-未预期的标记。 - Stefan Hansch
你必须分享它的内容,否则帮助起来不容易。我们还需要看到你的 Babel 配置文件。 - enapupe
显示剩余4条评论
9个回答

21

你的 script 标签中的 bundle.js 路径是错误的。它返回的是你的主 index.html 文件,这就是为什么你会收到那个错误——JS解析器试图解析一个HTML文件。

你必须在你的脚本路径中添加一个斜杠: <script src="/bundle.js"></script>

如果这样还不行,你必须仔细检查你的 output 配置。


我有同样的问题,而且我认为你指出了正确的方向。我已经在 HTML 文件中双重检查了脚本标记:<script type="text/javascript" src="/bundle.js"></script>。正如你所看到的,一切都看起来很好。我想知道如果我配置 webpack 将 bundle 放入“public”文件夹,那么 publicPath 应该包含什么值?目前我的设置是 publicPath: '/' - SuperManEver
@SuperManEver,你应该打开一个新的问题并分享你的webpack配置等内容。 - enapupe

1
在Webpack版本5.46.0和Node 14.x中,有一种可能的解决方法。我希望发布这篇文章来帮助其他人,以防他们遇到相同的问题并且还没有找到解决方法。因此,除了其他问题之外,一个可能性是,如果您正在使用html-webpack-plugin,则需要在属性中显式设置publicPath属性,而在旧版webpack < 5的插件中不需要这样做,因为它应该从output/devServer继承该属性。添加属性到插件后,最新的html-webpack-plugin可以在webpack 5中正常工作。
以下是相关配置。
module.exports = {
  mode: 'development',
entry: ['@babel/polyfill', './config/polyfills', './src/index.js'],
  output: {
    hotUpdateMainFilename: '[id].hot-update.[fullhash].json',
    hotUpdateChunkFilename: '[id].hot-update.[fullhash].js',
    path: resolve(__dirname, '..', 'dist'),
    filename: '[name].[fullhash].js',
  },
  optimization: {
    moduleIds: 'named',
  },
  devtool: 'eval-cheap-module-source-map',
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      hash: true,
      publicPath: '/yourPath',
      template: resolve(__dirname, '..', 'src', 'index.html'),
      alwaysWriteToDisk: true,
    }),
    new HtmlWebpackHarddiskPlugin({
      outputPath: resolve(__dirname, '..', 'dist'),
    }),
  ],
};

1
我最终在index.html中明确指定了bundle.js文件的路径:
从: <script src="bundle.js"></script> 到: <script src="public/bundle.js"></script>

1

如果需要的话,经过长时间的考虑,您只需要在<head>标签内添加<base href="/" />到您的index.html文件中。请参考此评论


0
解决方案:使用中间件“app.use(express.static('./'));”来提供静态资源文件'bundle.js'的位置。 包含此修复程序的server/index.js的简化版本如下:
import express from 'express';
import path from 'path';
const __dirname = path.resolve();

let app = express();

app.use(express.static('./'));

app.get('/*', (req, res)=>{
    res.sendFile(path.join(__dirname, './index.html'));
});

app.listen('3000', ()=>{console.log('Running on port 3000')});

我能够重现这个问题。我已经使用你提供的文件和目录结构测试了修复程序。然而,我禁用了Babel并注释掉了与Webpack相关的内容。


0
在我的情况下,主页:<path> 出现了问题。

package.json

{
    "homepage":  '<path>',  // removed this 
    .....
}
  

0

抱歉,如何设置输出?我添加了输出:{ path: '/' publicPath: '/' } - Stefan Hansch
尝试将文件名添加到输出中:{ path: '/' publicPath: '/' filename: 'bundle.js' },并检查是否按照enapupe在评论中所说正确设置了路径路由。另外,为什么需要将'webpack-hot-middleware/client'作为入口点? - Tuko90
嗯...是的,我添加了文件名:'bundle.js',现在可以工作了。我需要webpack-hot-middleware/client来在浏览器上更改数据而无需重新加载页面。 - Stefan Hansch

0

没有任何建议对我起作用。

当我尝试在我的index.html文件中添加<base href="/" />时,错误会在控制台中显示两次。

最后,这个对我有效

我从浏览器的URL中删除了/<username>/<app-name>部分,而是只使用:

http://localhost:3000/

这让错误消失了。
不过,我不确定这是怎么做到的。

-1

我通过向对象输出添加filename项来解决了这个问题:

output: {
 path: '/',
 filename: 'bundle.js'
},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接