How to Hide API key in Preact? - api

How can i hide api key in preact , in react i used .env file , but don't know how to do it in preact ?
index.js?2e9b:8 Uncaught (in promise) ReferenceError: process is not defined
at eval (index.js?2e9b:8)
at Generator.next (<anonymous>)
at asyncGeneratorStep (index.js:5)
at _next (index.js:7)
at eval (index.js:7)
at new Promise (<anonymous>)
at eval (index.js:7)
at getSeriesInfo (index.js?2e9b:7)
at Object.eval [as __] (index.js?2e9b:14)
at j (index.js?a178:361)

Preact is just a UI library, but I'll assume you're referring to Preact-CLI, which is an actual build tool. Let me know if this is incorrect.
Our wiki covers this under "Use Environment Variables in your Application". process will not exist outside of Node so you'll need to specify the variables you want to use using DefinePlugin.
Add the following to your preact.config.js file:
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify('my-value'),
}),
);
};
If you specifically want to read from a .env file, you will also need to add some utility to read it, such as dotenv:
import dotenv from 'dotenv';
dotenv.config();
export default (config, env, helpers) => {
config.plugins.push(
new helpers.webpack.DefinePlugin({
'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE),
}),
);
};

Related

metro error 'crypto', package itself specifies a `main` module field that could not be resolved, react-native and open api

