Why Nuxt generate publicPath does not work as expected at first visit? - vue.js

I'm using Nuxt v2.15.8 to create a static website using nuxt generate command. I expect the requests to the server for fetching the main js and CSS files to be made to / path, as I specified in my nuxt.cofig:
export default {
ssr: false,
target: 'static',
// ...
build: {
publicPath: process.env.NODE_ENV === 'development' ? '/_nuxt/' : '/',
},
// ...
}
When I visit the generated static website, despite what I specified in the build config, at first it tries to load data from /_nuxt/ path which does not exist. As you can see in the attached pictures, after getting a 404 error for this route, it loads data successfully from the correct path which is /, but it should not send those requests to /_nuxt path to begin with.
Request to the wrong path
Request to the correct path
Any idea about how can I eliminate those initial requests to /_nuxt/?

So I fixed the issue by adding the following lines to nuxt.config.js:
export default {
ssr: false,
target: 'static',
// ...
build: {
publicPath: process.env.NODE_ENV === 'development' ? '/_nuxt/' : '/',
},
// added the following lines
hooks: {
render: {
resourcesLoaded(resources) {
const path = `/`
resources.clientManifest && (resources.clientManifest.publicPath = path)
resources.modernManifest && (resources.modernManifest.publicPath = path)
resources.serverManifest && (resources.serverManifest.publicPath = path)
}
}
},
// ...
}

Related

Serving a modified asset-manifest.json in CRA using CRACO doesn't work

I have just created a new CRA app. In our organization we have a micro frontend framework which has certain requirements when it comes to the the asset file of each micro frontend app. CRA will by default, create a asset-manifest.json file.
https://github.com/facebook/create-react-app/blob/main/packages/react-scripts/config/webpack.config.js#L656
Now I need to change this file to assets.json and make some structural changes as well. To achieve this I use CRACO and add the WebpackManifestPlugin.
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
webpack: {
plugins: {
// tried removing CRA definition for ManifestPlugin.
// It worked, but had no impact on my problem
// remove: ['ManifestPlugin'],
add: [
new ManifestPlugin({
fileName: 'assets.json',
generate: (seed, files, entrypoints) => {
const js = [],
css = [];
files.forEach((file) => {
if (file.path.endsWith('.js') && file.isInitial) {
js.push({ value: file.path, type: 'entry' });
}
if (file.path.endsWith('.css') && file.isInitial) {
css.push({ value: file.path, type: 'entry' });
}
});
return { js, css };
},
})
]
}
}
};
Whenever I build the application, my new assets.json file is generated as expected.
However, I can't get CRA, or webpack-dev-server I assume, to serve this file while I run my CRA app in development mode. It only resolves to the index.html file. I have looked through CRA source code and can't really find any relevant place where asset-manifest.json is mentioned.
So how do I get webpack-dev-server to serve my assets.json file?
You need to add the ManifestPlugin to webpack.plugins.remove array to receive only the configuration from WebpackManifestPlugin:
...
webpack: {
alias: {},
plugins: {
add: [
new WebpackManifestPlugin(webpackManifestConfig)
],
remove: [
"ManifestPlugin"
],
},
configure: (webpackConfig, { env, paths }) => { return webpackConfig; }
},
...

Vue V-Bind:src always includes local server "localhost:8080"

Hi! I receive data from the server by the type "/uploads/image.png", that is, the path to the file. But Vue add to path localhost:8000,
how can I replace localhost with the domain I need?
My problem:
Here
my vue-config:
const path = require('path')
module.exports = {
outputDir: path.resolve(__dirname, './dist'),
devServer: {
proxy : {
'/': {
target: 'http://localhost:1337'
}
}
}
}
set publicPath:
publicPath: process.env.NODE_ENV === 'production' ? '': 'http://localhost:1337/',

Uncaught ReferenceError: webpackJsonp in Vue Js

