Cannot Import modules from Nuxt.js middleware - javascript

I try to import modules from middleware, type error occurs and the Nuxt application does not start.
The code is as follows.
The application uses nuxt-community / starter-template.
nuxt.config.js (jsut add only router on default file)
module.exports = {
router: {
middleware: 'auth'
},
middleware/auth.js
import { Auth } from aws-amplify
export default ( ) => {
const user = Auth.currentUserInfo()
console.log(user)
}
run npm run dev (error occur)
Cannot read property 'indexOf' of undefined
Thanks your help!

Related

How to use vue-toastification

I just migrated my project created in vue 3 to nuxt 3. Previously I used the vue-toastification module but now I don't know how to import it correctly. My code using this module.
import { useToast, POSITION } from 'vue-toastification'
const toast = useToast()
export default {
methods: {
copy(text) {
toast.success('Copied!', {
timeout: 2000,
position: POSITION.BOTTOM_CENTER,
})
navigator.clipboard.writeText(text)
}
}
}
In Vue I had to do app.use(Toast) but Nuxt does not have an index.js file. Adding modules: ['vue-toastification/nuxt'] in nuxt.config.js does not work because I get an error.
Answers suggested by kissu and Ricardo de Paula worked for me while I was using development server (npm run dev).
After building and running the project I encountered error 500:
Named export 'useToast' not found. The requested module 'vue-toastification' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using: import pkg from 'vue-toastification';
To fix this, I registered toast as plugin helper (I'm using Nuxt 3.1.1 with Nitro 2.1.1):
Inside vue-toastificaton.client.js:
import { defineNuxtPlugin } from '#app'
import * as vt from 'vue-toastification'
import '#/assets/css/toast.scss'
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(vt.default)
return {
provide: {
toast: vt.useToast()
}
}
})
Then in my component script setup:
//throws an error after production build
//import { useToast } from 'vue-toastification'
//const toast = useToast()
//toast.success('Yay!!!')
//works after production build
const { $toast } = useNuxtApp()
$toast.success('Yay!!!')
If you want it to be available globally, you can install it as a Nuxt plugin as explained in the official docs or in this other answer.
vue-toastification is probably a client-side only plugin, hence you would probably want to use it as
/plugins/vue-toastificaton.client.js like this
import { defineNuxtPlugin } from '#app'
import Toast from "vue-toastification"
import "vue-toastification/dist/index.css" // if needed
export default defineNuxtPlugin(nuxtApp => {
nuxtApp.vueApp.use(Toast)
})
Then, you should be able to use it in your components with either Composition API or Options API (I think).
I was wanting to do the same thing. I read kissu's answer and did the following:
1 - I created a folder for the puglin - plugins
2 - Inside the plugins folder I created a file called vue-toastificaton.client.js
Inside vue-toastificaton.client.js:
import { defineNuxtPlugin } from '#app'
import Toast from 'vue-toastification'
import 'vue-toastification/dist/index.css' // if needed
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(Toast)
})
And I used it that way:
<script setup>
import { useToast } from 'vue-toastification'
const toast = useToast()
const onSubmit = () => {
// use the toast notification plugin to show a success message
toast.success('Hello world!')
}
</script>

Got the error "Build optimization failed: found page without a React Component as default export in pages/" Help me

