Import json data as sass variables in an .scss file Nuxt - vue.js

I'm trying to import json varialbes in a scss file so i can have them defined in 1 place and later use them in both scss and js.
The application is vue/nuxt
Have tried many variants but without success
Here is my code
src/assets/scss/test.json
{
"danger": "#cc3333",
"info": "#3399ff",
"success": "#33cc99",
"warning": "#ffcc00"
}
src/assets/scss/main.scss
#import "./test.json";
body {
background-color: $info;
}
nuxt.config.js
const jsonImporter = require('node-sass-json-importer');
module.exports = {
css: [
'#/assets/scss/main.scss',
],
...
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend (config, ctx) {
ctx.loaders.sass.sassOptions.importer = jsonImporter
console.log(ctx.loaders.sass.sassOptions)
}
}
}
Gives me error
Module build failed (from ./node_modules/sass-loader/dist/cjs.js): friendly-errors 17:22:43
SassError: Invalid CSS after "{": expected 1 selector or at-rule, was "{"
on line 1 of assets/scss/test.json
from line 1 of C:\Users\Fluksikarton\Desktop\nuxt-webserotonin-template\assets\scss\main.scss
>> {
extend (config, ctx) {
console.log(ctx.loaders.scss)
ctx.loaders.scss.scssOptions = {};
ctx.loaders.scss.scssOptions.importer = jsonImporter()
}
Gives
ValidationError: Invalid options object. Sass Loader has been initialised using an options object that does not match the API schema.
- options has an unknown property 'importer'. These properties are valid:
object { implementation?, sassOptions?, prependData?, sourceMap?, webpackImporter? }

Default export from node-sass-json-importer is a factory function, not the importer itself.
Also you are using SCSS not SASS ....
Change it to this: ctx.loaders.scss.sassOptions.importer = jsonImporter()

Related

Call SQL linter's API from Codemirror with Typescript

I am trying to call an API to lint a SQL query written in Codemirror (actually I use Angular and the wrapper ngx-codemirror)
Unfortunately, I could not call the API because this is considered undefined:
data-analyzer.component.html:81 ERROR TypeError: Cannot read property 'analyzerService' of undefined
at testA (data-analyzer.component.ts:624)
at lintAsync (lint.js:134)
at startLinting (lint.js:152)
at Object.lint (lint.js:248)
at new CodeMirror (codemirror.js:7885)
at CodeMirror (codemirror.js:7831)
at Function.fromTextArea (codemirror.js:9682)
at ctrl-ngx-codemirror.js:64
at ZoneDelegate.invoke (zone-evergreen.js:365)
at Zone.run (zone-evergreen.js:124)
My code is as follow:
<ngx-codemirror
#ref
name="query"
[options]="config"
[(ngModel)]="item.query"
(keypress)="CMonKeyPress($event)"
>
</ngx-codemirror>
config = {
mode: 'text/x-mysql',
showHint: true,
lint: {
lintOnChange: true,
getAnnotations: this.lintSQL
},
gutters: [
'CodeMirror-linenumbers',
'CodeMirror-lint-markers'
]
};
constructor(
private analyzerService: DataAnalyzerService
) {}
lintSQL(a: string, b: LintStateOptions, cm: Editor) {
const found: Annotation[] = [];
// The error occurs here
this.analyzerService.lint(this.item.query).subscribe(
(r: any) => {
console.log(r.data);
},
(err) => {
console.log(err);
}
);
// So far I return an empty array, the focus is to get the results from the service
return found;
}
I would like to know how could I access to the service in the linting function.
Found from this question, the solution is to bind (this) as follow:
getAnnotations: this.lintSQL.bind(this)

Adding custom rules in Solhint

I am using solhint plugin for linting solidity code. But I want to add custom rules for the code analysis. How to add custom rules as part of the ruleset ?
Code added for custom rule:
const BaseChecker = require('./../base-checker')
const ruleId = 'no-foos'
const meta = {
type: 'naming',
docs: {
description: `Don't use Foo for Contract name`,
category: 'Style Guide Rules'
},
isDefault: false,
recommended: true,
defaultSetup: 'warn',
schema: null
}
class NoFoosAllowed extends BaseChecker {
constructor(reporter) {
super(reporter, ruleId, meta)
}
ContractDefinition(ctx) {
const { name } = ctx
if (name === 'Foo') {
this.reporter.error(ctx, this.ruleId, 'Contracts cannot be named "Foo"')
}
}
}
module.exports = NoFoosAllowed
I have saved the above code into a new js file inside rules->naming folder. And i have used the 'no-foos' rule id inside my .solhint.json file inside the rules property.
{
"extends": "solhint:all",
"plugins": [],
"rules": {
"avoid-suicide": "error",
"avoid-sha3": "warn",
"no-foos" : "warn",
"var-name-mixedcase": "error"
}
}
Each ruleset loops through all rules and enables (or doesn't enable) it based on the rule metadata and the ruleset config.
So you can create a custom rule in the rules folder and set it a combination of metadata that your ruleset will enable.

Aurelia CLI font-awesome

I've tried several different solutions but not a single one have worked for me.
I'm using.NET Core, latest Aurelia/Aurelia CLI and Font-Awesome installed using npm install font-awesome --save.
Solution 1:
New file: prepare-font-awesome.js in folder \aurelia_project\tasks
import gulp from 'gulp';
import merge from 'merge-stream';
import changedInPlace from 'gulp-changed-in-place';
import project from '../aurelia.json';
export default function prepareFontAwesome() {
const source = 'node_modules/font-awesome';
const taskCss = gulp.src(`${source}/css/font-awesome.min.css`)
.pipe(changedInPlace({ firstPass: true }))
.pipe(gulp.dest(`${project.platform.output}/css`));
const taskFonts = gulp.src(`${source}/fonts/*`)
.pipe(changedInPlace({ firstPass: true }))
.pipe(gulp.dest(`${project.platform.output}/fonts`));
return merge(taskCss, taskFonts);
}
Updated build.js\aurelia_project\tasks
import prepareFontAwesome from './prepare-font-awesome'; // Our custom task
export default gulp.series(
readProjectConfiguration,
gulp.parallel(
transpile,
processMarkup,
processCSS,
prepareFontAwesome // Our custom task
),
writeBundles
);
Included font-awesome in html
<link rel="stylesheet" href="scripts/css/font-awesome.min.css">
Error:
GET http://localhost:9000/scripts/css/font-awesome.min.css
Solution 2:
Updated aurelia.json
{
"name": "font-awesome",
"path": "../node_modules/font-awesome/",
"main": "",
"resources": [
"css/font-awesome.min.css"
]
}
Added font files in root/font-awesome/fonts
Included font-awesome in html
<require from="font-awesome/css/font-awesome.min.css"></require>
Error: No error but icons are not shown
Solution 3:
Updated build.js:
import gulp from 'gulp';
import transpile from './transpile';
import processMarkup from './process-markup';
import processCSS from './process-css';
import { build } from 'aurelia-cli';
import project from '../aurelia.json';
import fs from 'fs';
import readline from 'readline';
import os from 'os';
export default gulp.series(
copyAdditionalResources,
readProjectConfiguration,
gulp.parallel(
transpile,
processMarkup,
processCSS
),
writeBundles
);
function copyAdditionalResources(done){
readGitIgnore();
done();
}
function readGitIgnore() {
let lineReader = readline.createInterface({
input: fs.createReadStream('./.gitignore')
});
let gitignore = [];
lineReader.on('line', (line) => {
gitignore.push(line);
});
lineReader.on('close', (err) => {
copyFiles(gitignore);
})
}
function copyFiles(gitignore) {
let stream,
bundle = project.build.bundles.find(function (bundle) {
return bundle.name === "vendor-bundle.js";
});
// iterate over all dependencies specified in aurelia.json
for (let i = 0; i < bundle.dependencies.length; i++) {
let dependency = bundle.dependencies[i];
let collectedResources = [];
if (dependency.path && dependency.resources) {
// run over resources array of each dependency
for (let n = 0; n < dependency.resources.length; n++) {
let resource = dependency.resources[n];
let ext = resource.substr(resource.lastIndexOf('.') + 1);
// only copy resources that are not managed by aurelia-cli
if (ext !== 'js' && ext != 'css' && ext != 'html' && ext !== 'less' && ext != 'scss') {
collectedResources.push(resource);
dependency.resources.splice(n, 1);
n--;
}
}
if (collectedResources.length) {
if (gitignore.indexOf(dependency.name)< 0) {
console.log('Adding line to .gitignore:', dependency.name);
fs.appendFile('./.gitignore', os.EOL + dependency.name, (err) => { if (err) { console.log(err) } });
}
for (let m = 0; m < collectedResources.length; m++) {
let currentResource = collectedResources[m];
if (currentResource.charAt(0) != '/') {
currentResource = '/' + currentResource;
}
let path = dependency.path.replace("../", "./");
let sourceFile = path + currentResource;
let destPath = './' + dependency.name + currentResource.slice(0, currentResource.lastIndexOf('/'));
console.log('Copying resource', sourceFile, 'to', destPath);
// copy files
gulp.src(sourceFile)
.pipe(gulp.dest(destPath));
}
}
}
}
}
function readProjectConfiguration() {
return build.src(project);
}
function writeBundles() {
return build.dest();
}
Updated aurelia.json
{
"name": "font-awesome",
"main":"",
"path": "../node_modules/font-awesome",
"resources": [
"css/font-awesome.css",
"/fonts/fontawesome-webfont.woff2",
"/fonts/FontAwesome.otf",
"/fonts/fontawesome-webfont.eot",
"/fonts/fontawesome-webfont.svg",
"/fonts/fontawesome-webfont.ttf"
]
}
Included font-awesome in html
<require from="font-awesome/css/font-awesome.css"></require>
Error:
get:
http://localhost:9000/font-awesome/fonts/fontawesome-webfont.woff2?v=4.7.0
(same with woff and ttf)
It's really strange because the files are copied and the url is correct..
Folder structure:
Tested a couple of different sources
What am I missing?
I would prefer a less implementation so I can import Font-Awesome in my master less file.
Based off of the discussion, since you are hosting your project inside the wwwroot folder, you must base your "gets" for files from there.
So, if you move your font files into wwwroot/fonts/font-name.woff (or somewhere thereabouts), you should be golden.
If you are on a webpack based project generated with latest (2019ish) aurelia cli , then adding fontawesome or bootstrap is pretty simple.
step 1: install fontawesome
check the official docs here. Just for completeness, here is the npm or yarn way for free version
//with npm
npm install --save-dev #fortawesome/fontawesome-free
// yarn
yarn add --dev #fortawesome/fontawesome-free
step 2: import the font
in your main.js or main.ts or app.js or app.ts , all of them will work equally well, which is better? ask google.
import '#fortawesome/fontawesome-free/css/all.min.css';
And an even simpler method would be to add the CDN version into the head of your index.esj or index.html file
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.1/css/all.css" />
all of the above work equally well, personally for public apps, I prefer CDN solution due to browser cache.

how to pass 'eventBusIndex' parameter to EventBus annotation processor

I am just getting started to use the new Android Jack compiler and use the Greenrobot Eventbus.
I got it working after some trial-and-error but it only seems to work, when I specify the eventBusIndex parameter in 2 places - see code below:
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
// TODO: why must I specify eventBusIndex twice? --> also for each buildVariant
arguments = [
'eventBusIndex': "com.tmtron.dscontrol.EventBusIndex"
]
}
}
}
// this is a workaround to specify the Manifest for AndroidAnnotations
// see: https://code.google.com/p/android/issues/detail?id=210753
applicationVariants.all { variant ->
variant.variantData.variantConfiguration.javaCompileOptions.annotationProcessorOptions
.arguments = [
'eventBusIndex': "com.tmtron.dscontrol.EventBusIndex"
, 'androidManifestFile': variant.outputs[0]?.processResources?.manifestFile?.absolutePath
]
}
}

