Javascript Node JS 和 Webpack Unexpected token <

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33260093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:52:05  来源:igfitidea点击:

Node JS and Webpack Unexpected token <

javascriptnode.jswebpack

提问by

I've started studing Node JS.

我已经开始研究Node JS

So here is my files.

所以这是我的文件。

index.html

索引.html

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div id="app">
    <h1>Hello<h1>
  </div>
  <script src='assets/bundle.js'></script>
</body>
</html>

app.js

应用程序.js

var http = require("http"),
    path = require('path')
    fs = require("fs"),
    colors = require('colors'),
    port = 3000;

var Server = http.createServer(function(request, response) {
  var filename = path.join(__dirname, 'index.html');

  fs.readFile(filename, function(err, file) {
    if(err) {        
      response.writeHead(500, {"Content-Type": "text/plain"});
      response.write(err + "\n");
      response.end();
      return;
    }

    response.writeHead(200);
    response.write(file);
    response.end();
  });
});

Server.listen(port, function() {
  console.log(('Server is running on http://localhost:'+ port + '...').cyan);

webpack.config.js

webpack.config.js

module.exports = {
    entry: './src/index.js',
    output: {
        path: __dirname + '/assets',
        filename: 'bundle.js'
    }
}

UPDATEbundle.js

更新bundle.js

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

    alert('Hello');

/***/ }
/******/ ]);

So, when i hit a app.jsand visit the address (localhost:3000) i get the error in console.

因此,当我点击app.js并访问地址 (localhost:3000) 时,我在控制台中收到错误消息。

bundle.js:1 Uncaught SyntaxError: Unexpected token <

bundle.js:1 Uncaught SyntaxError: Unexpected token <

Also my JS file doesnt run. Could someone suggest something to fix it?

我的 JS 文件也没有运行。有人可以建议一些东西来解决它吗?

Thanks in advance

提前致谢

采纳答案by Quentin

Your server:

您的服务器:

var Server = http.createServer(function(request, response) {
  var filename = path.join(__dirname, 'index.html');
var Server = http.createServer(function(request, response) {
  var filename = path.join(__dirname, 'index.html');

… is configured to ignore everything in the request and always return the contents of index.html.

... 配置为忽略请求中的所有内容并始终返回index.html.

So when the browser requests /assets/bundle.jsit is given index.html(and errors because that isn't JavaScript).

因此,当浏览器请求时,/assets/bundle.js它会给出index.html(并且会出现错误,因为那不是 JavaScript)。

You need to pay attention to the path and serve up appropriate content, with the appropriate content type.

您需要注意路径并以适当的内容类型提供适当的内容。

This would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).

这可能最好通过为 Node找到一个静态文件服务模块(Google 出现node-static)(或用 Lighttpd 或 Apache HTTPD 之类的东西替换 Node)来完成。

If you want to serve up dynamic content as well as static content, then Expressis a popular choice (and has support for static files).

如果您想同时提供动态内容和静态内容,那么Express是一种流行的选择(并且支持静态文件)。

回答by Dmytro Shevchenko

No matter what is requested by the browser, your server will always return the same exact file: index.html.

无论浏览器请求什么,您的服务器将始终返回完全相同的文件:index.html.

The error you are seeing is because your HTML file has a reference to bundle.js, which, when requested, is returned with the contents of index.html.

您看到的错误是因为您的 HTML 文件有对 的引用bundle.js,当请求时,该引用与 的内容一起返回index.html

You should use a web framework so that you don't have to worry about these things. E.g. Express.

您应该使用 Web 框架,这样您就不必担心这些事情。例如快递

回答by Akash

Express Users :

快递用户:

Let the Node server know the locationof your static files

让 Node 服务器知道你的静态文件位置

Notice this line >> app.use(express.static('public'))

注意这一行>> app.use(express.static('public'))

//server.js
const express = require('express')
const app = express()
// serve static assets from the public folder in project root
app.use(express.static('public')) 
//
app.listen(8080, () => console.log('listening...'))

DOCS- https://expressjs.com/en/starter/static-files.html

文档- https://expressjs.com/en/starter/static-files.html

Good Luck.

祝你好运。

回答by Mat Watershed

Simply add output: {publicPath: '/',}in your webpack.config.jsfile.

只需添加output: {publicPath: '/',}您的webpack.config.js文件。

回答by Dominic

You need to serve all kinds of static files, e.g. https://github.com/expressjs/serve-static#serve-files-with-vanilla-nodejs-http-server

您需要提供各种静态文件,例如https://github.com/expressjs/serve-static#serve-files-with-vanilla-nodejs-http-server

var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic(__dirname)

// Create server
var server = http.createServer(function(req, res){
  var done = finalhandler(req, res)
  serve(req, res, done)
})

// Listen
server.listen(process.ENV.port || 3000)