In developer mode worked great. Later in CMD, I sent "npm run build. Got error...
info - Checking validity of types
info - Creating an optimized production build
info - Compiled successfully
> Build optimization failed: found pages without a React Component as default export in
pages/js/TimeClock
pages/js/ChangePage
I tried to fix it. Nothing on the internet helped. Here are my files:
index.js
import Head from 'next/head'
import Time from './js/TimeClock.page';
import { ChangePage0, ChangePage1, ChangePage2 } from './js/ChangePage.page';
export default function Home() {
...
}
TimeClock.page.js
import ReactDOM from 'react-dom'
export function tick()
{
const site = (
<div>
<span className="time">
{new Date().toLocaleTimeString()}
</span>
</div>
);
ReactDOM.render(site, document.getElementById('time'));
}
setInterval(tick, 1000);
next.config.js
/** #type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = {
pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'], nextConfig
}
Not sure to understrand what you're trying to do with the setIinterval on a component but you probably need to export default instead of a naming export.
In TimeClock.page.js
function Tick() {
...
}
export default Tick;

export import browser complaint cannot find module

This Meteor app has a template event that maks a Meteor.call, and is causing browser error Cannot find module 'server/plateCheck.js'. The file responsible is:
//app/imports/api/vehicles/methods.js
import { Meteor } from 'meteor/meteor'
import { Vehicles } from './vehicles.js'
import { plateCheck } from "../server/plateCheck.js"; //<<<<<<<<<<
Meteor.methods({
'extractPlateData': function (plate) {
console.log('method called: ', plate)
plateCheck(plate)
}
)},
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '../imports/api/vehicles/vehicles.js'
const plateCheck = async (plateNumber) => {...}
module.exports = plateCheck;
meteor list includes ecmascript 0.15.1
Why is this and isn't the export/import correct as stated? How to get read of the error? Thanks.
Your relative path is wrong. The server folder is in the same directory as methods.js, so you'll need to import
import { plateCheck } from "./server/plateCheck.js";
Or you can make all imports absolute:
//app/imports/api/vehicles/methods.js
import { plateCheck } from "/imports/api/server/plateCheck.js";
...
//app/imports/api/vehicles/server/plateCheck.js
import {Vehicles} from '/imports/api/vehicles/vehicles.js'

Unexpected undefined while import with Webpack

I have a problem that has never happened to me before: I'm compiling a little basic starter browser web app (with React) using Webpack + Babel 7.
I've got three different file:
withAuth.js The Auth High Order Component
NavBar.js The NavBar Component
Login.js The Login Form
If I import the withAuth HOC in the NavBar is everything alright, but if I import the withAuth component in the Login.js file it return undefined
/** withAuth.js */
console.log('withAuth Loaded');
const withAuth = Child => ChildProps => (
<AuthContext.Consumer>
{ authClient => <Child {...ChildProps} authClient={authClient} }
</AuthContext.Consumer>
)
export { withAuth };
/** NavBar.js */
import { withAuth } from 'HOC/Auth';
console.log('NavBar Loaded', withAuth); // <- My HOC
const NavBarComponent = (authClient) => { /* ... My Code ... */ }
const NavBar = withAuth(NavBarComponent);
export default NavBar;
/** Login.js */
import { withAuth } from 'HOC/Auth';
console.log('Login Loaded', withAuth); // <- undefined ??
const LoginFormComponent = (authClient) => { /* ... My Code ... */ }
const LoginForm = withAuth(LoginFormComponent);
// /|\
// |
// Will produce an Error, withAuth is Undefined
This is my Webpack Configuration:
/** webpack.config.js */
module.exports = {
entry: { core: 'index.js' },
resolve: {
alias: {
HOC: './path/to/hoc/folder'
}
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all'
}
},
plugins: [ /* Various Plugin */ ],
module: {
rules: [ /* My Rules */ ]
}
}
Any one know why my HOC is undefined?
Edit:
I've placed Console Log in the tree file. The result are:
'Login Loaded' - undefined
'withAuth Loaded'
'NavBar Loaded' - function() { }
Edit 2:
This is the files structure:
app/
|-high-order-component/
| |-auth/
| |-withAuth.js
|
|-layout-component/
| |-navbar/
| |-index.js
|
|-pages/
|-auth/
|-login.js
Resolved
After much testing and research throughout the afternoon I came to the solution of the problem. As I said in the question, mine is a larger project and I only partially wrote its structure because I thought the problem was located in those three files.
In reality, the problem was a Circular Dependency problem and not a Webpack configuration problem.
In my project I have a module called 'Route' that store all Path and all Component for Path, so I can build the React Router using Array Map function. That module has a function that allow me to Route through path and that can return me a path string to a Component.
My problem was due to the fact that this module is often called in the project and this has created a Circular Dependency.
Webpack doesn't show the Circular Dependency during compiling, but I found useful adding a plugin, called CircualDependencyPlugin. This plugin will break Webpack compiling when a Circual Dependency will be found.
Splitting the Route module into two files solved my problem.

Alternative for "component: () => import()" in VueJS routing

I downloaded a template online to better understand VueJS and also create a web app. However I have a problem with routing. There is a function in my router's index.js that imports a path. The import syntax seems to be buggy due to some webpack issues. I tried a lot of different things but couldn't fix the bug so I want to find a workaround for that import syntax
This is my code for router's index.js
import Vue from 'vue'
import VueAnalytics from 'vue-analytics'
import Router from 'vue-router'
import Meta from 'vue-meta'
// Routes
import paths from './paths'
// import views from './views'
function route (path, view, name) {
return {
name: name || view,
path,
component: () => import(
`../views/${view}.vue`
)
}
}
Vue.use(Router)
// Create a new router
const router = new Router({
mode: 'history',
routes: paths.map(path => route(path.path, path.view, path.name)).concat([
{ path: '*', redirect: '/home' }
]),
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
}
if (to.hash) {
return { selector: to.hash }
}
return { x: 0, y: 0 }
}
})
Vue.use(Meta)
// Bootstrap Analytics
// Set in .env
// https://github.com/MatteoGabriele/vue-analytics
if (process.env.GOOGLE_ANALYTICS) {
Vue.use(VueAnalytics, {
id: process.env.GOOGLE_ANALYTICS,
router,
autoTracking: {
page: process.env.NODE_ENV !== 'development'
}
})
}
export default router
When i try to build it, I get an error saying:
ERROR in ./src/router/index.js
Module build failed: SyntaxError: C:/djangoProjects/martin - Copy/martin/src/router/index.js: Unexpected token (15:21)
The syntax error is on line (15:21), in the route function on the component: () => import( line and exactly on import. Fixing this issue is a pain so I was wondering if there is a workaround for it without using the import syntax?
If I remember correctly you'll need a plugin for babel that can handle dynamic imports.
Check out:
https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import
Run npm install #babel/plugin-syntax-dynamic-import
Create or open .babelrc
{
"plugins": ["#babel/plugin-syntax-dynamic-import"]
}

Categories

Resources