【发布时间】:2016-10-26 18:58:18
【问题描述】:
我是 Reactjs 和 webpack 的新手。我正在尝试使用 Node 和 React 做一个示例应用程序。我选择了 Webpack 作为模块打包器。 这是我的项目结构
Project
|--index.html
|--package.json
|--server.js
|--webpack.config.js
|--app/main.js
|--app/routes.js
|--app/components/login.js
webpack.config.js
module.exports = {
entry: "./app/main.js",
output: {
sourceMapFilename: "build/bundle.js.map",
filename: "build/bundle.js"
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.png$/,
loader: "url-loader?limit=100000"
}]
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>New Eden Faces</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,900"/>
</head>
<body>
<div id="app">{{ html|safe }}</div>
<script type="text/javascript" src="build/bundle.js"></script>
</body>
</html>
在我的 server.js 中,我添加了一个中间件
app.use(function(req, res) {
Router.match({ routes: routes.default, location: req.url }, function(err, redirectLocation, renderProps) {
if (err) {
res.status(500).send(err.message)
} else if (redirectLocation) {
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
var html = ReactDOM.renderToString(React.createElement(Router.RoutingContext, renderProps));
var page = swig.renderFile("./index.html", {html:html});
res.status(200).send(page);
} else {
res.status(404).send('Page Not Found')
}
});
});
Webpack 在我的根目录下生成 build/build.js(与 server.js 和 index.html 平行)
当我运行节点服务器并尝试根据 routes.js 中配置的路由获取 http://localhost:3007/login 时,我的登录组件会被渲染。
这是我的项目/app/components/login.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Button} from 'react-bootstrap';
class Login extends React.Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-sm-5">
<strong>Username</strong>
</div>
<div className="col-sm-5 form-control">
<input type='text' className='form-control'/>
</div>
<Button bsSize="large">Hi</Button>
</div>
</div>
)
}
}
export default Login;
这是我输出的图像快照。
It is not loading my bundle.js why?
我可以看到它是在我的项目 build 目录下生成的。为什么不加载任何CSS?即使我使用了 react-bootstrap 中的 Button?为什么没有应用 css 类。 Webpack 也应该捆绑依赖的 css 文件,对吗?
几天以来一直坚持这一点,但没有找到任何东西。任何帮助都会非常棒。我希望我很清楚,并提前感谢。
【问题讨论】:
-
您是否告诉您的节点服务器在任何地方使用构建目录作为静态资源位置?
-
我已经做到了。还是不行。
标签: javascript node.js reactjs webpack