vue plugin pwa sw.js not found - vue.js

I have 1 app using the vue pwa plugin, it works great.
The vuejs config for the app looks like this:
const WebpackNotifierPlugin = require('webpack-notifier')
module.exports = {
lintOnSave: false,
css: {
loaderOptions: {
sass: {
implementation: require('sass')
}
}
},
transpileDependencies: [
'vuex-module-decorators',
'vuex-persist'
],
pwa: {
name: 'MyApp',
themeColor: '#000000',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'dev/sw.js',
// ...other Workbox options...
}
},
configureWebpack: {
devServer:{
historyApiFallback: true,
},
plugins: [
new WebpackNotifierPlugin(),
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: 3,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `npm.${packageName.replace('#', '')}`;
},
},
},
},
},
},
}
I have another app, exactly the same, vue2, beufy etc etc.. i installed the same stuff via the vue pwa plugin and the config looks exactly the same but when i run build it says it cannot find the sw.js file:
Error: ENOENT: no such file or directory, open 'dev/sw.js'
I have created a uber basic vue app which does the same thing here: https://github.com/johndcarmichael/vue-pwa-sw-not-found
Has anyone else got this issue, and how did you resolve it?

You are not having dev/sw.js in your project, as you set in swSrc. InjectManifest means take this sw.js source file and write precache manifest into it, producing the final service-worker.js file.

Related

Vite.js Dynamic Image Loading Fails In Production

