我在前面使用 Angular 5 ,在后面使用 Java 和 Apache 。当您使用 PathLocationStrategy 来摆脱 /#/ 角度时,当用户转到除root用户以外的其他页面时,我在这里已经阅读了很多关于404页的内容路由。
我想摆脱这个#,因为它对Google Analytics(分析)不利,对我来说也不是很漂亮。过了一会儿,我设法做到了,但它只在本地有效。对我来说,本地的窍门是在我的webpack.dev.js中添加 historyApiFallback:true ,这一切都像 charm 一样。
现在的问题是,在生产环境中,唯一可行的方法是主要方法,其他方法均无效!我能做什么????我认为webpack.prod.js可能有用,但不确定是什么。
webpack.dev.js:
const webpack = require('webpack');
const writeFilePlugin = require('write-file-webpack-plugin');
const webpackMerge = require('webpack-merge');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const WebpackNotifierPlugin = require('webpack-notifier');
const path = require('path');
const utils = require('./utils.js');
const commonConfig = require('./webpack.common.js');
const ENV = 'development';
module.exports = webpackMerge(commonConfig({ env: ENV }), {
devtool: 'eval-source-map',
devServer: {
historyApiFallback: true,
contentBase: './build/www',
proxy: [{
context: [
/* jhipster-needle-add-entity-to-webpack - JHipster will add entity api paths here */
'/api',
'/management',
'/swagger-resources',
'/v2/api-docs',
'/h2-console',
'/auth'
],
target: 'http://127.0.0.1:8080',
secure: false
}],
watchOptions: {
ignored: /node_modules/
}
},
entry: {
polyfills: './src/main/webapp/app/polyfills',
global: './src/main/webapp/content/css/global.css',
main: './src/main/webapp/app/app.main'
},
output: {
path: utils.root('build/www'),
filename: 'app/[name].bundle.js',
chunkFilename: 'app/[id].chunk.js',
publicPath: '/'
},
module: {
rules: [{
test: /\.ts$/,
enforce: 'pre',
loaders: 'tslint-loader',
exclude: ['node_modules', new RegExp('reflect-metadata\\' + path.sep + 'Reflect\\.ts')]
},
{
test: /\.ts$/,
loaders: [
'angular2-template-loader',
'awesome-typescript-loader'
],
exclude: ['node_modules/generator-jhipster']
},
{
test: /\.css$/,
loaders: ['to-string-loader', 'css-loader'],
exclude: /(vendor\.css|global\.css)/
},
{
test: /(vendor\.css|global\.css)/,
loaders: ['style-loader', 'css-loader']
}]
},
plugins: [
new BrowserSyncPlugin({
host: 'localhost',
port: 9000,
proxy: {
target: 'http://localhost:9060'
}
}, {
reload: false
}),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.NamedModulesPlugin(),
new writeFilePlugin(),
new webpack.WatchIgnorePlugin([
utils.root('src/test'),
]),
new WebpackNotifierPlugin({
title: 'JHipster',
contentImage: path.join(__dirname, 'logo-jhipster.png')
})
]
});
这是 webpack.prod.js :
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const Visualizer = require('webpack-visualizer-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const WorkboxPlugin = require('workbox-webpack-plugin');
const AngularCompilerPlugin = require('@ngtools/webpack').AngularCompilerPlugin;
const path = require('path');
const utils = require('./utils.js');
const commonConfig = require('./webpack.common.js');
const ENV = 'production';
const extractCSS = new ExtractTextPlugin(`[name].[hash].css`);
module.exports = webpackMerge(commonConfig({ env: ENV }), {
// Enable source maps. Please note that this will slow down the build.
// You have to enable it in UglifyJSPlugin config below and in tsconfig-aot.json as well
devtool: 'source-map',
devServer: {
historyApiFallback: true,
contentBase: './build/www',
},
entry: {
polyfills: './src/main/webapp/app/polyfills',
global: './src/main/webapp/content/css/global.css',
main: './src/main/webapp/app/app.main'
},
output: {
path: utils.root('build/www'),
filename: 'app/[name].[hash].bundle.js',
chunkFilename: 'app/[id].[hash].chunk.js',
publicPath: '/',
},
module: {
rules: [{
test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
use: [ '@ngtools/webpack' ]
},
{
test: /\.css$/,
loaders: ['to-string-loader', 'css-loader'],
exclude: /(vendor\.css|global\.css)/
},
{
test: /(vendor\.css|global\.css)/,
use: extractCSS.extract({
fallback: 'style-loader',
use: ['css-loader']
})
}]
},
plugins: [
extractCSS,
new Visualizer({
// Webpack statistics in target folder
filename: '../stats.html'
}),
new UglifyJSPlugin({
parallel: true,
uglifyOptions: {
ie8: false,
// sourceMap: true, // Enable source maps. Please note that this will slow down the build
compress: {
dead_code: true,
warnings: false,
properties: true,
drop_debugger: true,
conditionals: true,
booleans: true,
loops: true,
unused: true,
toplevel: true,
if_return: true,
inline: true,
join_vars: true
},
output: {
comments: false,
beautify: false,
indent_level: 2
}
}
}),
new AngularCompilerPlugin({
mainPath: utils.root('src/main/webapp/app/app.main.ts'),
tsConfigPath: utils.root('tsconfig-aot.json'),
sourceMap: true
}),
new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false
}),
new WorkboxPlugin({
clientsClaim: true,
skipWaiting: true,
})
]
});
最后,以防万一 webpack.common.js :
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const rxPaths = require('rxjs/_esm5/path-mapping');
const MergeJsonWebpackPlugin = require("merge-jsons-webpack-plugin");
const utils = require('./utils.js');
module.exports = (options) => ({
resolve: {
extensions: ['.ts', '.js'],
modules: ['node_modules'],
alias: rxPaths()
},
stats: {
children: false
},
module: {
rules: [
{ test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },
{
test: /\.html$/,
loader: 'html-loader',
options: {
minimize: true,
caseSensitive: true,
removeAttributeQuotes:false,
minifyJS:false,
minifyCSS:false
},
exclude: ['./src/main/webapp/index.html']
},
{
test: /\.(jpe?g|png|gif|otf|svg|woff2?|ttf|eot)$/i,
loaders: ['file-loader?hash=sha512&digest=hex&name=content/[hash].[ext]']
},
{
test: /manifest.webapp$/,
loader: 'file-loader?name=manifest.webapp!web-app-manifest-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: `'${options.env}'`,
BUILD_TIMESTAMP: `'${new Date().getTime()}'`,
VERSION: `'${utils.parseVersion()}'`,
DEBUG_INFO_ENABLED: options.env === 'development',
// The root URL for API calls, ending with a '/' - for example: `"http://www.jhipster.tech:8081/myservice/"`.
// If this URL is left empty (""), then it will be relative to the current context.
// If you use an API server, in `prod` mode, you will need to enable CORS
// (see the `jhipster.cors` common JHipster property in the `application-*.yml` configurations)
SERVER_API_URL: `''`
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'polyfills',
chunks: ['polyfills']
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
chunks: ['main'],
minChunks: module => utils.isExternalLib(module)
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
}),
new webpack.optimize.CommonsChunkPlugin({
name: ['manifest'],
minChunks: Infinity,
}),
/**
* See: https://github.com/angular/angular/issues/11580
*/
new webpack.ContextReplacementPlugin(
/(.+)?angular(\\|\/)core(.+)?/,
utils.root('src/main/webapp/app'), {}
),
new CopyWebpackPlugin([
{ from: './node_modules/swagger-ui/dist/css', to: 'swagger-ui/dist/css' },
{ from: './node_modules/swagger-ui/dist/lib', to: 'swagger-ui/dist/lib' },
{ from: './node_modules/swagger-ui/dist/swagger-ui.min.js', to: 'swagger-ui/dist/swagger-ui.min.js' },
{ from: './src/main/webapp/swagger-ui/', to: 'swagger-ui' },
{ from: './src/main/webapp/favicon.ico', to: 'favicon.ico' },
{ from: './src/main/webapp/manifest.webapp', to: 'manifest.webapp' },
// jhipster-needle-add-assets-to-webpack - JHipster will add/remove third-party resources in this array
{ from: './src/main/webapp/robots.txt', to: 'robots.txt' }
]),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new MergeJsonWebpackPlugin({
output: {
groupBy: [
{ pattern: "./src/main/webapp/i18n/en/*.json", fileName: "./i18n/en.json" },
{ pattern: "./src/main/webapp/i18n/de/*.json", fileName: "./i18n/de.json" }
// jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
]
}
}),
new HtmlWebpackPlugin({
template: './src/main/webapp/index.html',
chunksSortMode: 'dependency',
inject: 'body'
})
]
});
我不确定我会丢失什么,有什么想法吗?我不完全相信webpack.prod上的historyApiFallback,但是我确实在几篇博文中看到了它,所以值得一试。
我检查了几篇文章,它实际上帮助我使它在Local上工作,但是关于这个问题,我没有发现任何有用的东西。
非常感谢:)
pathlocationstrategy-works-only-locally
implementing-history-api-fallback-for-webpack-production-environment
matching-root-route-in-webpack-dev-servers-historyapifallback