I have suddenly started hitting Uncaught ReferenceError: webpackJsonp in Vue Js. I am fairly new to Js and have just started with Vue applications. I tried the various solutions that were mentioned in the Git and stackoverflow but they have not worked. Can someone help me out.
To give some context, the issue suddenly appeared without having made much of a change. The code is working when it was in the state earlier but making any change in the components even modifying the css has started causing the issue.
Based on what I read about the issue, it is supposed to be controlled by the webpack.prod.conf.js (Attached mine below). Incase any other info is needed please let me know.
"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 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.assetsRoot,
filename: utils.assetsPath("js/[name].[chunkhash].js"),
chunkFilename: utils.assetsPath("js/[id].[chunkhash].js")
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
"process.env": env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath("css/[name].[contenthash].css"),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap ?
{ safe: true, map: { inline: false } } :
{ safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: config.build.index,
template: "index.html",
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: "dependency"
}),
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: "vendor",
async: false,
minChunks(module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(path.join(__dirname, "../node_modules")) === 0
);
// return module.context && module.context.includes("node_modules");
}
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: "app",
async: "vendor-async",
children: true,
minChunks: 3
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: "manifest",
async: false,
minChunks: Infinity
}),
// copy custom static assets
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;
The entry points are missing in the configuration, i.e. you are not informing webpack from where the application should start.
Also this issue is happening because you have mentioned vendor
please refer this link

nuxt.config.js where build modules build only in dev mode?

The source code: github.com/alexpilugin/ap-nuxt-firebase-ssr
The issue is next: this Nuxt SSR Application uses the same nuxt.config.js file which is located in /src folder and before deployment it will be copied into the server folder.
nuxt.config.js contains a next build module which creates an issue on server (in the ssrapp firebase function)
buildModules: [
// https://go.nuxtjs.dev/eslint
'#nuxtjs/eslint-module'
],
My question is how to use a single nuxt.config.js file but don't use #nuxtjs/eslint on production?
I found that it's possible to define dev mode in nuxt.config.js file like that:
dev: process.env.NODE_ENV !== 'production'
but how to use it with buildModules in order to use it with a condition?
My current solution - remove #nuxtjs/eslint-module from nuxt.config.js file
I think you can write a javascript function that returns related environment based modules (dev or prod).
// moduleBuilder.js
const getModulesByEnvironment = () => {
const env = process.env.NODE_ENV;
if (env === 'production') {
return [
...
'brilliant_prod_module',
...
];
}
else {
return [
...
'brilliant_dev_module',
...
]
}
};
export { getModulesByEnvironment };
// nuxt.config.js
import { getModulesByEnvironment } from './moduleBuilder';
...
buildModules: getModulesByEnvironment()
...
You could use array and object destructuring together with process.env.NODE_ENV comparison like this:
nuxt.config.js:
const isProduction = process.env.NODE_ENV === 'production'
export default defineNuxtConfig({
modules: [
...(isProduction ? ['nuxt-bugsnag'] : []),
'#nuxtjs/tailwindcss',
'#vueuse/nuxt',
],
...(
isProduction
? {
bugsnag: {
config: {
apiKey: '',
enabledReleaseStages: ['staging', 'production'],
}
}
}
: {}
),
})

How to output single build.js file for vue production build

I'm using vue-cli 2.9.6, and created a vue project using vue init webpack <project name>.
When I call vue run build, it is creating a number of different js files (and names change each time...):
vendor.20d54e752692d648b42a.js
vendor.20d54e752692d648b42a.js.map
app.ed70f310595763347909.js
app.ed70f310595763347909.js.map
manifest.2ae2e69a05c33dfc65f8.js
manifest.2ae2e69a05c33dfc65f8.js.map
And also css files like this:
app.a670fcd1e9a699133143a2b144475068.css
app.a670fcd1e9a699133143a2b144475068.css.map
I would like the output to simply be 2 files:
build.js { for all js }
styles.css { for all css }
How can I achieve this?
for preventing creation of vendor.js and manifest.js just remove following code from webpack.prod.conf.js
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
To prevent sourceMaps set in config/index.js the variable productionSourceMap from true to false
Changing name of app.js to build.js can be obtained modifying the entry and outputproperties in webpack.base.conf.js this way:
entry: {
build: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].js'),
chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
},
Update name of the css output file updating options of ExtractTextPluginin webpack.prod.conf.js to filename: utils.assetsPath('css/styles.css'),
// vue.config.js
module.exports = {
chainWebpack: config => {
if(config.plugins.has('extract-css')) {
const extractCSSPlugin = config.plugin('extract-css')
extractCSSPlugin && extractCSSPlugin.tap(() => [{
filename: 'styles.css',
chunkFilename: 'styles.css'
}])
}
},
configureWebpack: {
output: {
filename: 'build.js',
chunkFilename: 'build.js'
}
}
}
or
module.exports = {
configureWebpack: {
optimization: {
splitChunks: false
}
},
filenameHashing: false
}