【发布时间】:2019-07-24 17:39:12
【问题描述】:
已经有其他类似的问题了,但是尽管有这些答案,这个问题仍然困扰着我——我在一个项目中使用 webpack 和 babel,但是浏览器的控制台在尝试查找 bundle.js 时总是显示错误 404 .
这是我的 package.json:
{
"name": "node-str",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./bin/server.js"
},
"keywords": [],
"author": "Pedro_Coelho",
"license": "ISC",
"dependencies": {
"babel-register": "^6.26.0",
"body-parser": "^1.18.3",
"create-react-class": "^15.6.3",
"debug": "^3.1.0",
"ejs": "^2.6.1",
"express": "^4.16.3",
"guid": "0.0.12",
"http": "0.0.0",
"md5": "^2.2.1",
"mongoose": "^5.2.4",
"react": "^16.6.1",
"react-dom": "^16.6.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"nodemon": "^1.18.3",
"webpack-cli": "^3.1.2"
}
}
这是我的 webpack.config.js:
module.exports = {
entry: 'src/client.js',
output: {
filename:'bundle.js',
//path: './public',
path:__dirname + 'dist',
publicPath: "./public"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
cacheDirectory: true,
presets: ['react', 'es2015']
}
}
]
},
//devtool: 'source-map',
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: { historyApiFallback: true }, // to serve your index.html in place of 404 responses
};
这是我的 about.js 文件,其中 bundle.js 在脚本中被引用:
var React = require('react');
var createReactClass = require('create-react-class');
module.exports = createReactClass({
_handleClick: function () {
alert("Hello!");
},
render: function () {
return (
<html>
<head>
<title>About - React Page</title>
<link rel='stylesheet' type="text/css" href='/style.css' />
</head>
<body>
<div>
<h1>Hello World!</h1>
<p>Isn't server-side rendering remarkable?</p>
<button onClick={this._handleClick}>Click Me</button>
</div>
<script type="text/javascript" src='/bundle.js' />
</body>
</html>
);
}
});
项目结构:
任何线索为什么会发生这种情况?
【问题讨论】:
-
"node ./bin/server.js"那么那个文件里有什么?或者在任何您实际在端口 3000 上运行“服务器”的情况下。请注意,bundle.js正在被 webpack 输出到dist/bundle.js,而且这不太可能在服务器根/的相对路径位置上。就我个人而言,我不会“服务器端渲染”根上下文,而只会在更改路线内做事。'index.html'实际上应该是静态内容作为最佳实践。 -
你应该尝试在你的 webpack bundle js 配置中使用
path:__dirname + '/dist',。
标签: javascript node.js reactjs webpack babeljs