Testing elm lib with local Native directory

How do we organize our test directory when developing some libraries that uses Native js code?
I tried to work this out, but I'm blocked here, with this error at runtime when running test/test.sh:
Elm.Native.Mylib = {};
^
TypeError: Cannot read property 'Native' of undefined
git repository
My directories are structured this way:
Mylib:
- src :
- Mylib.elm
- Native :
- MyLib.js
- tests :
- Test.elm
- Test.sh
- elm-package.json
the tests/elm-package.json contains :
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
,"../src"
],
"exposed-modules": [],
"native-modules": true,
"dependencies": {
"elm-community/elm-test": "1.1.0 <= v < 2.0.0",
"elm-lang/core": "4.0.1 <= v < 5.0.0"
},
"elm-version": "0.17.0 <= v < 0.18.0"
}
the tests/Test.elm is :
module Main exposing (..)
import Basics exposing (..)
import ElmTest exposing (..)
import Mylib exposing (..)
tests : Test
tests =
suite "elm-Mylib Library Tests"
[ ]
main =
runSuite tests
The tests/test.sh is
#!/bin/sh
elm-package install -y
elm-make --yes --output test.js Test.elm
node test.js
The src/Mylib.elm is
module Mylib exposing (..)
import Native.Mylib exposing (..)
import Task exposing (Task)
import Time exposing (Time)
print : a -> Task x ()
print value =
Native.Mylib.log (toString value)
getCurrentTime : Task x Time
getCurrentTime =
Native.Mylib.getCurrentTime
The src/Native/Mylib.js is
Elm.Native.Mylib = {};
Elm.Native.Mylib.make = function(localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.Mylib = localRuntime.Native.Mylib || {};
if (localRuntime.Native.Mylib.values)
{
return localRuntime.Native.Mylib.values;
}
var Task = Elm.Native.Task.make(localRuntime);
var Utils = Elm.Native.Utils.make(localRuntime);
function log(string)
{
return Task.asyncFunction(function(callback) {
console.log(string);
return callback(Task.succeed(Utils.Tuple0));
});
}
var getCurrentTime = Task.asyncFunction(function(callback) {
return callback(Task.succeed(Date.now()));
});
return localRuntime.Native.Mylib.values = {
log: log,
getCurrentTime: getCurrentTime
};
};
Try this:
var _user$project$Native_MyLib = function() {
return {
exported: function(arg) { return "One" },
exported2: F2(function(arg) { return "Two" }),
exported3: F3(function(arg) { return "Three" }),
}
}();
It works for grater than Elm 0.17.
Buy you should also use full qualified import:
import Natve.MyLib
exported : String -> String
Native.MyLib.exported
exported2 : String -> String -> String
Native.MyLib.exported2
exported3 : String -> String -> String -> String
Native.MyLib.exported3
User and project values are from your/local elm-package.json:
"repository": "https://github.com/user/project.git",