Nuxt.js returns undefined for custom plugin - vue.js

I wanted to create a custom plugin for a local databaase in Nuxt.js, after I was done with the code I registered it in nuxt.config.js and it didn't work. So I've tried the example code on docs to see what I was doing wrong, and the thing is, example code didn't work too. Here is how I registered it:
plugins/hello.js
export default ({ app }, inject) => {
inject("hello", msg => console.log(`Hello ${msg}!`));
};
nuxt.config.js
module.exports = {
ssr: false,
target: "static",
head: {
title: "project-title",
meta: [{ charset: "utf-8" }],
},
loading: false,
plugins: [{ ssr: true, src: "#/plugins/icons.js" }, "#/plugins/hello.js"],
modules: ["#nuxtjs/axios", "#nuxtjs/auth-next"],
}
Whenever I try to use this.$hello("something"), Nuxt returns this.$hello is not a function

Hmm, got it. After deleting and reinstalling node_modules it's resolved, then I tried changing the name of the plugin file, after then build failed from ./node_modules/#nuxt/webpack/node_modules/babel-loader/lib/index.js. After reinstalling packages again (deleted .nuxt, node_modules and lock file) issue is resolved.

Related

Updating PostCSS config to support plugins

I am trying to update my postcss.config.js file to support two plugins: postcss-nested and postcss-mixins. Tech used: react project, using webpack and npm.
From PostCSS documentation, it says i need to add the plugins as an array and in this StackOverflow post, it similarly says 'the export in the postcss.config.js needs to be an object with a plugins property that holds an array of your plugins.' When i try that, i'm getting linting erros and it seems wrong. Any suggestions welcome.
Old postcss.config.js
module.exports = {
parser: 'postcss-scss',
plugins: {
'precss': {
'import': {
extension: 'pcss',
prefix: '_',
},
},
'postcss-calc': {
mediaQueries: true,
},
},
};
New postcss.config.js
module.exports = {
parser: 'postcss-scss',
plugins: [
require('postcss-mixins'),
require('postcss-nested'),
],
'precss': {
'import': {
extension: 'pcss',
prefix: '_',
},
},
'postcss-calc': {
mediaQueries: true,
},
};
};
One other question: will any of my postcss plugins work if i don't include them in my postcss.config.js file? I am looking at our codebase and seeing many postcss plugins installed (such as autoprefixer) and they are not in the config file...so not sure if that was ever working for us.

google/model-viewer with nuxt

I'm a bit clueless with integrating the #google/model-viewer into a nuxtjs project:
This is my model-viewer.js in the plugins folder
import Vue from "vue";
import modelViewer from "#google/model-viewer";
Vue.use(modelViewer);
The part in my nuxt.config.js
plugins: [
"#/plugins/hooks",
{ src: "#/plugins/gsap", mode: "client" },
{ src: "#/plugins/model-viewer", mode: "client" },
],
... and the component so far
<template>
<model-viewer
:src="src"
bounds="tight"
enable-pan
camera-controls
environment-image="neutral"
poster="poster.webp"
shadow-intensity="1"
autoplay
></model-viewer>
</template>
<script lang="ts">
export default {
ssr: false,
name: "Viewer3d",
props: {
src: {
type: String,
required: true,
},
},
setup() {
return {};
},
};
</script>
When called I get the Error
Failed to compile with 1 errors friendly-errors 13:36:36
ERROR in
./node_modules/#google/model-viewer/dist/model-viewer.min.js
friendly-errors 13:36:36
Module parse failed: Unexpected token (999:5963)
friendly-errors 13:36:36 You may need an appropriate loader to handle
this file type, currently no loaders are configured to process this
file. See https://webpack.js.org/concepts#loaders | * limitations
under the License. | */
and a
window is not defined
from my browser.
What am I missing? I am not familiar with loaders in nuxt and wasn't able to find something helping me with my problem.
I had the same issue but with NuxtJS. Try to use an older version of the model-viewer, everything until version 1.10.1 is working for me.

How do I include 'fs' modules in Sapper?

