Migrating Nuxt to 2.7: refresh loop - javascript

I'm working on migrating a Nuxt.js project from Nuxt#1.4 to 2.7, and after updating the Webpack config as required, etc. I'm now running into the following error.
When I try to access any of the pages on the website, I hit the stock Nuxt loading screen showing bundling progress, which then immediately refreshes ad infinitum. The application never progresses past this screen, and the tab title never changes from Nuxt.js: Loading app....
There are no errors in the console, nor any compile time errors, but when I go to the devtools Network tab, I see a failed (HTTP 500) request to localhost:3000, with the following error as response payload:
NuxtServerError
render function or template not defined in component: NuxtLoading
I looked into NuxtLoading, and the only reference to it I can find is a file in the .nuxt folder called nuxt-loading.vue, which looks like a regular functioning component. It has a render() method, which is implemented as follows:
render(h) {
let el = h(false)
if (this.show) {
el = h('div', {
staticClass: 'nuxt-progress',
class: {
'nuxt-progress-notransition': this.skipTimerCount > 0,
'nuxt-progress-failed': !this.canSucceed
},
style: {
'width': this.percent + '%',
'left': this.left
}
})
}
return el
}
What I've tried:
Reinstall node_modules;
rm -rf .nuxt && yarn dev (EDIT: and yarn.lock);
Upgrading element-ui to latest version.
Thanks in advance for any help. If any more info is needed, please ask.

You have a wrong configuration for i18n loader. It should be like this:
config.module.rules.push({
resourceQuery: /blockType=i18n/,
type: 'javascript/auto',
loader: '#kazupon/vue-i18n-loader'
});
Or you can use nuxt-i18n module, that will setup this for you using vueI18nLoader option.

Related

How to load React GTM Module in Gatsby project

I'm trying to use react-gtm-module in my Gatsby project, I used the library #loadable/component to load this module in my component. So, when I run gatsby develop, I get the error TagManager.initialize is not a function
This is the code:
import loadable from '#loadable/component';
const TagManager = loadable(() => import('react-gtm-module'));
export const setupGtm = () => {
if (typeof window !== 'undefined') {
TagManager.initialize({
gtmId: 'GTM-ID',
});
}
};
I would really like to use the react-gtm-module because I already have several codes already pre-configured, does anyone know how to use no gatsby?
Thanks!!
For this to run properly, you have to install the Gatsby plugin called Google Tagmanager inside your gatsby project, you can do that. by running
npm install gatsby-plugin-google-tagmanager
When you are done, you have to get the plugin set up in your gatsby-config.js or gatsby-config.ts file.
Check out this doc from Gatsby for more info.
Don't use the React-based dependency. It's far way easy to use the native Gatsby plugins for that since they will insert the script in the needed places automatically. I would suggest get riding off that snippet and using gatsby-plugin-google-tagmanager:
// In your gatsby-config.js
plugins: [
{
resolve: "gatsby-plugin-google-tagmanager",
options: {
id: "YOUR_GOOGLE_TAGMANAGER_ID",
// Include GTM in development.
//
// Defaults to false meaning GTM will only be loaded in production.
includeInDevelopment: false,
// datalayer to be set before GTM is loaded
// should be an object or a function that is executed in the browser
//
// Defaults to null
defaultDataLayer: { platform: "gatsby" },
// Specify optional GTM environment details.
gtmAuth: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_AUTH_STRING",
gtmPreview: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_PREVIEW_NAME",
dataLayerName: "YOUR_DATA_LAYER_NAME",
// Name of the event that is triggered
// on every Gatsby route change.
//
// Defaults to gatsby-route-change
routeChangeEventName: "YOUR_ROUTE_CHANGE_EVENT_NAME",
// Defaults to false
enableWebVitalsTracking: true,
},
},
]
You can omit the options you won't use.

How to set up plotly.js in nuxt SSR?

I'm trying to set up plotly.js in nuxt but whatever I do I get this cryptic error
self is not defined
I tried to install plotly.js and plotly.js-dist same error shows.
I would prefer to make custom build so I tried like this in nuxt plugins:
// here we use custom partial bundle
import plotly from 'plotly.js/lib/core';
import barpolar from 'plotly.js/lib/barpolar';
export default function (_, inject) {
plotly.register([barpolar]);
inject('plotly', plotly);
}
but whenever I register nuxt plugin site crashes with aforementioned error.
Even not going down custom bundle route, and using dist lib still fails just the same.
I also tried not to employ nuxt plugins system but to import manually and to set up, same things happen.
I also added ify-loader as recommended here: https://github.com/plotly/plotly-webpack
and this is my nuxt.config.js in regards to webpack plugin:
build: {
extend(config, { isClient }) {
console.log('config :>> ', config);
config.module.rules.push({
test: /\.js$/,
use: [
'ify-loader',
'transform-loader?plotly.js/tasks/compress_attributes.js',
],
});
},
},
still no luck.
I presume this is problem with webpack 5 and plotly.js not working well together in default setup but I have no idea how to solve this.
Help appreciated.
The reason why this wasn't working is that plotly tried to access document, and in SSR that would obviously fail.
So to fix this I just had to assign plugin in client only mode like this:
plugins: [
// other plugins
{ src: '~/plugins/plotly', mode: 'client' },
],
and it worked.