I have a problem in importing dynamic assets in production mode. When I ran the development environment everything works fine and the assets loads...but when I build the Vue.js application, assets won't load and I gets below error:
TypeError: URL constructor: ../../../assets/images/name.png is not a valid URL.
how can I fix this issue?
Vue Example
<img :src="findImageFromNumber(card.cartNumber)" alt="image" width="25" />
function findImageFromNumber(number: string) {
const name = identify(number).english;
const path = new URL('../../../assets/images/banks/' + name + '.png', import.meta.url);
return path.href
}
Vite.js Config
export default defineConfig({
root: './',
resolve: {
alias: {
'/#/': path.resolve(__dirname, 'src')
},
},
publicDir: 'assets',
mode: 'production',
build: {
outDir: 'dist',
sourcemap: true,
target: ['es2019', 'safari11', 'firefox60', 'chrome61', 'node12'],
chunkSizeWarningLimit: 500,
minify: false,
emptyOutDir: true,
assetsInlineLimit: 2048,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`,
manualChunks(id) {
if (id.includes('vue')) {
return 'react';
} else if (id.includes('node_modules')) {
return 'vendor';
}
},
},
}
},
plugins: [
vue(),
legacy({
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally']
})
],
})
Note: Everything works fine in development and it only fails in production...
Assets is your public dir. Should it just be /assets/images/banks, according to the docs?

Webpack control of output css file names

I'm trying to control the filenaming of files produced from a Vue app with Webpack.
The environment where I want to host the built app doesn't like filenames with '.' (don't ask).
I have been able via get js files to comply with a 'hyphen' naming scheme by using output.filename in vue.config.js configureWebpack entry. But css files are not renamed.
As I am loading the two bulk packed files rather than chunks I can obviously manually rename the single css file. However when I run it I get an error
Error: Loading CSS chunk error failed.
(/my-path/resources/css/error.d0f9a634.css)
I'm hoping I can force all css files (including the error one) to be renamed by the build process.
My vue.config.js
module.exports = {
outputDir: path.resolve(__dirname, 'dist'),
publicPath: "/my-path/resources",
configureWebpack: {
optimization: {
splitChunks: false
},
output: {
filename: "[name]-js",
chunkFilename: "[name]-chunk-js",
// get cssFilename() {
// return "[name]-css";
// }
},
resolve: {
alias: {
'vue$': path.resolve('./node_modules/vue/dist/vue.common.js'),
},
},
},
// https://cli.vuejs.org/config/#productionsourcemap
productionSourceMap: false,
// https://cli.vuejs.org/config/#css-extract
css: {
extract: { ignoreOrder: true },
loaderOptions: {
sass: {
prependData: '#import \'~#/assets/scss/vuetify/variables\''
},
scss: {
prependData: '#import \'~#/assets/scss/vuetify/variables\';'
}
}
},
// ...
}
I have started to look at MiniCssExtractPlugin but not sure if that is the right direction to look. Any help appreciated.
I found a working solution for this via the css.extract element in vue.config.js.
configureWebpack: {
optimization: {
splitChunks: false
},
output: {
filename: "js/[name]-js",
chunkFilename: "js/[name]-chunk-js",
},
...
},
// https://cli.vuejs.org/config/#css-extract
css: {
extract: {
ignoreOrder: true,
filename: 'css/[name]-css',
chunkFilename: 'css/[name]-chunk-css',
},
loaderOptions: {
sass: {
prependData: '#import \'~#/assets/scss/vuetify/variables\''
},
scss: {
prependData: '#import \'~#/assets/scss/vuetify/variables\';'
}
}
},
...
Which as the documentation link for css.extract says
Instead of a true, you can also pass an object of options for the
mini-css-extract-plugin if you want to further configure what this
plugin does exactly
and is covered by the webpack mini-css-extract-plugin documentation

Can not config Tailwind in NuxtJS

i use "#nuxtjs/tailwindcss": "^2.0.0" for my Nuxt App.
After install, it created a tailwind.config.js file. And then, i added a little code as you could see below:
module.exports = {
theme: {},
variants: {},
plugins: [],
purge: {
enabled: process.env.NODE_ENV === 'production',
content: [
'components/**/*.vue',
'layouts/**/*.vue',
'pages/**/*.vue',
'plugins/**/*.js',
'nuxt.config.js',
],
},
options: {
important: true,
},
};
I want all the Tailwind's class have important, but it weren't.
inside the tailwin's class
What i did wrong?
Most probably you are running NODE_ENV=production so its purging unused classes
Setting purge.enabled=false will do what you want. I don't recommend setting it false. If a class is used purge won't remove the class. As you are not using most of the classes in HTML they are getting removed.
module.exports = {
theme: {},
variants: {},
plugins: [],
purge: {
enabled: false, // DONT DO THIS IN PRODUCTION
content: [
'components/**/*.vue',
'layouts/**/*.vue',
'pages/**/*.vue',
'plugins/**/*.js',
'nuxt.config.js',
],
},
options: {
important: true,
},
};
If I look at the documentation the important key should be at the root of export :
// tailwind.config.js
module.exports = {
important: true,
}
instead of
// tailwind.config.js
module.exports = {
options: {
important: true,
}
}
I know what messed up.
So turn out that the problem was PostCSS
And, another thing is that in older version, the important was in options, but now it placed at the root
// tailwind.config.js
module.exports = {
important: true,
}

How to process css with postcss inside sapper-template with rollup

Having trouble using rollup-plugin-postcss with sapper-template:
npx degit sveltejs/sapper-template#rollup my-app
npm install rollup-plugin-postcss --save-dev
install various postcss plugin
create src/css/main.css
add import './css/main.css'; to the top line of src/client.js
*edit rollup.config.js
*add postcss.config.js
*going wrong here? I have tried several variations.
// rollup.config.js
...
import postcss from 'rollup-plugin-postcss'
...
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
dev,
hydratable: true,
emitCss: true
}),
resolve(),
commonjs(),
postcss({
// extract: true,
// sourceMap: true,
plugins: [require('autoprefixer')]
}),
...
// postcss.config.js
module.exports = {
plugins: {
...
autoprefixer: {}
}
};
No real error message, once I add postcss to the plugins in the client:{} of rollup.config.js - css breaks on the site.
This is a matter of simply putting the svelte plugin config together properly. I would recommend you use svelte-preprocess and setup your rollup.config.js as follows:
import autoPreprocess from 'svelte-preprocess';
const preprocessOptions = {
postcss: {
plugins: [
require('postcss-import'),
require('postcss-preset-env')({
stage: 0,
browsers: 'last 2 versions',
autoprefixer: { grid: true }
}),
...
]
}
};
...
export default {
client: {
plugins: [
svelte({
preprocess: autoPreprocess(preprocessOptions),
dev,
hydratable: true,
emitCss: true
}),
...
As you see here, you need to set the preprocess option of the svelte plugin.

ESLint throw error Expected method shorthand (object shorthand)

I am following the steps in this tutorial :
https://www.youtube.com/watch?v=z6hQqgvGI4Y
using VSCode (version 1.22.2) as my editor
I am running the following version
==> vue --version
2.9.3
of Vue / vue-cli installed from npm using the steps outlined here :
npm install --global vue-cli
My VSCode workspace settings (User settings) are as follows :
{
"workbench.colorTheme": "Visual Studio Dark",
"window.zoomLevel": 1,
"workbench.statusBar.visible": true,
"workbench.startupEditor": "newUntitledFile",
// Format a file on save. A formatter must be available, the file must not be auto-saved, and editor must not be shutting down.
// "editor.formatOnSave": true,
"eslint.autoFixOnSave": true,
// Enable/disable default JavaScript formatter (For Prettier)
"javascript.format.enable": false,
// Use 'prettier-eslint' instead of 'prettier'. Other settings will only be fallbacks in case they could not be inferred from eslint rules.
"prettier.eslintIntegration": false,
"editor.insertSpaces": true,
"[javascript]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"[vue]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"eslint.options": {
"extensions": [".html", ".js", ".vue", ".jsx"]
},
"eslint.validate": [
{
"language": "html",
"autoFix": true
},
{
"language": "vue",
"autoFix": false
},
{
"language": "javascript",
"autoFix": true
},
{
"language": "javascriptreact",
"autoFix": true
}
]
}
I have the Vetur tooling for VSCode installed :
https://github.com/vuejs/vetur
I have the following files :
src/components/HomeCentral.vue
<template>
<div class="homecentral">
<input type="text" v-model="title"><br/>
<h1>{{title}}</h1>
<p v-if="showName">{{user.first_name}}</p>
<p v-else>Nobody</p>
<ul>
<li v-for="item in items" :key="item.id">{{item.title}}</li>
</ul>
<button v-on:click="greet('Hello World')">Say Greeting</button>
</div>
</template>
<script>
export default {
name: 'HomeCentral',
data() {
return {
title: 'Welcome',
user: {
first_name: 'John',
last_name: 'Doe',
},
showName: true,
items: [
{ title: 'Item One' },
{ title: 'Item Two' },
{ title: 'Item Three' },
],
};
},
methods: {
greet: function (greeting) {
alert(greeting);
},
},
};
</script>
<style scoped>
</style>
src/App.vue
<template>
<div id="app">
<home-central></home-central>
</div>
</template>
<script>
import HomeCentral from './components/HomeCentral';
export default {
name: 'App',
components: {
HomeCentral,
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import HomeCentral from '../components/HomeCentral';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'HomeCentral',
component: HomeCentral,
},
],
});
My .eslintrc looks as follows :
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
node: true,
"es6": false
},
extends: 'airbnb-base',
// required to lint *.vue files
plugins: [
'html',
'vue'
],
// check if imports actually resolve
settings: {
'import/resolver': {
webpack: {
config: 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
js: 'never',
vue: 'never'
}],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
'no-param-reassign': ['error', {
props: true,
ignorePropertyModificationsFor: [
'state', // for vuex state
'acc', // for reduce accumulators
'e' // for e.returnvalue
]
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
optionalDependencies: ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
My .editorconfig looks like this :
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
But when I run
==> npm run dev
I get the following output :
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
95% emitting
WARNING Compiled with 1 warnings 3:01:35 PM
⚠ http://eslint.org/docs/rules/func-names Unexpected unnamed method 'greet'
src/components/HomeCentral.vue:33:12
greet: function (greeting) {
^
⚠ http://eslint.org/docs/rules/no-alert Unexpected alert
src/components/HomeCentral.vue:34:7
alert(greeting);
^
✘ http://eslint.org/docs/rules/object-shorthand Expected method shorthand
src/components/HomeCentral.vue:33:5
greet: function (greeting) {
^
✘ 3 problems (1 error, 2 warnings)
Errors:
1 http://eslint.org/docs/rules/object-shorthand
Warnings:
1 http://eslint.org/docs/rules/no-alert
1 http://eslint.org/docs/rules/func-names
You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
Why is ESlint complaining about "Expected method shorthand" as an error and pointing to the following ES6 linting rule :
http://eslint.org/docs/rules/object-shorthand
Does 2.9.3 version of Vue use ES6 ?
How to silence the VScode editor from linting this semantically correct Vue code :
Fixed by following PeterVojtek answer at the following :
https://github.com/vuejs-templates/webpack/issues/73
Basically changed the following section on build/webpack.base.conf.js
const createLintingRule = () => ({
test: /\.(js|vue)$/,
loader: 'eslint-loader',
enforce: 'pre',
include: [resolve('src'), resolve('test')],
options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay
}
})
to
const createLintingRule = () => ({
})
Also removed 'html' from plugins sections of .eslintrc.js
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
node: true,
"es6": false
},
extends: [
'airbnb-base',
],
// required to lint *.vue files
plugins: [
'vue',
],
// check if imports actually resolve
settings: {
'import/resolver': {
webpack: {
config: 'build/webpack.base.conf.js'
}
}
},
// add your custom rules here
rules: {
// don't require .vue extension when importing
'import/extensions': ['error', 'always', {
js: 'never',
vue: 'never'
}],
// disallow reassignment of function parameters
// disallow parameter object manipulation except for specific exclusions
'no-param-reassign': ['error', {
props: true,
ignorePropertyModificationsFor: [
'state', // for vuex state
'acc', // for reduce accumulators
'e' // for e.returnvalue
]
}],
// allow optionalDependencies
'import/no-extraneous-dependencies': ['error', {
optionalDependencies: ['test/unit/index.js']
}],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
TSlint error/warning in callback function in 'Angular 10', VS code version 1.53.2 -
Solution -
doc.html(htmlData.innerHTML, {
callback(data: any): void {
data.save('angular-demo.pdf');
},
x: 10,
y: 10
});
package.json -
{
"dependencies": {
"#angular/core": "~10.1.3",
...
},
"devDependencies": {
"#angular/cli": "~10.1.3",
"#types/node": "^12.11.1",
"ts-node": "~8.3.0",
"tslint": "~6.1.0",
"typescript": "~4.0.2",
...
}
}