gpt4 book ai didi

javascript - 使用 webpack 将 react 和 react-router 导出到独立的 html 文件时,应用程序不运行

转载 作者:行者123 更新时间:2023-12-04 19:43:15 27 4
gpt4 key购买 nike

我正在尝试导出我的 react SPA到一个htmljs所以我可以将它安装到 phonegap 中申请。

我的产品 webpack.config 已“准备就绪”,但是当我导出文件时,所有内容都捆绑在一起并且看起来没问题。但是应用程序在到达 Provider 时停止.

入口点 - src/client/js/Entry.js

这是入口点

import React, { Component, PropTypes } from 'react'
import {render} from 'react-dom';
import { Router, browserHistory, Route, IndexRoute } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux'

import Root from './core/Provider'
import configureStore from './core/Store'

const store = configureStore;
const history = syncHistoryWithStore(browserHistory, store)

console.info('Entry') //OUTPUTS correctly
render(
<Root store={store} history={history} />,
document.getElementById('app')
)

我可以确认 <div id="app"></div>在页面加载时。

Provider.js

import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute } from 'react-router'

import App from './App';
//###### Routes #######
import Splash from '../components/pages/Splash';

export default class Root extends Component {
render() {
console.info('Provider'); //Provider Correct
const { store, history } = this.props;
return (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Splash}/>

</Route>
</Router>
</Provider>
)
}
}

Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}

App.js

import React, { Component, PropTypes } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as ActionCreator from '../actions/ActionCreator';

import { browserHistory } from 'react-router'

class App extends Component {

constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
}

handleChange(nextValue) {
browserHistory.push(`/${nextValue}`)
}

render() {
console.info('App'); //No console log, does not render
return (
<div>
{this.props.children}
</div>
)
}
}

App.propTypes = {
// Injected by React Router
children: PropTypes.node
}

function mapStateToProps(state, ownProps) {
return {
errorMessage: state.errorMessage,
inputValue: ownProps.location.pathname.substring(1)
}
}
function mapDispatchToProps(dispatch) {
return {
SexAction: bindActionCreators(ActionCreator, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)

当应用程序正常运行时我期望的结果

What I expect when the application is running correctly

我在独立应用程序中看到的内容

What I am seeing with the stand alone app

Store.js

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import createLogger from 'redux-logger'
import rootReducer from './Reducers'
import defaultStates from '../states/statesDefault'

const configureStore = function (preloadedState) {
const Store = createStore(
rootReducer,
preloadedState,
compose(
applyMiddleware(thunk, createLogger())
)
)

if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./Reducers', () => {
const nextRootReducer = require('../../js/Entry').default;
Store.replaceReducer(nextRootReducer)
})
}

return Store;
};

export default configureStore(defaultStates);

Webpack.prod.js

.......   
module.exports = {
devtool: 'cheap-module-source-map',
entry: [
path.join(__dirname, 'src/client/js/Entry')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name]-[hash].min.js',
publicPath: './'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
new ExtractTextPlugin('[name]-[hash].min.css'),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false,
screw_ie8: true
}
}),
new StatsPlugin('webpack.stats.json', {
source: false,
modules: false
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel?presets[]=react,presets[]=es2015,presets[]=stage-0'],
include: __dirname
}
......
};

一切都正确导出

Output of dist folder

[编辑] - Node.js 和 Express

我意识到我无疑错过了一个关键信息。我正在使用节点和 express 。我用 npm start 启动我的应用程序

const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config.js');

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 6004 : process.env.PORT;
const app = express();


app.use(express.static(__dirname + '/public/'));

const compiler = webpack(config);
const middleware = webpackMiddleware(compiler, {
publicPath: config.output.publicPath,
contentBase: 'public',
stats: {
colors: true,
hash: false,
timings: true,
chunks: false,
chunkModules: false,
modules: false
}
});

app.use(middleware);
app.use(webpackHotMiddleware(compiler));
app.get('*', function response(req, res) {
res.write(middleware.fileSystem.readFileSync(path.join(__dirname, 'public/index.html')));
res.end();
});

app.listen(port, '0.0.0.0', function onStart(err) {
if (err) {
console.log(err);
}
console.info('==> 🌎 Listening on port %s. Open up http://0.0.0.0:%s/ in your browser.', port, port);
});

最佳答案

我们在聊天中发现问题是 HTML 5 历史记录 API 与 file:// url 不兼容(至少在 Chrome 中是这样)。 react-router 提供的 browserHistory 是一个包装器。但是,对于 file:// URL,您可以改用 hashHistory:

import { Router, hashHistory, Route, IndexRoute  } from 'react-router';

// ...

render(
<Root store={store} history={hashHistory} />,
document.getElementById('app')
)

关于javascript - 使用 webpack 将 react 和 react-router 导出到独立的 html 文件时,应用程序不运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39592712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com