Google Analytics doesn't work in my vuepress project - vue.js

Now I hava a vuepress project,
I am trying to use google analytic to track the flow of it.
But it seems there are some problem between my project and google analytic
I already follow the Document Guide(
https://vuepress.vuejs.org/plugin/official/plugin-google-analytics.html)
to use yarn add -D #vuepress/plugin-google-analytics
rather than npm install -D #vuepress/plugin-google-analytics
and also add the plugin to my config
plugins: [
'vuepress-plugin-mathjax',
{
target: 'svg',
macros: {
'*': '\\times',
},
},
'latex',
'#vuepress/google-analytics',
{
'ga': 'UA-157347770-2',
}
],
But it still nothing catch by google analytics.
Is there anyone has the same problem or similiar one before?
Thanks for anyone read

The declaration of plugin is wrong.
You have two options to declare the plugin: Babel Style or Object Style.
Babel style:
module.exports = {
plugins: [
['#vuepress/plugin-google-analytics', { ga: 'XX-000000000-0' }],
],
};
Object style:
module.exports = {
plugins: {
'#vuepress/plugin-google-analytics': {
ga: 'XX-000000000-0',
},
},
};
For more details, please see the documentation: https://vuepress.vuejs.org/plugin/using-a-plugin.html#babel-style

Related

Updating PostCSS config to support plugins

I am trying to update my postcss.config.js file to support two plugins: postcss-nested and postcss-mixins. Tech used: react project, using webpack and npm.
From PostCSS documentation, it says i need to add the plugins as an array and in this StackOverflow post, it similarly says 'the export in the postcss.config.js needs to be an object with a plugins property that holds an array of your plugins.' When i try that, i'm getting linting erros and it seems wrong. Any suggestions welcome.
Old postcss.config.js
module.exports = {
parser: 'postcss-scss',
plugins: {
'precss': {
'import': {
extension: 'pcss',
prefix: '_',
},
},
'postcss-calc': {
mediaQueries: true,
},
},
};
New postcss.config.js
module.exports = {
parser: 'postcss-scss',
plugins: [
require('postcss-mixins'),
require('postcss-nested'),
],
'precss': {
'import': {
extension: 'pcss',
prefix: '_',
},
},
'postcss-calc': {
mediaQueries: true,
},
};
};
One other question: will any of my postcss plugins work if i don't include them in my postcss.config.js file? I am looking at our codebase and seeing many postcss plugins installed (such as autoprefixer) and they are not in the config file...so not sure if that was ever working for us.

Next.js: Jest encountered an unexpected token. Jest failed to parse a file. Crashing due to dot ( .{color: red} ) before a className in CSS files [duplicate]

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"jest":{
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

How to set webpack uglifyoptions in vue cli to mantain comments?

I need to configure Uglify options in a vue cli project.
What I need is to mantain certain comments, so I've tried to set up this in vue cli, without success.
configureWebpack: {
plugins: [
new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: /\<\/?fs_premium_only\>/i
}
}
})
]
},
Is something I'm doing wrong? if I inspect the vue config I see that the options is there, but my comment are stripped out.
Is there any way to preserve those comments?
It came ot I must use this syntax:
chainWebpack: config => config.optimization.minimizer([new UglifyJsPlugin({
uglifyOptions: {
output: {
comments: /\<\/?fs_premium_only\>/i,
}
}
})])

responsive-loader with nuxt.js