NuxtJS ignore webpack/chokidar watchers for specific file or folder

I'm using NuxtJS' serverMiddleware for logging. It works on every route.
import { logger } from './utils/logger';
module.exports = function(req, res, next){
logger.info('log.js');
next();
}
It works fine, but when im working on dev environment, whenever I navigate some page, it logs some data, Nuxt dev server logs to console: Updated logs/server.log and then rebuilds dev server.
I need to extract them from watching list.
I've configured watchers property on nuxt.config.js ( according to this page: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-watchers) :
watchers: {
chokidar: {
ignored: '/logs/server.log'
},
webpack: {
ignored: '/logs/server.log'
}
},
but unfortunately it doesn't work.
Thank you for your interest!
Edit
I've tried adding files to .nuxtignore file. But it doesn't work as well.
If you look at the documentation of the configuration-watcher you will find a link to the documentation and syntax needed by chokidar.ignored and webpack.ignored. (Basically use a regexp for a partial match on the path.)
THis should work:
watchers: {
chokidar: { ignored: /logs\/server.log/ },
webpack: { ignored: /logs\/server.log/ } },
You could create a .nuxtignore file and add your file to it. I think this will help ignoring it all the way down.
More info here: https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-ignore#nuxtignore
UPDATE: this solution may be quite better: https://stackoverflow.com/a/74052866/8816585

ES6 Dynamic Imports using Webpack and Babel

I've been using Webpack for my ES6 JS project and has been going well until I started to play with dynamic imports.
What I had that worked (router.js):
import { navigo } from "Navigo"; // router
import { clients } from "Controllers/clients.js";
const navigo = new Navigo();
navigo_router.on({
'/clients': () => {
clients.init();
}
});
But the more pages/routes I add, the more imports get stacked up in the head of the module. This is a relatively large app and I have a lot of pages/routes to add and therefore I need to load them dynamically to reduce the size of the initial page load.
So, following Webpack's documentation for dynamic imports, I tried the following which loads the controller module only when the relative route is called:
import { navigo } from "Navigo"; // router
const navigo = new Navigo();
navigo_router.on({
'/clients': () => {
import("Controllers/clients.js").then((clients) => {
clients.init();
});
}
});
But saving this in my editor resulted in a Babel transpiling error; SyntaxError: 'import' and 'export' may only appear at the top level, and clients.init() is not being called when tested in browser.
After a bit of reading, I discovered I needed a Babel plugin to transpile dynamic import() to require.ensure. So, I installed the plugin using the following command:
npm install babel-plugin-dynamic-import-webpack --save-dev
And declared the plugin in my babel.rc file
{ "plugins": ["dynamic-import-webpack"] }
After installing the plugin, the transpiling error disappeared and checking my transpiled code I found that the dynamic import()s has in fact been changed to require.ensure as expected. But now I get the following browser errors when testing:
Error: Loading chunk 0 failed.
Stack trace:
u#https://<mydomain.com>/js/app.bundle.js:1:871
SyntaxError: expected expression, got '<' 0.app.bundle.js:1
Error: Loading chunk 0 failed.
I didn't understand why it was referencing 0.app.bundle.js with the 0. prefix, so I checked my output/dist folder and I now have a new file in there called 0.app.bundle.js:
0.app.bundle.js 1,962bytes
app.bundle.js 110,656bytes
I imagine this new bundled file is the dynamically imported module, clients.js.
I only added dynamic importing to that one route and have left all the other routes as they were. So, during testing, I can view all routes except that one /clients route that now throws the above errors.
I'm totally lost at this point and hoped somebody could help push me over the finish line. What is this new file 0.app.bundle.js and how am I supposed to be using it/including it in my application?
I hope I've explained myself clearly enough and look forward to any responses.
I managed to fix my own problem in the end, so I will share what I discovered in an answer.
The reason the chunk file wasn't loading was because Webpack was looking in the wrong directory for it. I noticed in the Network tab of my developer console that the the chunk file/module was being called from my root directory / and not in /js directory where it belongs.
As per Webpack's documentation, I added the following to my Webpack config file:
output: {
path: path.resolve(__dirname, 'dist/js'),
publicPath: "/js/", //<---------------- added this
filename: 'app.bundle.js'
},
From what I understand, path is for Webpack's static modules and publicPath is for dynamic modules.
This made the chunk load correctly but I also had further issues to deal with, as client.init() wasn't being called and yielded the following error:
TypeError: e.init is not a function
To fix this, I also had to change:
import("Controllers/clients.js").then((clients) => {
clients.init();
});
To:
import("Controllers/clients.js").then(({clients}) => {
clients.init();
});
Note the curly braces in the arrow function parameter.
I hope this helps somebody else.
For debugging, you need to do
import("Controllers/clients.js").then((clients) => {
console.log(clients);
});
maybe working
import("Controllers/clients.js").then((clients) => {
clients.default.init();
});

React Native Image Picker: Cannot read property 'showImagePicker' of undefined