I am working on a Sapper project, as it seemed neat for a little project I wanted to get up and running quickly. That's not be easy and I'm now having trouble running scripts from my Sapper project that include the built-in 'fs' modules.
I'm trying to build a character generator. I have built a script that will do this but I'd like to be able to save my generated characters as JSON files then read them in later. Reading in is easy, writing doesn't seem to be listed anywhere obvious. The best I have is trying to get the built in plugins to function to allow me access to fs modules but my research on this is spotty and not helping. Trying to get rollup to help doesn't appear to work and I am unable to find an acceptable alternative.
Whenever I run the project, it just says that it can't resolve it.
Could not load fs (imported by E:\Software Projects\Javascript\Io-Generator\src\routes\generator\generator.js): ENOENT: no such file or directory, open 'E:\Software Projects\Javascript\Io-Generator\fs'
Nothing I do seems to help. Please can someone explain what I'm missing here? Am I using Sapper wrong? Am I missing something in rollup here? Is there an alternative I'm missing?
My roll-up config if it helps:
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({
browser: true,
preferBuiltins: true,
dedupe
}),
commonjs( {
browser: true
} ),
globals(),
builtins( {
fs: true
} ),
json(),
legacy && babel({
extensions: ['.js', '.mjs', '.html', '.svelte'],
runtimeHelpers: true,
exclude: ['node_modules/#babel/**'],
presets: [
['#babel/preset-env', {
targets: '> 0.25%, not dead'
}]
],
plugins: [
'#babel/plugin-syntax-dynamic-import',
['#babel/plugin-transform-runtime', {
useESModules: true
}]
]
}),
!dev && terser({
module: true
})
],
onwarn,
},
server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
svelte({
generate: 'ssr',
dev
}),
resolve({
browser: false,
preferBuiltins: true,
dedupe
}),
commonjs(),
builtins( {
fs: true
} ),
json()
],
external: Object.keys(pkg.dependencies).concat(
require('module').builtinModules || Object.keys(process.binding('natives'))
),
onwarn,
},
serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve( {
browser: false,
preferBuiltins: true
} ),
replace({
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
}),
commonjs(),
builtins( {
fs: true
} ),
json(),
!dev && terser()
],
onwarn,
}
};```
So, I went an restarted my project from a fresh project. Aaaaand it was fine. It's working fine. It's possible that I really screwed up my project trying out multiple different things to get them working, causing some serious damage. I'll need to be more careful in future.

Vue PWA plugin adjusting iconPaths and manifest destination

I have attached 2 screenshots, one of my vue.config.js and another of a section of the unminified output my build is producing.
Whats happening is this: I want to change the icon paths and the path to the manifest. For whatever reason the official way of changing this is not working. Right now they are blank spaces, however it was not working when it was anything else either ( just tried with 'foo/bar' as the path as I was typing this to triple check ).
I am confused because I seem to be doing everything exactly as I should according to the official docs. Is there anything another set of eyes can spot that I am missing?
Greetings Erik White
At some point I had the same difficulty and solved it as follows:
Copy the images into the "public" folder
example:
We add the folder "favicon" to "public", "favicon" contains 5 images
[project]/public/favicon/favicon-32x32.png
[project]/public/favicon/favicon-16x16.png
[project]/public/favicon/apple-touch-icon-152x152.png
[project]/public/favicon/safari-pinned-tab.svg
[project]/public/favicon/msapplication-icon-144x144.png
To add images in your html: modify the "vue.config.js" and add.
// Inside vue.config.js
module.exports = {
  // ... other vue-cli plugin options ...
  pwa: {
  // ...
    iconPaths: {
      favicon32: 'favicon/favicon-32x32.png',
      favicon16: 'favicon/favicon-16x16.png',
      appleTouchIcon: 'favicon/apple-touch-icon-152x152.png',
      maskIcon: 'favicon/safari-pinned-tab.svg',
      msTileImage: 'favicon/msapplication-icon-144x144.png'
    }
  // ...
  }
}
To change the path and name of "manifest.json" modify the "vue.config.js" and add:
// Inside vue.config.js
module.exports = {
  // ... other vue-cli plugin options ...
  pwa: {
  // ...
    manifestPath: 'my_new_manifest.json',
  // ...
  }
}
To change the properties of the "manifest.json", (name, images, color, etc) modify the "vue.config.js" and add:
// Inside vue.config.js
module.exports = {
// ... other vue-cli plugin options ...
pwa: {
// ...
manifestOptions: {
name: 'etc ..',
short_name: 'etc ..',
theme_color: '# f44647',
background_color: '# f44647',
start_url: 'index.html',
display: 'standalone',
orientation: 'portrait',
icons: [
{
src: './favicon/favicon-32x32.png',
sizes: '32x32',
type: 'image/png'
},
{
src: './favicon/favicon-16x16.png',
sizes: '16x16',
type: 'image/png'
},
{
src: './favicon/apple-touch-icon-152x152.png',
sizes: '152x152',
type: 'image/png'
},
{
src: './favicon/safari-pinned-tab.svg',
sizes: '942x942',
type: 'image/svg+xml'
},
{
src: './favicon/msapplication-icon-144x144.png',
sizes: '144x144',
type: 'image/png'
},
]
},
// ...
}
}
NOTE
chucks is not a supported parameter.
excludeChucks is not a supported parameter.
If you need to test a service worker locally, build the application and run a simple HTTP-server from your build directory. It's recommended to use a browser incognito window to avoid complications with your browser cache.
Remember to see the VUE documentation, it is very detailed, I leave you a link below #vue/cli-plugin-pwa
Nevermind, solved by updating my dependencies.
guessing this was fixed in a patch i didnt catch

r.js minified optimized file not running

BEFORE, I was using r.js to optimize and minify my javascript successfully. I had a main.js file that looked something like this:
require.config({
baseUrl: "scripts/lib",
paths: {
jquery: "http://code.jquery.com/jquery-1.11.2.min",
underscore: "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min",
d3: "d3-for-development",
katex: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min", // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function (){
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true,
},
});
MathJax.Hub.Startup.onload();
return MathJax;
}
},
},
});
require( [
"jquery",
"underscore",
"browser-detect",
"check-types",
"katex",
"mathjax",
etc
], function(
$,
_,
browser,
check,
katex,
mathjax,
etc
){
/////////////////////////// INITIALIZATION ///////////////////////////
loginInit()
show('#login')
etc...
and I could successfully run node build/r.js -o mainConfigFile=www/scripts/main.js baseUrl=www/scripts/lib name=../main out=www/scripts/main-optimized.min.js generateSourceMap=true preserveLicenseComments=false optimize=uglify2 to minify. Everything worked.
NOW, I have a config.js file that looks like this:
require.config({
urlArgs: "bust=" + new Date().getTime(),
baseUrl: "scripts/lib",
paths: {
jquery: ["jquery-min", "http://code.jquery.com/jquery-1.11.2.min"],
underscore: ["underscore-min", "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min"],
d3: "d3-for-development", // if we add patches separately, then we can just use https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min
katex: ["katex-min", "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"], // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
main: "../main",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function init() {
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
processEscapes: true }
});
MathJax.Hub.Startup.onload();
return MathJax;
}
}
}
});
require(["main"], function (main) {
// pass. by loading main, we run main.js
});
Instead of passing the minify/optimize arguments straight into the command line, I've created a rbuild.js file for that:
({
mainConfigFile: "../www/scripts/config.js",
baseUrl: "../www/scripts/lib",
name: "../config",
out: "../www/scripts/config-optimized.min.js",
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
// removeCombined: true,
// findNestedDependencies: true,
paths: {
// https://github.com/jrburke/requirejs/issues/791
// http://www.anthb.com/2014/07/04/optimising-requirejs-with-cdn-fallback
jquery: "jquery-min",
underscore: "underscore-min",
d3: "d3-for-development",
katex: "katex-min",
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
marked: "marked",
chosen: "chosen-min",
jsnetworkx: "jsnetworkx-min",
main: "../main",
},
})
and I run it with node build/r.js -o build/rbuild.js in the command line. It appears to run successfully and makes the config-optimized.min.js file, as expected. The output is:
Tracing dependencies for: ../config
Cannot optimize network URL, skipping: http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured
Uglify2 file: /Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
/Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
----------------
/Users/Matthew/programming/prove-math/www/scripts/lib/jquery-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/underscore-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/browser-detect.js
/Users/Matthew/programming/prove-math/www/scripts/lib/check-types.js
/Users/Matthew/programming/prove-math/www/scripts/lib/katex-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/profile.js
/Users/Matthew/programming/prove-math/www/scripts/lib/marked.js
/Users/Matthew/programming/prove-math/www/scripts/lib/d3-for-development.js
/Users/Matthew/programming/prove-math/www/scripts/lib/user.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph-animation.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph.js
/Users/Matthew/programming/prove-math/www/scripts/lib/node.js
/Users/Matthew/programming/prove-math/www/scripts/lib/blinds.js
/Users/Matthew/programming/prove-math/www/scripts/lib/chosen-min.js
/Users/Matthew/programming/prove-math/www/scripts/main.js
/Users/Matthew/programming/prove-math/www/scripts/lib/../config.js
But when I visit index.html via my server, the page is blank. The JS console gives no errors or log messages, which suggests that no JS is being run. My server gives no errors, which suggests that everything has been sent to the client successfully, and the client JS is not running.
So I'm pretty convinced the JS is there but not running. Is there something wrong with my setup that causes config.js to not run the code? With no error messages, I am having trouble troubleshooting :)
So I commented out
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
and it worked! THEN, I uncommented that stuff, and it STILL worked!
It seems that as of requireJS 2.2 (I was using RequireJS 2.1.6 BEFORE), you can now use
optimize: "uglify",
or nothing at all, since this is the default setting. As of requireJS 2.2, it DOES use uglify2 in this case. This is the closest thing to an explanation that I can give :/