我正在努力让Angular 2+Webpack正常工作,我几乎做到了:)
我需要解决的最后一个问题是:
当浏览子路由(例如/childreout/main)时,只要我使用路由器链接,一切都能正常工作
当手动输入地址或重新加载时,我会得到一个404,其中包含错误的束路径。。它应该是localhost:5001/dist/bundle.js,但webpack尝试获取localhost:5001/childreoute/dist/bundle.js。在webpack中更改我的publicPath不起作用:(
这是我的webpack配置:
"use strict";
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
"app": "./wwwroot/app/base/boot",
"vendor": "./wwwroot/app/base/vendors"
},
devtool: 'source-map',
output: {
filename: "bundle.js",
chunkFilename: "[id]chunk.js",
path: "./wwwroot/dist/",
publicPath: "./dist/"
},
//devServer: {
// contentBase: "./wwwroot/",
// host: "localhost",
// port: 50001,
// inline:true
//},
resolve: {
extensions: ['','.js','.ts']
},
module: {
loaders: [
//Typescript
{
test: /.ts$/,
loader: 'ts-loader',
exclude: '/node_modules/'
},
// SASS
{
test: /.scss$/,
loaders: ['style','css','sass'],
exclude: '/node_modules/'
},
// Fonts & Files
{
test: /.(ttf|eot|txt|svg|woff(2)?)(?[a-z0-9=&.]+)?$/,
loader: 'file-loader' ,
exclude: '/node_modules/'
}
]
},
plugins: [
//new webpack.optimize.UglifyJsPlugin({
// compressor: {
// warnings: false
// }
//}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new webpack.optimize.CommonsChunkPlugin("vendor","vendor_bundle.js")
]
};
我希望有人能给我一个提示:)
谢谢大家!
编辑:如果我将index.html中的脚本路径从"dist/bundle.js"更改为"/dist/bundle.js",我会加载脚本,但angular找不到我的模板。。。模板路径中的附加"/childreoute/"出现相同错误。。
如果在index.html中添加一个基本标记,则所有资源都是相对于基本路径加载的,而不是相对于当前路由加载的。
<head>
<base href="/">
</head>
这是一个常见的问题,因为这些请求首先在您的后端(apache,nginx..)上处理,而您的后端服务器可能没有配置为处理这些请求。解决方案是将后端配置为对/childreout/main的请求提供index.html,或者更好的是,对所有请求返回index.html。
这样,当访问/childreout/main时,您的后端仍将为您的react应用程序提供服务,然后由它负责路由。
或者您可以使用HashLocationStrategy
bootstrap(MyApp,[..., provide(LocationStrategy, {useClass: HashLocationStrategy})])
不太像PathLocationStrategy,但您不需要服务器支持。