use sass styles globally in Vue.js - vue.js

I tried to use sass globally in the vue.js app using this method :
const { defineConfig } = require('#vue/cli-service')
module.exports = {
css:{
loaderOptions:{
sass:{
data:`#import "#/sass/test.scss";`
}
}
}
}
but in vue.config.js i have these 2 lines of code:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({transpileDependencies: true})
I've tried to put a comma between them and it didn't work, I've also tried to remove the first two lines and it won't work, I've searched but all the results were old,

Alright, I've figured it out, go to your main.js and import your main sass file (or whatever files you have) and it'll work just fine.

Related

How to write a JSON file into the dist folder by vue.config.js webpack config?

The origin data is not from a file, but from a JSON object.
I already know how to use the native Node.js code to write a JSON file into the dist directory, but now I want to use vue.config.js webpack config to do this task.
I'm not familiar with webpack either. I simply checked some information, but I didn't find any way.
I hope to get some advice, thanks!
I found a solution.
const fs = require('fs-extra');
function JsonWebpackPlugin() {
fs.writeJSONSync('./public/some.json', { a: 1 });
}
JsonWebpackPlugin.prototype.apply = new Function();
module.exports = {
chainWebpack(config) {
config.plugin('Json').use(JsonWebpackPlugin);
}
}

How to remove comments in chunk-vendors.js

a little strange question, but how to remove comments from the file chunk-vendors.js? I mean, there are automatically placed licenses and other information about plugins, including the vue, vuex, vue-router.
Is there any parameter responsible for this? I’m tired of removing these lines manually after each build
I use vue-cli
Assuming Vue CLI 3 or newer, this is handled by the minimizer's (terser) output options. Specifically, set output.comments=false to exclude comments from the minified output.
Edit vue.config.js to include:
module.exports = {
chainWebpack: config => {
config.optimization.minimizer('terser').tap((args) => {
args[0].terserOptions.output = {
...args[0].terserOptions.output,
comments: false // exclude all comments from output
}
return args
})
}
}

Vue unit testing: "You are running Vue in development mode."?

I understand that in your jest.setup.js code, you are supposed to set
Vue.config.productionTip = false;
Vue.config.devtools = false;
and I do. In fact, here is my jest.setup.js code. Notice the console.log('yo ho');
// test/setup.js
import Vue from 'vue';
import Vuetify from 'vuetify';
import { config } from '#vue/test-utils';
import VueCompositionApi from '#vue/composition-api'; // <-- Make the import
Vue.use(Vuetify);
Vue.use(VueCompositionApi);
Vue.config.productionTip = false;
Vue.config.devtools = false;
console.log('yo ho');
// https://vue-test-utils.vuejs.org/
// and this came from: https://github.com/kazupon/vue-i18n/issues/323
// it mocks out the $t function to return the key so you can test that the right key is being used
config.mocks = {
$t: (key) => 'i18n:' + key
};
So given that, I don't expect to get these warnings - ever. But I do on about 1/3 of my unit test files. Not all my unit test files, just some of them. I am really confused.
So I then added that console log statement to ensure that on the unit tests that I am getting this warning, the jest.setup.js is actually getting called. This is the output from one of my unit tests:
PASS src/components/announcement-banner.test.ts (8.255s)
● Console
console.log tests/unit/jest.setup.js:12
yo ho
console.info node_modules/Vue/dist/vue.runtime.common.dev.js:8403
Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
console.info node_modules/Vue/dist/vue.runtime.common.dev.js:8412
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
How in the world I am I getting the Vue warning, when I am definitely executing the jest.setup?
to make these warnings go away, I have to go to the specific test file and add the config lines directly before the createLocalVue() call.
Vue.config.productionTip = false;
Vue.config.devtools = false;
const localVue = createLocalVue();
Finally solved. Looks like jest.mock('module') is importing clean Vue (into mock, behind the scenes) if Vue is imported in given file. I've solved this by creating global mock for Vue.
In root of your project (where node_modules directory is) create __mocks__/vue/index.ts (or .js if you are not using TypeScript) file with:
import Vue from 'vue'
Vue.config.productionTip = false
Vue.config.devtools = false
export default Vue
Should solve this annoying problem.
UPDATE 2022-07-04 VueI18n common error (related)
Using Vue.extend() in components will cause Jest to use version imported through this file when component is a child component of component mounted in the test. If you are using VueI18n and try to mount component or stub child component (that uses VueI18n) everything will go sideways with error _vm.$t is not a function
To avoid that, You will need to mock VueI18n in that particular file. For example by creating fake plugin (this is more advanced fake than just $t: (key) => key, you can use whatever you want):
const VueI18nStub = {
install(_Vue: typeof Vue) {
function getFormattedTranslationArgs(...args: any): string {
return args
.reduce((result: string[], arg: any) => {
result.push(typeof arg === 'object' ? JSON.stringify(arg) : arg.toString())
return result
}, [])
.join(' | ')
}
_Vue.prototype.$t = getFormattedTranslationArgs
_Vue.prototype.$tc = getFormattedTranslationArgs
_Vue.prototype.$te = () => true
},
}
Vue.use(VueI18nStub)
VueI18n is a common example, but any plugin will need to be added in this file to work, as you can't extend mock from this file inside any test.
Whole file with VueI18n stub would look like this:
import Vue from 'vue'
Vue.config.productionTip = false
Vue.config.devtools = false
const VueI18nStub = {
install(_Vue: typeof Vue) {
function getFormattedTranslationArgs(...args: any): string {
return args
.reduce((result: string[], arg: any) => {
result.push(typeof arg === 'object' ? JSON.stringify(arg) : arg.toString())
return result
}, [])
.join(' | ')
}
_Vue.prototype.$t = getFormattedTranslationArgs
_Vue.prototype.$tc = getFormattedTranslationArgs
_Vue.prototype.$te = () => true
},
}
Vue.use(VueI18nStub)
export default Vue
After upgrading to vue 2.7, all my unit tests for components using the composition-api were failing. It turns out, now that the composition-api is directly exported in the vue module, the jest mock from the accepted answer has to be updated like this:
import Vue from 'vue';
Vue.config.productionTip = false;
Vue.config.devtools = false;
export default Vue;
// this line makes available all of the non-default exports from the vue module in jest tests
export * from 'vue';
Hope this helps anyone struggling with unit tests under vue 2.7

