【发布时间】:2016-03-02 17:04:24
【问题描述】:
我使用 react router 和 webpack 将代码拆分为 shared.js、bundle.min.js 和 1.chunk.js,并使用 getComponents 和 require.ensure api 用于页面,例如“/about”,来自“/ " 因为我想增加主页的初始加载时间。如果我将 index.html 和那些 js 放入名为 public 的单个文件夹中并在 html 中声明脚本 shared.js、bundle.min.js,那么它在开发环境中运行良好。
我想知道如果我打算将所有 javascript 文件部署在 CDN(如 cloudfront)上,javascript 怎么可能加载正确的块。我可以简单地将 CDN url 放入 bundle.min.js 和 shared.js 的 html 中,因为这些对于任何页面都是必需的。但是,当它需要 1.chunk.js CDN url 时,我怎么能让它知道呢? html中捆绑的文件名和实际url(如CDN url)之间是否存在声明性映射?否则我看不到它如何加载 1.chunk.js。
基本上,我的服务器会为所有请求的 URL 回复 index.html,例如 example.com 或 example.com/about。 React 路由器会处理其他所有事情。
我的html代码是这样的:
<html>
<body>
<div id="container"></div>
<script src="http://xxxxCDN.net/common.js"></script>
<script src="http://xxxxCDN.net/bundle.min.js"></script>
</body>
</html>
我的路由文件是:
import Router, {Route, IndexRoute} from "react-router"
import React from 'react';
import App from "../components/App"
import HomePage from "../components/pages/HomePage"
import LoginPage from "../components/pages/LoginPage"
import SignupPage from "../components/pages/SignupPage"
//import AboutPage from "../components/pages/AboutPage"
import GuidePage from "../components/pages/GuidePage"
import SearchPage from '../components/pages/SearchPage'
import ProfilePage from '../components/pages/ProfilePage'
import HomeDetailPage from '../components/pages/HomeDetailPage'
import OrderDetailPage from "../components/pages/OrderDetailPage"
const routes = <Route path='/' component={App}>
<IndexRoute component={HomePage}/>
<Route path="login" component={LoginPage}/>
<Route path="signup" component={SignupPage}/>
<Route path="search" component={SearchPage}/>
<Route path="guide" component={GuidePage}/>
<Route path="about" getComponent={(location, cb) => {
require.ensure([], (require) => {
cb(null, require('../components/pages/AboutPage'))
})
}}/>
<Route path="profile" component={ProfilePage}/>
<Route path="home" component={HomeDetailPage}/>
<Route path="order" component={OrderDetailPage}/>
</Route>;
export default routes;
和用于部署的 webpack 配置文件:
var webpack = require('webpack');
module.exports = {
entry: [
'./src/app.jsx'
],
output: {
path: './dist',
filename: 'bundle.min.js',
chunkFilename: '[id].chunk.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify("production")
}
}),
new webpack.optimize.UglifyJsPlugin()
]
}
【问题讨论】:
标签: javascript node.js reactjs webpack react-router