Node JS and Webpack Unexpected token <

前端 未结 5 829
旧巷少年郎
旧巷少年郎 2020-12-01 05:41

I\'ve started studing Node JS.

So here is my files.

index.html





        
相关标签:
5条回答
  • 2020-12-01 06:01

    Your server:

    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.

    So when the browser requests /assets/bundle.js it is given index.html (and errors because that isn't 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).

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

    0 讨论(0)
  • 2020-12-01 06:11

    You need to serve all kinds of static files, e.g. 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)
    
    0 讨论(0)
  • 2020-12-01 06:13

    No matter what is requested by the browser, your server will always return the same exact file: 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.

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

    0 讨论(0)
  • 2020-12-01 06:13

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

    0 讨论(0)
  • 2020-12-01 06:17

    Express Users :

    Let the Node server know the location of your static files

    Notice this line >> 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

    Good Luck.

    0 讨论(0)
提交回复
热议问题