Using Web3.js in VueJS - Error: undefined is not a constructor or null - vue.js

I'm using VueJs + Webpack and trying to get Web.js to work.
I installed web.js using npm npm install web3 --save and I'm trying to use it in one of my VueJS components by importing it using import Web3 from 'web3'.
When I load my application I get an error:
app.js:101191 Uncaught TypeError: Class extends value undefined is not a constructor or null
at module.exports (app.js:101191)
at module.exports (app.js:101155)
at Object../node_modules/keccak/js.js (app.js:101140)
at __webpack_require__ (app.js:200063)
...
My package.json looks like:
"private": true,
"scripts": {
...
},
"devDependencies": {
...
},
"dependencies": {
...
"web3": "^1.3.6"
}
Do I need to import it using webpack?

Related

Adding a plugin to vite

I am trying out Vite and using it to develop a Vue app with Prismic Cms. In reading Prismic Doc's I see have to install dependencies
npm install #prismicio/vue #prismicio/client prismic-dom
Doc's then say you have to register it:
To use #prismicio/vue, you must register it in your app entry point, which is most likely ~/src/main.js.
The access token and API options are only necessary if your repo is set to private.
// `~/src/main.js`
import Vue from 'vue'
import App from './App'
import PrismicVue from '#prismicio/vue'
import linkResolver from './link-resolver' // Update this path if necessary
const accessToken = '' // Leave empty if your repo is public
const endpoint = 'https://your-repo-name.cdn.prismic.io/api/v2' // Use your repo name
// Register plugin
Vue.use(PrismicVue, {
endpoint,
apiOptions: { accessToken },
linkResolver
})
In reading Vite doc's I see you add plugins via the vite.config.js file instead of using Vue.use() in main.js. So I created one as follows:
import { defineConfig } from "vite";
import Vue from "#vitejs/plugin-vue";
import PrismicVue from "#prismicio/vue";
import linkResolver from "./link-resolver"; // Update this path if necessary
const accessToken = ""; // Leave empty if your repo is public
const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
Vue(),
PrismicVue({
endpoint,
apiOptions: { accessToken },
linkResolver,
}),
],
});
However I get error as follows:
failed to load config from C:\Users\akill\Github\shs\vite.config.js
error when starting dev server:
TypeError: (0 , import_vue.default) is not a function at Object.<anonymous> (C:\Users\akill\Github\shs\vite.config.js:53:28)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.require.extensions.<computed> [as .js]
(C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76005:20)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at loadConfigFromBundledFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:76013:17)
at loadConfigFromFile (C:\Users\akill\Github\shs\node_modules\vite\dist\node\chunks\dep-98dbe93b.js:75932:32)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! shs#0.0.0 dev: `vite --open`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the shs#0.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
I also notice VS Code is giving me a hint # import of PrismicVue line of
Could not find a declaration file for module '#prismicio/vue'. 'c:/Users/akill/Github/shs/node_modules/#prismicio/vue/dist/prismic-vue.common.js' implicitly has an 'any' type.
I have isolated it to the line "PrismicVue({endpoint,apiOptions: { accessToken }, Etc....})," causing the error. Can someone explain what is the proper way to import this plugin in Vite? Thanks in advance.
vite.config.js's plugins property is intended for Vite plugins, which are for Vite itself (e.g., adding a custom transform for specific file types). That config is not for Vue plugins, which can only be installed in a Vue 3 app with app.use().
To setup Prismic with Vue 3:
Install the following dependencies. The alpha versions of #prismicio/vue and #prismicio/client (3.x and 6.x, respectively) are needed for Vue 3 support.
npm i -S #prismicio/vue#alpha #prismicio/client#alpha prismic-dom
Create a link resolver that returns a route path based on a given Prismic document type. The resolved route path should already be registered in router.js:
const resolver = doc => {
if (doc.isBroken) {
return '/not-found'
}
if (doc.type === 'blog_home') {
return '/blog'
} else if (doc.type === 'post') {
return '/blog/' + doc.uid
}
return '/not-found'
}
export default resolver
In src/main.js, use createPrismic() from #prismic/vue to create the Vue plugin, and pass that along with the link resolver to app.use():
import { createApp } from 'vue'
import { createPrismic } from '#prismicio/vue'
import linkResolver from './prismic/link-resolver'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.use(createPrismic({
endpoint: 'https://blog-demo2.prismic.io/api/v2',
linkResolver,
}))
.mount('#app')
demo
You probably have a mess in your setup / package.json as there is nothing special to do - I bet that you are missing vite-plugin-vue2 and vue-template-compiler.
To get it working, try to create a new project with the following :
vite.config.js:
const { createVuePlugin } = require('vite-plugin-vue2');
module.exports = {
plugins: [
createVuePlugin()
]
};
main.js:
import Vue from 'vue';
import App from './App.vue';
import PrismicVue from "#prismicio/vue";
const accessToken = ""; // Leave empty if your repo is public
const endpoint = "https://*******-****.cdn.prismic.io/api/v2"; // Use your repo name
Vue.use(PrismicVue, {
endpoint: endpoint
});
new Vue({
render: (h) => h(App),
}).$mount('#app');
App.vue:
<template>
<div id="app">
<img
alt="Vue logo"
src="./assets/logo.png"
/>
</div>
</template>
<style>
#app {
text-align: center;
}
</style>
then package.json:
{
"name": "vue2-prismic",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
},
"dependencies": {
"#prismicio/client": "^5.1.0",
"#prismicio/vue": "^2.0.11",
"prismic-dom": "^2.2.6",
"vite-plugin-vue2": "^1.4.0",
"vue": "^2.6.12",
"vue-template-compiler": "^2.6.14"
},
"devDependencies": {
"vite": "^2.0.5"
}
}

