我已经使用react router和webpack将代码分割为shared.js,bundle.min.js和1.chunk.js,其中包含getComponents和require.ensure api的页面,例如" / about&#34 ;,来自" /"因为我想提高主页的初始加载时间。如果我将index.html和那些js放入名为public的单个文件夹并在html中声明脚本shared.js,bundle.min.js,它在开发设置中运行良好。
我想知道如果我打算在CDN上部署所有javascript文件(例如cloudfront),javascript如何加载正确的块。我可以简单地将CDN url放在html中,用于bundle.min.js和shared.js,因为这些都是任何页面都需要的。但是,如果需要,我怎么能让它知道1.chunk.js CDN网址?在html中是否存在捆绑文件名和实际URL(如CDN url)之间的声明性映射?否则我不知道如何加载1.chunk.js。
基本上我的服务器回复index.html请求所有网址,例如example.com或example.com/about。反应路由器会处理其他所有事情。
我的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()
]
}
答案 0 :(得分:2)
output.publicPath
将完成这项工作。
最终配置将成为
module.exports = {
.....,
output: {
path: './dist',
filename: 'bundle.min.js',
chunkFilename: '[id].chunk.js',
publicPath: "http://xxxxCDN.net/"
},
.....
}
参考:https://webpack.github.io/docs/configuration.html#output-publicpath