In a vue cli application, scss global variables are injected by webpack chain, or simply using vue.config.js as I did in below.
let data = require('./public/content.json')
let color = data.app.skin.color
module.exports = {
css: {
loaderOptions: {
sass: {
data: `
$font: 'my font';
$host: 'example.com';
$turquaz: ${color.turquaz};
$green: ${color.green};
$green_dark: ${color.green_dark};
$green_darker: ${color.green_darker};
$yellow: ${color.yellow};
$yellow_dark: ${color.yellow_dark};
$yellow_darker: ${color.yellow_darker};
$red: ${color.red};
$red_dark: ${color.red_dark};
$red_darker: ${color.red_darker};
$white: ${color.white};
$grey: ${color.grey};
$dark: ${color.dark};
$dark_overlay: ${color.dark_overlay};
#import '#/styles/main.scss';
`
}
}
}
}
But users decided to get data by an API. So I tried to make a get request to server by axios like below:
const Axios = require('axios')
Axios.get(`api.example.com`)
.then(response => {
let color = response.data.app.skin.color
module.exports = {
css: {
loaderOptions: {
sass: {
data: `
$font: 'my font';
$host: 'example.com';
$turquaz: ${color.turquaz};
$green: ${color.green};
$green_dark: ${color.green_dark};
$green_darker: ${color.green_darker};
$yellow: ${color.yellow};
$yellow_dark: ${color.yellow_dark};
$yellow_darker: ${color.yellow_darker};
$red: ${color.red};
$red_dark: ${color.red_dark};
$red_darker: ${color.red_darker};
$white: ${color.white};
$grey: ${color.grey};
$dark: ${color.dark};
$dark_overlay: ${color.dark_overlay};
#import '#/styles/main.scss';
`
}
}
}
}
}).catch(error => console.error(error))
This way, data is present but not exported, or chained by webpack.
Is there a way to perform this action ?
Thanks in advance.
Related
i have a problem with passing generated nonce into my layout.ejs in koa, helmet.
const directives = helmet.contentSecurityPolicy.getDefaultDirectives()
delete directives['form-action']
directives['script-src'] = [
"'self'",
CTFS_BASE_URI,
'https://cdn.cookielaw.org',
(req, res) => {
return `'nonce-${res.locals.cspNonce}'`
}
]
const pHelmet = promisify(
helmet({
contentSecurityPolicy: {
useDefaults: false,
directives
}
})
)
provider.use(async (ctx, next) => {
const origSecure = ctx.req.secure
ctx.req.secure = ctx.request.secure
// eslint-disable-next-line no-unused-expressions
ctx.res.locals || (ctx.res.locals = {})
ctx.res.locals.cspNonce = crypto.randomBytes(16).toString('base64')
await pHelmet(ctx.req, ctx.res)
ctx.req.secure = origSecure
return next()
})
render(provider.app, {
cache: false,
viewExt: 'ejs',
// TODO(#ct): comment layout if you don't want to use it.
layout: '_layout',
root: path.join(__dirname, 'views')
})
My configuration looks like this. provider variable is oidc-provider library.
helmet is from "helmet" and not from "koa/helmet" i tried "koa/helmet" but it doesn't work either.
I am trying to generate nonce and save it into my ctx.res.local.cspNonce. That part works as expected. Then in my _layout.ejs i want to use cspNonce in my script with
<script src="flksdjfsal" <%= locals.cspNonce%>
But it doesn't work. cspNonce variable is empty.
Configuration is from this example https://github.com/panva/node-oidc-provider/blob/main/certification/oidc/index.js
Can someone help me? Thanks
I'm trying to display a background image that it's path needs to be loaded through an API.
The plan is: From a main grid of links, click one and display a background image according to the one clicked.
As of now I am using axios to query my API which sends the data I need. I have the following script part on my component.
<script>
import axios from 'axios'
const lhost = require("#/config/global").host;
let championData;
export default {
name: 'IndividualChampion',
props: {
},
data: () => ({
champions: [],
verPersonagem: mdiMovieOpen,
}),
computed: {
},
created: async function() {
try {
let champion = this.$route.fullPath.split('/')[2];
let response = await axios.get(lhost + "/champion/" + champion + '/full');
championData = response.data
console.log(championData)
let background = '#/assets' + championData['skins']['0']['splash'].replace('.png','.jpg')
}
catch (e) {
return e;
}
},
methods: {
}
}
</script>
And this is my HTML
<template>
<div :style="{ backgroundImage: `url(${require(background)})` }">
</div>
</template>
I have searched but can't seem to find a solution in which the background image is loaded and, when loaded, is presented.
Can someone help?
Judging from your use of '#/assets', you seem to be using webpack with a resolve alias. The expression require(background) is not enough for webpack to determine what files it needs to add to your bundle.
You can help Webpack by specifying the directory that you want to load your file from. All you have to do is take out '#/assets/' from the background variable and use it directly in the require call so that Webpack can see it.
<template>
<div v-if="background" :style="{ backgroundImage: `url(${require('#/assets/' + background)})` }">
</div>
</template>
<script>
import axios from 'axios'
const lhost = require("#/config/global").host;
let championData;
export default {
name: 'IndividualChampion',
props: {
},
data: () => ({
champions: [],
verPersonagem: mdiMovieOpen,
background: ''
}),
computed: {
},
created: async function() {
try {
let champion = this.$route.fullPath.split('/')[2];
let response = await axios.get(lhost + "/champion/" + champion + '/full');
championData = response.data
console.log(championData)
this.background = championData['skins']['0']['loading'].replace('.png','.jpg')
}
catch (e) {
return e;
}
},
methods: {
}
}
</script>
It will bundle every possible file inside the directory, though.
You can read more about it here: https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import
I have a create react app 3 project,
so I have in my src folders some js scripts using like:
import { Foo } from 'components/layout/Foo
Unfortunately, the testcafe compiler complains about it by default.
I read that maybe the solution was to create specify a custom tsconfig.json in which I declare
{
"compilerOptions": {
"baseUrl: "src"
}
}
But it does not work, apparently.
Thanks.
Sorry, indeed it is not a component file, but a utils one in the src directory.
in my foo_test.js I have
import { ROOT_PATH } from '../src/utils/config'
fixture("00 Home | Arriving to the Home").page(ROOT_PATH)
test('Default | leads to the home page', async t => {
const location = await t.eval(() => window.location)
await t.expect(location.pathname).eql('/home')
})
where utils/config is
import { getMobileOperatingSystem } from 'utils/mobile'
export const MOBILE_OS = getMobileOperatingSystem()
let CALC_ROOT_PATH
if (MOBILE_OS === 'ios') {
document.body.className += ' cordova-ios'
CALC_ROOT_PATH = window.location.href.match(/file:\/\/(.*)\/www/)[0]
}
export const ROOT_PATH = CALC_ROOT_PATH || 'http://localhost:3000/'
I have setup an angular2 / Electron app similar to the explanation in this video : https://www.youtube.com/watch?v=pLPCuFFeKOU. The project I am basing my code on can be found here : https://github.com/rajayogan/angular2-desktop
I am getting the error:
app.ts:16Uncaught TypeError: Cannot read property 'on' of undefined
When I try to run this code:
import { bootstrap } from '#angular/platform-browser-dynamic';
import { Component } from '#angular/core';
import { MenuComponent} from './menu';
import { ConfigEditorComponent } from './config-editor';
import { remote, ipcRenderer} from 'electron';
let {dialog} = remote;
//Functions used for select server xml callbacks.
const ipc = require('electron').ipcMain
const xml2js = require('xml2js')
const fs = require('fs')
var parser = new xml2js.Parser();
ipc.on('open-file-dialog', function (event) {
dialog.showOpenDialog({
title:"Select zOS Connect server.xml",
properties: ['openFile', 'openDirectory'],
filters: [
{name: 'XML', extensions: ['xml']},
{name: 'All Files', extensions: ['*']}
]
}, function (files) {
if (files){
fs.readFile(files[0], function(err, data) {
parser.parseString(data, function (err, result) {
console.dir(result);
process_server_xml(event,result);
})
})
}
})
})
function process_server_xml(event,json){
console.log("oh hello!")
event.sender.send('selected-directory', json)
console.log("oh im done!")
}
#Component({
selector: 'connect-toolkit',
templateUrl: 'app.component.html',
directives: [ MenuComponent, ConfigEditorComponent ]
})
export class AppComponent {
constructor() {
var menu = remote.Menu.buildFromTemplate([{
label: 'Raja',
submenu: [
{
label: 'open',
click: function(){
dialog.showOpenDialog((cb) => {
})
}
},
{
label: 'opencustom',
click: function(){
ipcRenderer.send('open-custom');
let notification = new Notification('Customdialog', {
body: 'This is a custom window created by us'
})
}
}
]
}])
remote.Menu.setApplicationMenu(menu);
}
}
bootstrap(AppComponent);
I think the problem may be:
const ipc = require('electron').ipcMain
const xml2js = require('xml2js')
const fs = require('fs')
var parser = new xml2js.Parser();
Is it possible require doesn't work here, and somehow I need to use import statements instead from my ts files? If this is the case how do I use the import in order to get the ipcMain object and my xml2js etc?
Why would that be the case? How can I make require work within the ts files if this is the problem.
Note that if I remove the require lines, and all the ipc.on code everything runs as expected and works fine (other than the fact that the ipc event is never received ;)
Calling ipcMain doesn't work because you're not on main (i.e., the electron side code, which is on electron index.js file), your are on renderer (web page). Therefore you must use ipcRenderer instead, which is already imported using es6 import syntax on top of your app.ts file. And if you want to make something using electron ipcMain, it have to be done from the electron code side.
import {remote, ipcRenderer} from 'electron';
Electron ipc notes:
ipcMain Communicate asynchronously from the main process to renderer processes.
ipcRenderer Communicate asynchronously from a renderer process to the main process.
I am trying to write a demo isomorphic Cycle.js/Hapi.js app, but it fails with an exception in xstream while rendering on the server. What is going wrong here? I've based my app on Cycle.js' isomorphic app example.
The traceback looks like this:
TypeError: Uncaught error: s[i]._add is not a function
at CombineProducer._start (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:190:22)
at Stream._add (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:976:19)
at MapOperator._start (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:717:18)
at Stream._add (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:976:19)
at LastOperator._start (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:596:18)
at Stream._add (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:976:19)
at Stream.addListener (/Users/arve/Projects/hapi-cycle/node_modules/xstream/core.js:1050:14)
at Object.streamSubscribe (/Users/arve/Projects/hapi-cycle/node_modules/#cycle/xstream-adapter/lib/index.js:39:16)
at /Users/arve/Projects/hapi-cycle/node_modules/#cycle/base/lib/index.js:49:30
at Array.map (native)
The render code looks basically as follows:
import Cycle from '#cycle/xstream-run'
import xs from 'xstream'
import {html, section, h1, p, head, title, body, div, script, makeHTMLDriver,} from '#cycle/dom'
import serialize from 'serialize-javascript'
import Logger from '#arve.knudsen/js-logger'
let logger = Logger.get('server.rendering')
let wrapVTreeWithHtmlBoilerplate = ([vtree, context,]) => {
return (
html([
head([
title('Cycle Isomorphism Example'),
]),
body([
div('.app-container', [vtree,]),
script(`window.appContext = ${serialize(context)};`),
// script(clientBundle),
]),
])
);
}
let main = (sources) => {
let vtree = (
section('.home', [
h1('The homepage'),
p('Welcome to our spectacular web page with nothing special here.'),
])
)
return {
DOM: vtree,
}
}
let renderIndex = (request, reply) => {
let context = xs.of({})
Cycle.run((sources) => {
let vtree = main(sources).DOM
let wrappedVTree = xs.combine(vtree, context)
.map(wrapVTreeWithHtmlBoilerplate)
.last()
return {
DOM: wrappedVTree,
};
}, {
DOM: makeHTMLDriver((html) => {
let wrappedHtml = `<!doctype html>${html}`
}),
context: () => {return context},
PreventDefault: () => {},
})
}
You can find the full source code here.
I'm running on OS X using Node v6.6.0, babel-node 6.14.0, Hapi 15.0.3, #cycle/dom 12.2.5 and #cycle/xstream-run 3.1.0. Let me know if you need more info.
The reason for the error was that the rendered VTree was not a stream. I changed the code to the following and it works:
let vtree = sources.context.map(({}) => {
return (
section('.home', [
h1('The homepage'),
p('Welcome to our spectacular web page with nothing special here.'),
])
)
})
return {
DOM: vtree,
}
The sources.context.map call (which I borrowed from the original isomorphic example) ensures that vtree is a stream.