【问题标题】:bundle.js not found with webpackwebpack 找不到 bundle.js
【发布时间】:2017-10-08 23:21:43
【问题描述】:

学习使用 webpack 设置 MERN 堆栈项目。在运行 webpack 以捆绑所有内容并启动 express 服务器后,我看到 bundle.js 未找到,并且在控制台中看到 localhost:3000/bundle.js 404 状态代码。也许我的路径不正确或者我遗漏了什么

包.json

{
  "name": "mern_tut",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "express": "^4.16.1",
    "react": "^16.0.0",
    "react-dom": "^16.0.0",
    "webpack": "^3.6.0"
  }
}

webpack.config.js

const path = require('path');
module.exports = {
  entry: './static/app.js',
  output: {
    path: path.resolve('dist'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },


    ]

  }
}

.babelrc

{
    "presets":[
        "es2015", "react"
    ]
}

server.js

var express = require('express')

var app = express();

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

var server = app.listen(3000, function() {
    var port = server.address().port;
    console.log("Started server at port", port);
});

项目设置

 - dist
    -bundle.js
- node_modules
- static
   -app.js
   -index.html
- .babelrc
- package.json
- server.js
- webpack.config.js

【问题讨论】:

    标签: javascript node.js express webpack


    【解决方案1】:

    您没有在此处提供您的 bundle.js。将以下内容添加到您的 server.js

    app.use(express.static('dist')) 
    

    【讨论】:

    • 谢谢,我试过了,现在我收到一条错误消息“Cannot GET /”
    • 请添加路线。 app.get('/', function (request, response){ response.sendFile(path.resolve(__dirname, 'static', 'index.html')) })
    • 谢谢!使用 'dist' 而不是 static 并在我的索引中修复不正确的 bundle.js 路径。
    【解决方案2】:

    这是我在项目中使用的解决方案

    // server.js
    const express = require('express')
    const path = require('path')
    
    const app = express()
    
    // serve our static stuff like index.css
    app.use(express.static(path.join(__dirname, 'dist')))
    
    // send all requests to index.html so browserHistory in React Router works
    app.get('*', function (req, res) {
      res.sendFile(path.join(__dirname, 'dist', 'index.html'))
    })
    
    const port = process.env.PORT || 3000
    app.listen(port,() => {
       console.log(`App started on port: ${port}`);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2016-04-02
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多