running react native with ios simulator.
the backend uses open api, and has a folder in FrontEnd, to enforce schemas. I'm calling a class from this openapi auto generated file Frontend/sdk/api.ts.
in my frontend/service/doSomething.ts,
import { DefaultApi } from '../sdk/api // in frontend, autogenerated by open API
function func1 () {
const api = new DefaultApi() // calls crypto somehow
}
on build, i get this error
BUNDLE ./index.js
error: Error: While trying to resolve module `crypto` from file
`/app/node_modules/request/lib/helpers.js`, the package
`/app/node_modules/crypto/package.json` was successfully found.
However, this package itself specifies a `main` module field that
could not be resolved (`/app/node_modules/crypto/index.js`. Indeed,
none of these files exist:
* /app/node_modules/crypto/index.js(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.json|.native.json|.json)
* /app/node_modules/crypto/index.js/index(.native|.ios.jsx|.native.jsx|.jsx|.ios.js|.native.js|.js|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx|.ios.json|.native.json|.json)
at DependencyGraph.resolveDependency (/app/node_modules/metro/src/node-haste/DependencyGraph.js:311:17)
at Object.resolve (/app/node_modules/metro/src/lib/transformHelpers.js:129:24)
at resolve (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:396:33)
at /app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:412:26
at Array.reduce (<anonymous>)
at resolveDependencies (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:411:33)
at processModule (/app/node_modules/metro/src/DeltaBundler/traverseDependencies.js:140:31)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async addDependency (/node_modules/metro/src/DeltaBundler/traverseDependencies.js:230:18)
at async Promise.all (index 2)
Failed: I've tried following However, this package itself specifies a `main` module field that could not be resolved adding to metro.config.js
resolver: {
sourceExts: ['jsx', 'js', 'ts', 'tsx'], //add here
}
but it FAILS with same error.
the request package and crypto has been deprecated.

Nuxt, VueJS This must be called within a setup function

I've got a project. It's currently available on a certain website. I need to implement some changes. When I download a project from gitlab and run it throws me an error:This must be called within a setup function.
path: .nuxt/composition-api/index.js
const useContext = () => {
const vm = CompositionApi.getCurrentInstance();
if (!vm)
throw new Error("This must be called within a setup function.");
return {
...(vm[globalNuxt] || vm.$options).context,
route: CompositionApi.computed(() => vm.$route),
query: CompositionApi.computed(() => vm.$route.query),
What is wrong?
I need to run the project to make some changes but can't deploy it on my local server.
Update:
useContex is in default.vue
...
setup (_, { isServer, refs }: any) {
// console.info(context)
// const refs = context.refs
const { store } = useContext()
const { scrolllock } = scrollLock(store)
const locationName = computed(() => store.getters.locationName)
const location = computed({
set (val: boolean) {
store.dispatch('setLocationModal', val)
},
get () {
return store.getters.locationModal
}
})
...
cmd output when I'm trying to go the site
[Vue warn]: [vue-composition-api] already installed. Vue.use(VueCompositionAPI) should be called only once.
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:04
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:05
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:24
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
From my experience, npm can't install #nuxtjs/composition-api older versions, or stuff like that, so I did uninstall its older version and install the new version and it's worked
here is what I've done
rm -rf node_modules && rm -rf package-lock.json && npm uninstall #nuxtjs/composition-api && npm i #nuxtjs/composition-api && npm i
From the look of things, it seems you
You created another plugin for the VueCompositionAPI when it is installed already e.g #nuxtjs/composition-api
I would advise you to remove any other composition-api from your project and stick to the latest version of the official #nuxtjs/composition-api with Vuex v4 for Nuxt 2
In the latest version of #nuxtjs/composition-api, you could use
const store = useStore();
// OR
const { store } = useContext();
NOTE: You have to define the helper functions like const router = useStore() directly inside your setup() function, and not inside your method, to avoid This must be called within a setup function error.
For those that want to use route
To smooth your upgrade to Nuxt 3, it is recommended not to access route, query, from and params from useContext but rather to use the useRoute helper function.
I don't know what happened there. I deleted that repository and cloned it again.
Next up I did this:
npm init
and then
npm run dev
And it works.

SSR build says "document is not defined" for a Vuejs cli3 SPA app using a Vue cli3 library

I have a fairly complex SPA Vue.js app created with Vue CLI v3. I want to transform this app to benefit from SSR (although I might end up using only preprendering...)
My app is using custom Vuejs libraries created with the CLI v3 as well. These libs embbed CSS, and I would like to continue to do so.
I've probably read everything that the world has produced on Vue cli, vue-loader, vue-style-loader, vue.config.js, extract css etc, but I keep failing.
Here is the error message of my running app when I load a given route:
ReferenceError: document is not defined
at addStyle (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:699:22)
at addStylesToDom (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:683:20)
at addStylesClient (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:637:3)
at Object.3351 (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:500:14)
at __webpack_require__ (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:21:30)
at Object.d12e (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:3590:380)
at __webpack_require__ (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:21:30)
at Module.fae3 (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:3859:51)
at __webpack_require__ (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:21:30)
at /Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:85:18
at Object. (/Users/onekiloparsec/code/my-app/node_modules/vue-custom-lib/dist/vue-custom-lib.common.js:88:10)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
When clicking the first line of the error, I get the following code from the commonjs file of my lib:
function addStyle (obj /* StyleObjectPart */) {
var update, remove
var styleElement = document.querySelector('style[' + ssrIdKey + '~="' + obj.id + '"]')
...
I don't know if I need to change things in my lib (I think so) or in my app, or both.
Here is the vue.config.js of my lib:
module.exports = {
css: {
extract: false
}
}
But I also tried extract: true and (a lot) more sophisticated stuff.... I get always the same error.
Is there a way to integrate Vue cli 3 lib with CSS into a SSR Vue app??? Thanks a lot.
You experienced this error because when the application is building process is done on the server-side where no document exists. You can append an element to document styles by finding an element with querySelector:
var styleElement = document.querySelector('style[' + ssrIdKey + '~="' + obj.id + '"]')
only when JavaScript append to the page is interpreted by the browser (no node js).
You have two options in this case:
Manage styling on the server-side (you can't use `document)
Manage styling on the client-side (you can use document)
In option 1 - server-side you will probably resign from using your vue-custom-lib package or create a fork that checks if the environment is browser or node js. Eg.:
if(process) { you are in node js }
if(window) { you are in the browser - you can use the document.querySelector }
In option 2 I recommend you check Nuxt.
You can add a package with document in head.script property in nuxt.config.js
export default {
head: {
script: [
{ src: '...' }
]
},
you should also read about detecting server and client-side in the Nuxt context
https://nuxtjs.org/api/context/
Configuration build that has also the property isServer:
https://nuxtjs.org/api/configuration-build
Appending your custom library can be done also in renderAndGetWindow function
https://nuxtjs.org/api/nuxt-render-and-get-window

Vuetify & Webpack Encore compilation error

I created (currently standalone) and API and a VueJs (with Vuetify) App and wanted to combine both using the webpack encore bundle for Symfony.
But when I want to build the frontend app, I get this error when executing yarn run encore dev:
(node:12500) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
at items.forEach.item (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:21:60)
at Set.forEach (<anonymous>)
at Object.getMatches (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:16:9)
at Object.module.exports (/Users/pguetschow/Projects/hosting-tool/node_modules/vuetify-loader/lib/loader.js:106:64)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:12500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This is my webpack.config.js
const Encore = require('#symfony/webpack-encore');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.addEntry('js/main', './assets/js/main.js')
.enableVueLoader()
.enableBuildNotifications(true)
.addPlugin(new VuetifyLoaderPlugin())
;
module.exports = Encore.getWebpackConfig();
Any idea? The standalone app is working fine, I simply moved it to the assets/js folder. I require vuetify-loader ^1.2.2 for this.
And this is my main.js:
import Vue from 'vue'
import App from './App.vue'
import Vuetify from 'vuetify/lib'
import MultiFiltersPlugin from './plugins/MultiFilters'
import 'vuetify/src/stylus/app.styl'
import 'material-design-icons-iconfont/dist/material-design-icons.css'
import 'vuetify/dist/vuetify.min.css'
Vue.use(MultiFiltersPlugin);
Vue.use(Vuetify, {
iconfont: 'md',
});
new Vue({render: h => h(App),}).$mount('#app');
Here's an example webpack.config.js file from this working example that shows how to get Symfony and Vuetify (v.2x) to play nice together:
var Encore = require('#symfony/webpack-encore');
// import vuetify-loader as a plugin here
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin')
if (!Encore.isRuntimeEnvironmentConfigured()) {
Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}
Encore
.setOutputPath('public/build/')
.setPublicPath('/build')
.enableVueLoader() // <-- IMPORTANT: this loads Vue
// NOTE: I put my Vue app in assets/vue which I think is non-standard
// but it allows me to structure my Vue app as I would in a non-Symfony app
.addEntry('app', './assets/vue/main.js')
.splitEntryChunks()
.enableSingleRuntimeChunk()
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
.configureBabel(() => {}, {
useBuiltIns: 'usage',
corejs: 3
})
// add VuetifyLoaderPlugin: THIS loads all of the Vuetify components
.addPlugin(new VuetifyLoaderPlugin())
// enables Sass/SCSS support
.enableSassLoader(options => {
options.implementation = require('sass')
options.fiber = require('fibers')
})
;
module.exports = Encore.getWebpackConfig();
Caveat, I'm not really a symfony developer, but this worked for me. HTH!

How to mock react native I18nManager

I am trying to run jest cases in react native. I am using react-native-router-flux for navigation. My test cases are being failed with this error
Test suite failed to run
TypeError: Cannot read property 'isRTL' of undefined
at Object.<anonymous> (node_modules/react-native-router-flux/dist/NavBar.js:286:44)
at Object.<anonymous> (node_modules/react-native-router-flux/dist/navigationStore.js:7:13)
at Object.<anonymous> (node_modules/react-native-router-flux/dist/Reducer.js:74:36)
Exact line is transform:[{scaleX:_reactNative.I18nManager.isRTL?-1:1}]})
I tried different ways to mock but could not get it
One method is
import {I18nManager} from 'react-native'
I18nManager = {
isRTL : false
}
I put this snippet in jest initial configuration file but I got error like I18nManager is readonly
Actually I am using an explicit module factory that is being run instead of using Jest's automocking feature which is react-native-mock-render .
Like this
jest.mock('react-native', () => require('react-native-mock-render'), {
virtual: true
})
When I go through this lib code I could not found I18nManager in the mocks. So I forked that repo and added I18nManager file myself.