无法访问我网站上的链接(复制和粘贴):Node.js - Express.js - Webpack - Vue.js - 历史模式
Unable to acess links (copying and pasting) whitin my Site : Node.js - Express.js - Webpack - Vue.js - historymode
我最近创建了一个基于 Node.js、Express.js 和 Vue.js 的网站,带有历史模式的路由器和 Webpack。
由于是单页应用程序,我安装了 express-history-api-fallback 并且到目前为止它工作得很好但是(总是有一个但是)由于某些原因我不理解某些 url,我得到一个白页和一些错误,例如:
Uncaught SyntaxError: Unexpected token '<' ------ manifest.61d5cd8248647cdb144a.js:1
Uncaught SyntaxError: Unexpected token '<' ------ vendor.db7271094dc9fcde8b9f.js:1
Uncaught SyntaxError: Unexpected token '<' ------ app.3cfe27cef1608de00b06.js:1
我不明白问题是在我的 webpack conf 文件中还是在我的 node.js 中(我想与前端有关,因为我在 be 中没有看到任何传入请求)或者在我的 vue-router 中。
我不明白(除了缺乏知识)的原因是,如果我尝试访问我的 Vue 应用程序中的页面,单击 link(即访问用户的个人资料页面格式为 mywebsiteinexample。com/user/userId) 它可以工作,但如果我刷新页面,我只能看到一个白页,并且在控制台内,我在上面写的错误。
我的文件的总体架构:
我猜这里有一些有用的代码:
Server.js
const express = require('express')
const fallback = require('express-history-api-fallback')
const path = require('path')
const historyModeHandlerHTTP = express()
const root = `${__dirname}/../`
historyModeHandlerHTTP.use(express.static(root))
historyModeHandlerHTTP.use(fallback(path.join(__dirname + '/../index.html')))
historyModeHandlerHTTP.listen(80, () => {
console.log('HTTP Server on')
})
Webpack.prod.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRootMain,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.ProgressPlugin(),
new CleanWebpackPlugin({
dry: false,
cleanOnceBeforeBuildPatterns: [config.build.assetsSubDirectory + '*/js/*', config.build.assetsSubDirectory + '*/css/*']
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
allChunks: true,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ?
{
safe: true,
map: {
inline: false
}
} :
{
safe: true
}
}),
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'template.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: false,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks(module) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
new CopyWebpackPlugin([{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
const config = require('../config')
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost',
port: 8080,
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false,
devtool: 'cheap-module-eval-source-map',
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../../index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsRootMain: path.resolve(__dirname, '../../'),
assetsSubDirectory: 'front-end/static',
assetsPublicPath: '',
mainfile : 'front-end/src/main.js',
routerfile : 'front-end/src/router/index.js',
constantsFile : 'utils-bf/constants.js',
productionSourceMap: true,
devtool: '#source-map',
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
}
}
[解决方案]
问题与Webpack的配置有关!
如果有人遇到同样的问题,只需设置 PublicPath : '/'
output: {
publicPath: '/',
path: config.build.assetsRootMain,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
我最近创建了一个基于 Node.js、Express.js 和 Vue.js 的网站,带有历史模式的路由器和 Webpack。 由于是单页应用程序,我安装了 express-history-api-fallback 并且到目前为止它工作得很好但是(总是有一个但是)由于某些原因我不理解某些 url,我得到一个白页和一些错误,例如:
Uncaught SyntaxError: Unexpected token '<' ------ manifest.61d5cd8248647cdb144a.js:1
Uncaught SyntaxError: Unexpected token '<' ------ vendor.db7271094dc9fcde8b9f.js:1
Uncaught SyntaxError: Unexpected token '<' ------ app.3cfe27cef1608de00b06.js:1
我不明白问题是在我的 webpack conf 文件中还是在我的 node.js 中(我想与前端有关,因为我在 be 中没有看到任何传入请求)或者在我的 vue-router 中。
我不明白(除了缺乏知识)的原因是,如果我尝试访问我的 Vue 应用程序中的页面,单击 link(即访问用户的个人资料页面格式为 mywebsiteinexample。com/user/userId) 它可以工作,但如果我刷新页面,我只能看到一个白页,并且在控制台内,我在上面写的错误。
我的文件的总体架构:
我猜这里有一些有用的代码:
Server.js
const express = require('express')
const fallback = require('express-history-api-fallback')
const path = require('path')
const historyModeHandlerHTTP = express()
const root = `${__dirname}/../`
historyModeHandlerHTTP.use(express.static(root))
historyModeHandlerHTTP.use(fallback(path.join(__dirname + '/../index.html')))
historyModeHandlerHTTP.listen(80, () => {
console.log('HTTP Server on')
})
Webpack.prod.conf.js
'use strict'
const path = require('path')
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const env = require('../config/prod.env')
const webpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: true,
usePostCSS: true
})
},
devtool: config.build.productionSourceMap ? config.build.devtool : false,
output: {
path: config.build.assetsRootMain,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
plugins: [
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.ProgressPlugin(),
new CleanWebpackPlugin({
dry: false,
cleanOnceBeforeBuildPatterns: [config.build.assetsSubDirectory + '*/js/*', config.build.assetsSubDirectory + '*/css/*']
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
allChunks: true,
}),
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ?
{
safe: true,
map: {
inline: false
}
} :
{
safe: true
}
}),
new HtmlWebpackPlugin({
filename: config.build.index,
template: 'template.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: false,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
}),
new webpack.HashedModuleIdsPlugin(),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks(module) {
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
new CopyWebpackPlugin([{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}])
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
const config = require('../config')
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost',
port: 8080,
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false,
devtool: 'cheap-module-eval-source-map',
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../../index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsRootMain: path.resolve(__dirname, '../../'),
assetsSubDirectory: 'front-end/static',
assetsPublicPath: '',
mainfile : 'front-end/src/main.js',
routerfile : 'front-end/src/router/index.js',
constantsFile : 'utils-bf/constants.js',
productionSourceMap: true,
devtool: '#source-map',
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
}
}
[解决方案]
问题与Webpack的配置有关! 如果有人遇到同样的问题,只需设置 PublicPath : '/'
output: {
publicPath: '/',
path: config.build.assetsRootMain,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},