I want to integrate responsive-loader into my Nuxt.js project which runs in SPA mode. (Optional I want to add Vuetify Progressive Image support also).
It will be a static hosting with Netlify.
Versions:
"nuxt": "^2.3.4"
"responsive-loader": "^1.2.0"
"sharp": "^0.21.1"
I found some solutions how to do it (https://stackoverflow.com/a/51982357/8804871) but this is not working for me.
When I run npm run build
I get an error message: "TypeError: Cannot set property 'exclude' of undefined"
My build section looks the following:
build: {
transpile: [/^vuetify/],
plugins: [
new VuetifyLoaderPlugin()
],
extractCSS: true,
/*
** Run ESLint on save
*/
extend(config, { isDev, isClient, isServer }) {
// Default block
if (isDev && isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/
})
}
if (isServer) {
config.externals = [
nodeExternals({
whitelist: [/^vuetify/]
})
]
}
// Default block end
// here I tell webpack not to include jpgs and pngs
// as base64 as an inline image
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
/*
** Configure responsive-loader
*/
config.module.rules.push({
test: /\.(jpe?g|png)$/i,
loader: "responsive-loader",
options: {
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
});
}
}
The error is probably found in this section:
config.module.rules.find(
rule => rule.loader === "url-loader"
).exclude = /\.(jpe?g|png)$/;
Like said I get this error message: "TypeError: Cannot set property 'exclude' of undefined".
I run this project along with vuetify. I also would like to enable the Progressive image support together with responsive loader. Does anybody know how to setup both rules together?
https://github.com/vuetifyjs/vuetify-loader#progressive-images
The easiest way to integrate responsive-loader into a Nuxt.js project is to use this module: https://www.npmjs.com/package/nuxt-responsive-loader
Disclaimer: I created the module
The problem with your config that it relies on rule.loader property but rule can be defined in use or oneOf config sections as well.
Another one problem is that nuxt internal config has several rules with url-loader(for images, videos, fonts ...).
In your case the rule, you tried to find, has use section and url-loader is defined there, that's why your find function found nothing and threw this error:
{
"test": /\.(png|jpe?g|gif|svg|webp)$/,
"use": [{
"loader": "url-loader",
"options": {
"limit": 1000,
"name": "img/[hash:7].[ext]"
}
}]
}
About responsive-loader, you should remove extensions you want to process with responsive-loader from url-loader rule to avoid unexpected behavior and conflicts, here is extend function working example:
extend(config, ctx) {
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/';
// find by reg ex string to not rely on rule structure
let urlRule = config.module.rules.find(r => r.test.toString() === imgTest);
// you can use also "oneOf" section and define both loaders there.
// removed images from url-loader test
urlRule.test = /\.(svg|webp)$/;
config.module.rules.push({
test: /\.(png|jpe?g|gif)$/,
loader: "responsive-loader",
options: {
// place generated images to the same place as url-loader
name: "img/[hash:7]-[width].[ext]",
min: 350,
max: 2800,
steps: 7,
placeholder: false,
quality: 60,
adapter: require("responsive-loader/sharp")
}
})
}
Yes, it looks dirty, but I think it's only way for now to change some loader.
What about vuetify - I think both loaders will conflict with each other and probably the solution is to use single loader that will work with your images.
Hope it helps.
Update for Nuxt >= 2.4.0:
They modified the rules array please update the following line:
let imgTest = '/\\.(png|jpe?g|gif|svg|webp)$/i';
Then the code should work normally again.

Karma, Browserify on React is failing on LESS

I'm learning how to use React, and in turn use Karma as the test runner. I'm running Karma with browserify / reactify (mocha+kai). Whenever I run npm test, I get the following error:
ERROR [framework.browserify]: bundle error
ERROR [framework.browserify]:
/Users/user/Projects/example-d3-react/src/d3Chart.less:1
.d3 {
^
ParseError: Unexpected token
ERROR [karma]: [TypeError: Not a string or buffer]
This happens on all LESS files in the project. I have tried adding a LESS preprocessor to the karma.conf like so:
preprocessors: {
'src/*.less': ['less'],
'tests/**/*.js': ['browserify']
},
browserify: {
debug: true,
transform: [ 'reactify' ]
},
lessPreprocessor: {
options: {
paths: ['src'],
save: true,
rootpath: './'
},
additionalData: {
modifyVars: {
'bodyColor': 'grey',
'secondBoxColor': 'blue'
},
globalVars: {
'globalBoxColor': 'red'
}
},
transformPath: function(path) {
console.log("transforming");
return path.replace(/\.less$/, '.compiled.css');
}
},
Add the preprocessor explicitly to the config: plugins: ['karma-less-preprocessor']
None of the suggested answers helped me, but in case anyone is experiencing this problem, the solution that worked for me is just adding the project-specific less transform to the package.json file. E.g:
{
...
"browserify": {
"exclude": "*.spec.js",
"transform": [
"node-lessify",
"browserify-ng-html2js"
]
},
...
}
Build broke when doing this, since I was using the cmd line transform when building application through NPM. Removed the cmd line transform part since the package.json transform will apply the transform programmatically, and now it works again.