使用webpack时找不到bundle.js文件

3

学习如何使用Webpack来设置一个MERN堆栈项目。运行Webpack将所有文件打包后,启动Express服务器时,我发现bundle.js未找到,并且在控制台中看到了localhost:3000/bundle.js的404状态代码。也许我的路径不正确或我遗漏了某些内容。

Package.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
2个回答

2
你没有在这里提供bundle.js文件。请在server.js中添加以下内容。
app.use(express.static('dist')) 

谢谢,我尝试了那个方法,但现在出现了一个错误,显示“无法获取/”。 - the_islander
请添加路由。 app.get('/', function (request, response){ response.sendFile(path.resolve(__dirname, 'static', 'index.html')) }) - user-developer
谢谢!在我的索引中使用“dist”而不是静态文件,并修复了bundle.js的错误路径。 - the_islander

0

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

// 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}`);
});

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