I'm following the example exactly as shown in https://github.com/marcshilling/react-native-image-picker using react-native-image-picker, via terminal with react-native run-ios and coding via Atom editor.
I did npm install react-native-image-picker#latest --save and currently the dependency in package.json shows: "react-native-image-picker": "^0.22.8",
And I clicked a button to trigger the imagePicker but I am getting the error: Cannot read property 'showImagePicker' of undefined.
What am I doing wrong?
Here is the code
import ImagePicker from 'react-native-image-picker'
var Platform = require('react-native').Platform
var options = {
title: 'Select Avatar',
customButtons: [
{name: 'fb', title: 'Choose Photo from Facebook'},
],
storageOptions: {
skipBackup: true,
path: 'images'
}
}
export default class chooseImage extends Component {
constructor() {
super()
this.state = {
avatarSource: "",
}
}
_uploadImage() {
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
// You can display the image using either data...
const source = {uri: 'data:image/jpeg;base64,' + response.data, isStatic: true};
// or a reference to the platform specific asset location
if (Platform.OS === 'ios') {
const source = {uri: response.uri.replace('file://', ''), isStatic: true};
} else {
const source = {uri: response.uri, isStatic: true};
}
this.setState({
avatarSource: source
})
}
})
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight
onPress={this._uploadImage}
underlayColor='transparent'
>
<Image
source={this.state.avatarSource} style={styles.uploadAvatar}
/>
</TouchableHighlight>
</View>
)
}
}
EDIT
When I console.log(ImagePicker)
use manual installation
set permission
/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
cannot read property y of undefined means you have a statement x.y
such that x is undefined. in this case, x is ImagePicker.
My best guess is that your import statement causes the issue.
try this:
var ImagePicker = require('react-native-image-picker');
instead of
import ImagePicker from 'react-native-image-picker'
Which is also what the example suggests.
if you want to stick with the import statement,
try this:
import * as ImagePicker from 'react-native-image-picker'
Which imports the module as ImagePicker and puts it inside the scope.
For more info, see: MDN on import statement
I have been working for hours to solve this problem! Finally after adding correctly these lines in MainApplication.java it worked as a charm. Do not forget to rebuild the project.
it seems like IMagePicker is not defined.
Have you tried using
var ImagePicker = require('react-native-image-picker');
instead of the first line?
Hi there are few things that you can try: Run react-native link
Make sure you already completed this step
http://prntscr.com/hftr17
If not: your last chance is remove completely your code. Clone a new one.
I was successfully make it work by follow those.
Hope it can give you something.
Rebuild your app. Run the command react-native run-ios and react-native run-android.
Rebuilding your app will just mean you'll get the same error.
You need to go through Xcode for iOS and edit your settings.gradle manually for this to work:
https://github.com/react-community/react-native-image-picker
You don't need to do the steps for both Android and iOS, but the steps outlined for either platform are crucial
So unless you have already executed react-native link, you will need to go through each numbered steps and make sure your binaries are properly linked.
If you are using xcode and getting this error on simulator or real device make sure after installing and react link command you follow manual instructions. as described ie.
In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...> .
Go to node_modules ➜ react-native-image-picker ➜ ios ➜ select RNImagePicker.xcodeproj
Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSPhotoLibraryAddUsageDescription and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions.
Note. = RNImagePicker.a is now libRNImagePicker.a
and make sure you add this in your project build phase the lib's build phase itself.
Then you may compile and run it.
Note :
After installation you have to restart the project as react-native run-ios or
react-native run-android
May be u installed the picker but didn't restart the packager
: )
If you are using xcode and getting this error on simulator or real device make sure after installing and react link command you follow manual instructions. as described ie.
In the XCode's "Project navigator", right click on your project's Libraries folder ➜ Add Files to <...> .
Go to node_modules ➜ react-native-image-picker ➜ ios ➜ select RNImagePicker.xcodeproj
Add RNImagePicker.a to Build Phases -> Link Binary With Libraries
For iOS 10+, Add the NSPhotoLibraryUsageDescription, NSCameraUsageDescription, NSPhotoLibraryAddUsageDescription and NSMicrophoneUsageDescription (if allowing video) keys to your Info.plist with strings describing why your app needs these permissions.
Note. = RNImagePicker.a is now libRNImagePicker.a and make sure you add this in your project build phase the lib's build phase itself.
Then you may compile and run it.
As per your first comment you mentioned that you are not using Xcode you are using Atom and Terminal. In most of the cases only npm install will be enough but there are some platform specific cases that can be achieved either by linking it using react-native link or by following the manual installation steps provided in the document. if you are not using Xcode then its not possible for you to link this library completely for IOS platform. Make sure you use Xcode and follow the manual steps or else react-native link to solve your issue.
I had the same problem and in iOS it was due to the permission missing, even in the simulator. See the permissions here:
https://github.com/react-native-community/react-native-image-picker/blob/master/docs/Install.md
I just missed "NSPhotoLibraryAddUsageDescription" and it was enough to get the "Cannot read property 'showImagePicker' of undefined" error.

Categories

Resources