relative Path after build with Vuejs CLI ignored - vuejs2

After building my app i need a semi absolute path, but only when using standard webpack init. How can i solve this as described below?
Apppath on Server:
domain/subfolder/subfolder2/index.html
If using
vue init webpack-simple myproject
I can set:
assetsPublicPath: ''
The result is that all files will be loaded correctly if placed next to the index.html, or in a subfolder3 (depending on config obviously).
If instead using
vue init webpack myproject
Setting of the assetPublicPath is being ignored unless i make it non empty. So
assetPublicPath: '/static'
works. But while it is kinda relative, the static folder may change as i don't have full control over the overlaying project. Because of that i want to just place the js file next to the html file and use an empty assetsPublicPath to be sure it will always work.
Why is this behavior changing due to the template used? How can i fix it?
I tried digging into all the different config files and failed to find any reason as to why this might happen.

There's nothing stopping you placing a js file in src next to the component and loading that files data into the component script tag:
<template>
<div class="test">
</div>
</template>
<script>
import myClass from './myClass.js'
export default {
name: 'test',
data() {
return {
msg: '',
}
},
methods: {
something(){
let foo = myClass.prop;
}
}
}
</script>
<style lang="scss" scoped>
#import "../../assets/master";
</style>

Related

Importing SCSS variables in Vue components

I recently switched from Vue-CLI to laravel-mix, the usage of SCSS variables worked perfectly with Vue-CLI and now doesnt seem to work anymore at all after I switched to laravel-mix.
Vue-CLI just handled everything for me and I feel like I have to configure something to get the variables to work in laravel-mix.
This is what I've tried (and what worked with Vue-CLI):
// vue component
import variables from "#/styles/variables.scss";
// ...
data() {
return {
variables
}
}
methods: {
test() {
console.log(this.variables)
}
}
// scss
$variable: #FFFFFF;
:export {
variable: $variable;
}
Edit: To clarify, this log outputs an empty object, not undefined.
For this thing to work you need to follow that particular steps
Make Your Variables File. As you made your scss file inside your style its not good you need to make inside /assets/sass/
Add Variables File To App.scss. For that thing you need to import newly create file inside your app.scss by #import 'folder/file';
Add Alias To webpack.mix.js. What we essentially need to do is define an alias or variable that contains the path to our sass directory so we can include that SASS in our Vue components. Just add alias like this in your webpack
resolve: {
alias: {
'#': path.resolve('resources/assets/sass')
}
}
Last thing add Navigation Vue Component. You can import scss variables by adding #import '~#/folder/fie.scss'; in the vue component

Load vue component (truly) dynamically from local file