Babel - VueJS | Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. In

i tried to install preset-env for using environment variables. After that, my VueJS project got an error, i tried npm r #babel/preset-env, i tried npm i --save #babel-core but nothing changed. Any thoughts?
{
"presets": [
["env", { "modules": false }],
"stage-3",
],
"plugins": [["transform-runtime", { "polyfill": false, "regenerator": true }]]
}
Problem solved with using Babel version from vue.js webpack template repository.
npm r babel-core
add "babel-core": "^6.22.1" to package.json
npm i

Not able to work with peer dependency in react native

I have one react-native app in which I am using "json-schema-rules" library. Now I have also created one library which is getting used in my react-native app like this "file:../custom_library" in package.json.
Now to resolve the version conflict, I decided to use "json-schema-rules" as a peer dependency in my custom library. So, the package.json is like this
Package.json of my react-native app:
{
"dependencies": {
"json-rules-engine": "^2.3.0",
"custom_library": "file:../custom_library"
}
}
package.json of my custom_library:{
"peerDependencies": {
"json-schema-rules": "^2.3.0"
}
}
Now the problem is, whenever I am using metro bundler, I get an error
error: bundling failed: Error: Unable to resolve module json-rules-engine
json-rules-engine could not be found within the project.
This is the case when I am using it in peerDependencies, I do not get any error if I use this library in dependencies.
Please help.
You can try to add an alias for the module in your project's babel config.
This means that when your custom packages tries to import "json-rules-engine" it will get served the version from the main app.
First install 'babel-plugin-module-resolver' then configure the alias in "module-resolver"
babel.config.js
const config = {
presets: ["module:metro-react-native-babel-preset"],
plugins: [
[
"module-resolver",
{
root: ["./src"],
extensions: [".js", ".jsx", ".ios.js", ".android.js"],
alias: {
"json-rules-engine": require.resolve("json-rules-engine")
}
}
]
]
};
module.exports = config;

Error Angular 5 + NGX_Restangular + Webpack-dev-server