How to import a config file into Vue.JS+Vuex

I'm setting configs in my main.js file before calling Vue :
Vue.prototype.$api_url = process.env.NODE_ENV === 'production' ? 'https://api.xxx.com' : 'https://yyy.test:8443'
It works if I access this.$api_url in any Vue file.
But in store.js (Vuex), it's another Vue Instance that is rendered, so I can't access this.$api_url.
What about setting the configs in a file and Vue.use(configs.js) ?
What should I do inside the configs file in order to get its variables in main.js/store.js ?
Thank you.
Make a standalone config.js file and export your config object from that file. And import config where ever you need config.
You can also assign the same config to Vue's prototype if you want that to be provided in all Vue components.
Update:
So here is how you can do this:
In your config.js
let config;
if (process.env.NODE_ENV === "production") {
config = {
$api_url: "https://api.xxx.com",
timeoutDuration: 30000,
someOtherProps: 'xyz'
};
} else {
config = {
$api_url: "https://yyy.test:8443",
timeoutDuration: 1000,
someOtherProps: 'abc'
};
}
export { config }
In your main.js
import { config } from 'config';
Vue.prototype.appConfig = config
use this.appConfig.$api_url whatever way you want to use in .vue files
In your store.js
import { config } from 'config';
use config.$api_url whatever way you want to use

How to not put "use strict" everywhere

I'm trying to write some tests for a React app I've been working on, and I figured I would use Jest since it's mentioned in the React docs.
I'm using Webpack and so far I've installed jest-cli, babel-jest, and I included the following configuration in package.json:
"jest": {
"scriptPreprocessor": "./node_modules/babel-jest",
"unmockedModulePathPatterns": [
"./node_modules/react",
"./node_modules/react-dom"
],
}
So, I'm writing the tests for some file foo.js. This file includes some other module bar.js (i.e. const bar = require('./bar');). Unfortunately, when I run jest I get the following error:
SyntaxError: Block-scoped declarations (let, const, function, class) not yet
supported outside strict mode in file 'js/foo.js'.
So, after some research, I find out I have to include 'use strict'; at the top of foo-test.js. However, for some reason, I still get the same error unless I also include 'use strict'; at the top of foo.js.
So my question is: am I doing something wrong? If not, is there anyway for me to write my tests using Jest without having to write 'use strict'; at the top of all my source files?
It seems to test out basic ES2015 classes with jest, use strict is required, however to test React Components, 'use strict' isn't required. Here's an example
//CheckboxWithLabel.js
import React, {Component} from 'react';
class CheckboxWithLabel extends Component {
constructor(){
super(...arguments);
this.state = {
isChecked: false
};
this.onChange = this.onChange.bind(this);
}
onChange() {
this.setState({
isChecked: !this.state.isChecked
});
}
render() {
return (
<label>
<input type="checkbox"
checked={this.state.isChecked}
onChange={this.onChange} />
{this.state.isChecked ? this.props.labelOn : this.props.labelOff }
</label>
);
}
}
export default CheckboxWithLabel;
//CheckboxWithLabel_tests.js
jest.disableAutomock(); //use this instead of jest.autoMockOff()
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import CheckboxWithLabel from '../source/components/CheckboxWithlabel';
// const CheckboxWithLabel = require('../source/components/CheckboxWithLabel');
describe('CheckboxWithlabel', () => {
const shallowRenderer = TestUtils.createRenderer();
//render a checkbox
const checkbox = TestUtils.renderIntoDocument(
<CheckboxWithLabel labelOn="On" labelOff="Off" />
);
// shallowRenderer.render(<CheckboxWithLabel labelOn="On" labelOff="Off" />)
// const checkbox = shallowRenderer.getRenderOutput();
// it('defaults to unchecked and off label', () => {
// const inputField = checkbox.props.children[0];
// const textNode = checkbox.props.children[1];
// expect(inputField.props.checked).toBe(false);
// expect(textNode).toEqual('Off');
// })
var checkboxNode = ReactDOM.findDOMNode(checkbox);
// let checkboxElement = TestUtils.findRenderedDOMComponentWithTag(checkbox, 'input');
it('defaults to Off label', () => {
expect(checkboxNode.textContent).toEqual('Off');
// expect(checkboxElement.checked).toBe(false);
});
})
Edited: This is not required anymore
Notice the only caveat being that you have to explicitly add a auto_mock_off.js file that simply adds this line (it took me hours to figure this one out)
jest.autoMockOff();
More information can be found on this thread on github Github React Issue #932
That's it! the component testing works perfectly. I've also tried the same example with shallow rendering and it worked perfectly too! Hope this helps!