找不到/src/bundle.js与webpack应用程序做出反应

时间:2017-02-05 09:12:53

标签: node.js reactjs webpack

以下是我的server.js文件:

import path from 'path';
import express from 'express';
import webpack from 'webpack';
import middleware from './src/middleware';

const app = express();
var port     = process.env.PORT || 8080;

if(process.env.NODE_ENV === 'development') {
const config = require('./webpack.config.dev');
const compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true,
    publicPath: config.output.publicPath,
    stats: {
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
    }
}));
//app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'src')));
} else if(process.env.NODE_ENV === 'production') {
app.use(express.static(path.resolve(__dirname, 'dist')));
}

app.get('*', middleware);

app.listen(port, '0.0.0.0', (err) => {
if(err) {
    console.error(err);
} else {
    console.info(path.resolve(__dirname, 'src'));
    console.info('Listening at '+port);
}
});

我的webpack.config.dev.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
entry: './src/middleware.js',
output: {
path       : path.resolve('./src'), // always use absolute paths
filename   : 'bundle.js',
publicPath : '/assets/'
},
plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('development')
        }
    })
],
module: {
    loaders: [
        {
            test: /\.css$/,
            loader: 'style-loader'
        }, {
            test: /\.css$/,
            loader: 'css-loader',
            include: path.join(__dirname, 'node_modules'),
            query: {
                modules: true,
                localIdentName: '[name]__[local]___[hash:base64:5]'
            }
        },
        {
            test: /\.js$/,
            loader: 'babel',
            include: path.resolve(__dirname, 'src'),
            query: {
                presets: [ 'react-hmre' ]
            }
        },
        { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }
    ]
  }
};

这是我的中间件:

import React from 'react';
import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { match, RouterContext } from 'react-router';
import reducers from './reducers';
import routes from './routes';

export default (req, res) => {
match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    if(error) {
        res.status(500).send(error.message);
    } else if(redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    } else if(renderProps) {
        res.status(200).send(`
            <!DOCTYPE html>
            <html>
            <head>
            <title>Req Management</title>
            <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">
            </head>
            <body>
            <script src='/src/bundle.js'></script>
            <div id='app'>${renderToString(
                <Provider store={createStore(reducers)}>
                <RouterContext {...renderProps} />
                </Provider>
            )}</div>
            </body>
            </html>
            `);
        } else {
            console.log("inside else");
            res.status(404).send('Not found');
        }
    });
};

这是我的package.json:

{
"name": "universal-boilerplate",
"version": "1.4.0",
"description": "Universal/isomorphic boilerplate with react, redux, webpack and express",
"main": "src/index.js",
"scripts": {
"lint": "eslint ./src",
"start": "npm run build && cross-env NODE_ENV=development babel-node ./server.js",
"build": "webpack --config ./webpack.config.dev.js",
"serve": "cross-env NODE_ENV=production babel-node ./server.js"
},
"author": "",
"license": "",
"devDependencies": {
"babel-cli": "^6.10.1",
"babel-core": "^6.22.1",
"babel-eslint": "^6.1.2",
"babel-loader": "^6.2.10",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.5.0",
"copy-webpack-plugin": "^3.0.1",
"cross-env": "^2.0.0",
"eslint": "^3.1.1",
"eslint-plugin-babel": "^3.3.0",
"eslint-plugin-react": "^5.2.2",
"express": "^4.14.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-redux": "^4.4.5",
"react-router": "^2.6.1",
"react-router-redux": "^4.0.5",
"redux": "^3.5.2",
"rimraf": "^2.5.4",
"webpack": "^1.13.1",
"webpack-dev-middleware": "^1.6.1",
"webpack-hot-middleware": "^2.12.2"
},
"repository": {
"type": "",
"url": ""
},
"dependencies": {
"axios": "^0.13.1",
"babel": "^6.5.2",
"babel-cli": "^6.10.1",
"babel-core": "^6.10.4",
"babel-eslint": "^6.1.2",
"babel-loader": "^6.2.4",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.11.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.5.0",
"copy-webpack-plugin": "^3.0.1",
"cross-env": "^2.0.0",
"eslint": "^3.1.1",
"eslint-plugin-babel": "^3.3.0",
"eslint-plugin-react": "^5.2.2",
"express": "^4.14.0",
"fixed-data-table": "^0.6.3",
"querystring": "^0.2.0",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"react-dropdown": "^1.2.0",
"react-input-autosize": "^1.1.0",
"react-redux": "^4.4.5",
"react-router": "^2.6.1",
"react-router-redux": "^4.0.5",
"react-select": "^1.0.0-rc.3",
"redux": "^3.5.2",
"redux-logger": "^2.6.1",
"redux-thunk": "^2.1.0",
"rimraf": "^2.5.4",
"style-loader": "^0.13.1",
"webpack": "^1.14.0",
"webpack-dev-middleware": "^1.6.1",
"webpack-hot-middleware": "^2.12.2"
}
}

这是我的index.js:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import reducers from './reducers';
import routes from './routes';
import { applyMiddleware, createStore } from "redux"
import logger from "redux-logger"
import thunk from "redux-thunk"

const middleware = applyMiddleware(thunk, logger());

const store = createStore(reducers, middleware);
const history = syncHistoryWithStore(browserHistory, store);

render(
<Provider store={store}>
    <Router history={history} store={store}>
        { routes }
    </Router>
</Provider>,
document.getElementById('app')
);

if(process.env.NODE_ENV == 'development' && module.hot) {
module.hot.accept('./reducers', () => {
    store.replaceReducer(require('./reducers').default);
});
}

我试图将此代码部署到Heroku。在webpack.config.dev.js文件中做了一些更改。无法恢复。在代码在本地工作正常之前。现在也不在当地工作。

Folder structure is shown below:

2 个答案:

答案 0 :(得分:1)

这可能是由于:

造成的
app.use(express.static(path.resolve(__dirname, 'src')));

这使src/成为静态资源的根;换句话说,/SOME.FILE被查找为src/SOME.FILE。将其扩展到您的网址/src/bundle.js,它会被查询为src/src/bundle.js,这显然是不正确的。

有一些解决方案:

  • 在HTML
  • 中使用/bundle.js代替/src/bundle.js
  • 使用/src

    作为静态中间件的路径的前缀
    app.use('/src', express.static(path.resolve(__dirname, 'src')));
    

我认为后者更可取。

答案 1 :(得分:0)

关于您的代码无法在本地运行的原因。可能是因为你有拼写错误。您正在检查:

if(process.env.NODE_ENV === 'develospment') {

大概你的意思是'发展'......