Using Angular 5 + NGX_Restangular + Webpack-dev-server
Angular 5
"ngx-restangular": "2.2.3"
"webpack": "4.5.0",
"webpack-dev-server": "3.1.3"
Success building application and starting web server = ng serve
Failure running application on web server using webpack after running ng eject
npm start
npm start = '"start": "webpack-dev-server --port=4200"'
Chrome Console:
core.js:1448 ERROR Error: Uncaught (in promise): TypeError: _.isArray is not a function
TypeError: _.isArray is not a function
at RestangularFactory (ngx-restangular.config.js:11)
at _callFactory (core.js:10916)
at _createProviderInstance$1 (core.js:10868)
at resolveNgModuleDep (core.js:10850)
at _createClass (core.js:10895)
at _createProviderInstance$1 (core.js:10865)
at resolveNgModuleDep (core.js:10850)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/esm5/core.js.NgModuleRef_.get (core.js:12087)
at resolveNgModuleDep (core.js:10854)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/esm5/core.js.NgModuleRef_.get (core.js:12087)
at RestangularFactory (ngx-restangular.config.js:11)
at _callFactory (core.js:10916)
at _createProviderInstance$1 (core.js:10868)
at resolveNgModuleDep (core.js:10850)
at _createClass (core.js:10895)
at _createProviderInstance$1 (core.js:10865)
at resolveNgModuleDep (core.js:10850)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/esm5/core.js.NgModuleRef_.get (core.js:12087)
at resolveNgModuleDep (core.js:10854)
at NgModuleRef_.webpackJsonp../node_modules/#angular/core/esm5/core.js.NgModuleRef_.get (core.js:12087)
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at zone.js:873
at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4740)
at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
This only happens when I inject restangular and using webpack-dev-server.
import { Component, OnInit} from '#angular/core';
import { Restangular } from 'ngx-restangular';
#Component({
selector: 'app-onenote-open',
templateUrl: './onenote-open.component.html',
styleUrls: ['./onenote-open.component.scss']
})
export class OnenoteOpenComponent implements OnInit {
constructor(#Inject(Restangular) public xxx) { }
ngOnInit() {
}
}
There appears to be a problem with ngx-restangular 2.2.3 and ng ejects > webpack.config.js
Problem solved by using package.json > "ngx-restangular": "2.3.0-beta.3"

Running Jest tests in Vue.js

Basically, the component isn't getting compiled, so I get an Unexpected token < error when it runs into <template>
I've run the following commands:
$ npm install --save-dev jest
$ npm install --save-dev vue-jest
$ npm install --save-dev vue-test-utils
and I've out the following in package.json:
"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js",
"test": "jest"
},
...
"jest": {
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/vue"
],
"moduleFileExtensions": [
"js",
"vue"
],
"scriptPreprocessor": "index.js"
}
I created a __test__ folder in the root directory with a simple test:
const Vue = require("vue");
const VueTestUtils = require("vue-test-utils");
Vue.config.debug = true;
Vue.config.async = false;
Vue.use(VueTestUtils.install);
import Hello from '../src/components/Hello.vue'
const Constructor = Vue.extend(Hello)
const vm = new Constructor().$mount()
describe('initial test', () => {
it('should be 1', () => {
expect(1).toBe(1)
})
})
I recently got this error as well, and not quite sure how to configure Vue.js so it will run using the compiler-included build:
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Been looking around for a while, so any help would be appreciated
You need to use a Jest transform to transform Jest Vue files. A Jest transformer is a synchronous function, that takes the file and path as input and outputs transpiled code.
I maintain a npm package that does it for you - vue-jest.
npm install --save-dev vue-jest
You need to add a jest section to your package.json (or in a seperate file with --config). Your config should look something like this:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "babel-jest",
".*\\.(vue)$": "vue-jest"
}
}
This tells jest to use jest-vue as a transform for files with a .vue extension.
You can see a working repo using Vue Test Utils here - https://github.com/eddyerburgh/vue-test-utils-jest-example