Is it possible to load a vue component dynamically at runtime (in an electron app to build a plugin system)?
The component is in a specific file
Its path is only known at runtime
The component can either be precompiled (if that is possible, don't know) or is compiled at runtime
A simple example component is listed below
I tried the following approaches, both failing:
Require component
<template>
<component :is="currentComp"></component>
</template>
<script>
...
methods: {
loadComponent(path) {
const dynComp = eval('require(path)'); // use eval to prevent webpackresolving the require
this.currentComp = dynComp;
}
},
...
</script>
The import works, but the line this.currentComp = dynComp; Fails with error message:
Error in data(): "Error: An object could not be cloned."
Using the code presented here, but replace url with a local path
Fails with error message:
Failed to resolve async component: function MyComponent() {
return externalComponent('/path/to/Component.vue');
}
Reason: TypeError: Chaining cycle detected for promise #<Promise>
The used example component is the following:
// Example component
module.exports = {
template: `
<div>
<input v-model="value"/>
<button #click="clear">Clear</button>
<div>{{ value }}</div>
</div>`,
name: 'Example',
data() {
return {
value: '',
};
},
watch: {
value(value) {
console.log('change!');
},
},
methods: {
clear() {
this.value = '';
},
},
};
I found a solution:
Create the vue component as a SFC in a separate file (here src/Component.vue). I didn't try, but probably it works for inline components, too.
Precompile the component using vue-cli-service, which is already a dev dependency, if the project is created using vue-cli (It's nice to use vue-cli here, since the required loaders are already included):
yarn vue-cli-service build --target lib src/Command.vue
The component is compiled to different bundle types in the dist directory. The file [filename].umd.min.js can be imported now.
Import the component dynamically at runtime:
let MyComponent = eval(`require('/absolute/path/to/[filename].umd.min.js')`);
Vue.component('MyComponent', MyComponent);
The require is wrapped inside an eval to prevent webpack of trying to include the import in its bundle and transforming the require into a webpack__require.
(Optional) If the SFC component contains a <style>...</style> tag, the resulting css is compiled to a separate file. The css can be inlined in the js file by adding the following lines to the vue.config.js in the components project root:
module.exports = {
...
css: {
extract: false,
},
};
You can probably look into async loading:
https://v2.vuejs.org/v2/guide/components-dynamic-async.html#Async-Components
and see this for a webpack lazy load example:
https://vuedose.tips/dynamic-imports-in-vue-js-for-better-performance/#the-meat%3A
These are just some things I would research for your requirements.

Can't access CSS variables in script tag of Vue file

Problem
I am trying to access variables defined within an SCSS file from a .vue file. The project is using vue-cli.
According to Vue's docs:
"Vue CLI projects comes with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus."
However, if I create a variables.css file with a variable called variable, and try to import it within the script, this variable is not found.
styles/variables.module.css
$variable: 'foo';
:export {
variable: $variable
}
App.vue
<script>
import variables from "./styles/variables.module.scss";
export default {
name: "App",
methods: {},
computed: {
variable() {
console.log(variables); // Object {}
return variables.variable || "not found";
}
}
};
</script>
Importing the variables.css file within the <style module> tag of the same vue file does work however.
App.vue
<style module lang="scss">
#import "./styles/variables.module.scss";
:export {
variable: $variable;
}
</style>
What I'm trying to achieve
<p>Importing within <script>, the variable is {{variable}}</p>
// 'not found', should be "foo"
<p>Importing within <style>, the variable is {{$style.variable}}</p>
// correctly showing "foo"
Have tried:
Adding .module to the SCSS file name (as per vue's docs)
Creating a vue.config.js file with requireModuleExtension: false
(from same docs)
Reproducible demo
https://codesandbox.io/s/importing-css-to-js-o9p2b?file=/src/App.vue
You need to add webpack and CSS modular code into webpack.config.js.
npm install -D vue-loader vue-template-compiler webpack
Here is the working demo
Note: your vue-template-compiler and vue should be the same version

Unknown custom element error in Vue.js project

I started creating a project in vue.js based on this one:
https://github.com/creativetimofficial/vuetify-material-dashboard
When trying to integrate TableList.vue component, I get an error:
Unknown custom element: <material-card> - did you register the component correctly?
Vue.js project was created using webstorm. I copied over styles folder and enabled watcher to compile scss files into css. I run project using npm serve command in WebStorm.
My App.vue looks a little different like this:
<template>
<v-app>
<TheBar />
<TheNavigationDrawer />
<TheView />
</v-app>
</template>
<script>
import TheBar from '#/components/core/TheBar.vue'
import TheNavigationDrawer from "#/components/core/TheNavigationDrawer";
import TheView from '#/components/core/TheView.vue'
export default {
name: 'app',
components: {
TheBar,
TheNavigationDrawer,
TheView
},
data: () => ({
}),
};
</script>
<style lang="scss">
#import './styles/index.scss';
</style>
As you can see I am importing the full file, which in turn imports _cards.scss file which should have definition of material-card component. Is this how it works?
I tried registering component manually by adding material-card to components property but it fails to parse kebab-case properly because of '-' sign.
What also intrigues me is that the original creator NEVER registers material-card component so how the hell does his TableList.vue component know it?
I also found this guide - https://medium.com/#mahesh.ks/using-sass-scss-in-vue-js-2-d472af0facf9. However I don't see a webpack.config.js file anywhere, where is this?
Any help is greatly appreciated. :D
There are multiple ways of importing components into your Vue instance. For the case of the project you're working from, the vuetify library is imported at the root instance which allows all components to be available globally. This means you don't need to import the desired components within specific .vue files.
It's likely that you haven't installed all of the dependencies correctly. Or you have not properly imported these dependencies within main.js. Check that these dependecies (found in package.json) have been installed by running npm list.

Vue SFC add global Sass variables to all components

Im my webpack config I add a path
"mixins": path.resolve(
__dirname,
"resources/assets/sass/mixins/mixins.scss"
),
Which means in all my single file components I use
<style lang='scss' scoped>
#import '~variables';
This works fine but what I am finding is this file is used in 95% of components so the import really is unnecessary. I want these vars available everywhere.
How can I globally add my SASS to my single file components without the need for the import in every file?
Well, Load your common CSS from Webpack and make it available globally for all the component. Webpack configurations are as below.
sass-loader also supports a data option which allows you to share common variables among all processed files without having to explicit import them
module.exports = {
css: {
loaderOptions: {
sass: {
data: `
#import "#/scss/_variables.scss";
#import "#/scss/_mixins.scss";
`
}
}
}
};
In here, specifing the sass loader under the loaderOptions option. Just like that, all the code in those files will be available in the global scope. So from any component we can use it out of the box:
And now you can able to access the variable in your Vue SFC without importing it.
<style lang="scss">
.classroom {
/* No need to import, it just works \o/ */
background: $bg-classroom;
}
</style>
Reference Official Docs here
Hope this helps!