How to setup SASS/SCSS/sass-loader in Nuxt - vue.js

I have a Nuxt app and I want to use the CSS pre-processor.
I installed the sass-loader fibers dependencies, but after installation, a message appears in the application console, which I presented in the image and in the code
This is code err:
WARN webpack#5.49.0 is installed but ^4.46.0 is expected 17:22:44
WARN sass-loader#12.1.0 is installed but ^10.1.1 is expected
Rule can only have one resource source (provided resource and test + include + exclude) in { 17:22:46
"use": [
{
"loader": "/home/sergey/all_project/pro_projects_all_language/empty/node_modules/babel-loader/lib/index.js",
"options": {
"configFile": false,
"babelrc": false,
"cacheDirectory": true,
"envName": "server",
"presets": [
[
"/home/sergey/all_project/pro_projects_all_language/empty/node_modules/#nuxt/babel-preset-app/src/index.js",
{
"corejs": {
"version": 3
}
}
]
]
},
"ident": "clonedRuleSet-29[0].rules[0].use[0]"
}
]
}
"use": [
{
"loader": "node_modules/babel-loader/lib/index.js",
"options": {
"configFile": false,
"babelrc": false,
"cacheDirectory": true,
"envName": "server",
"presets": [
[
"node_modules/#nuxt/babel-preset-app/src/index.js",
{
"corejs": {
"version": 3
}
}
]
]
},
"ident": "clonedRuleSet-29[0].rules[0].use[0]"
}
]
}
at checkResourceSource (node_modules/#nuxt/webpack/node_modules/webpack/lib/RuleSet.js:167:11)
at Function.normalizeRule (node_modules/#nuxt/webpack/node_modules/webpack/lib/RuleSet.js:198:4)
at node_modules/#nuxt/webpack/node_modules/webpack/lib/RuleSet.js:110:20
at Array.map (<anonymous>)
at Function.normalizeRules (node_modules/#nuxt/webpack/node_modules/webpack/lib/RuleSet.js:109:17)
at new RuleSet (node_modules/#nuxt/webpack/node_modules/webpack/lib/RuleSet.js:104:24)
at new NormalModuleFactory (node_modules/#nuxt/webpack/node_modules/webpack/lib/NormalModuleFactory.js:115:18)
at Compiler.createNormalModuleFactory (node_modules/#nuxt/webpack/node_modules/webpack/lib/Compiler.js:636:31)
at Compiler.newCompilationParams (node_modules/#nuxt/webpack/node_modules/webpack/lib/Compiler.js:653:30)
at Compiler.compile (node_modules/#nuxt/webpack/node_modules/webpack/lib/Compiler.js:661:23)
at node_modules/#nuxt/webpack/node_modules/webpack/lib/Watching.js:77:18
at AsyncSeriesHook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:24:1)
at AsyncSeriesHook.lazyCompileHook (node_modules/tapable/lib/Hook.js:154:20)
at Watching._go (node_modules/#nuxt/webpack/node_modules/webpack/lib/Watching.js:41:32)
at node_modules/#nuxt/webpack/node_modules/webpack/lib/Watching.js:33:9
at Compiler.readRecords (node_modules/#nuxt/webpack/node_modules/webpack/lib/Compiler.js:529:11)
I tried reinstalling dependencies, reinstalling a completely clean Nuxt application, and still the problem remains.

To install SASS in Nuxt, you have to run yarn add -D sass sass-loader#10.1.1 (or npm i -D sass-loader#10.1.1 --save-exact && npm i -D sass).
The version of sass-loader needs to be exact and set at the latest 10.x.x because the next one (11.0.0) is using Webpack5, hence being a breaking change because Nuxt2 is only running on Webpack4 as shown here: https://github.com/webpack-contrib/sass-loader/releases
IF then, you still cannot use <style lang="sass"> in your .vue components, then proceed.
Add this to your nuxt.config.js file
export default {
build: {
loaders: {
sass: {
implementation: require('sass'),
},
scss: {
implementation: require('sass'),
},
},
}
}
Here is a working repo with the latest recommended sass (dart-sass) setup working properly with this kind of code
<template>
<div>
<span class="test">
Hello there
</span>
</div>
</template>
<style lang="sass" scoped>
div
.test
color: red
</style>
PS: if SASS is properly installed, then SCSS is working as good because it's basically the same thing.
If you have some warning on some things being deprecated like / for divison or any listed here: https://sass-lang.com/documentation/breaking-changes
You can refer to this answer for a fix: https://stackoverflow.com/a/68648204/8816585

kissu's answer worked for me, but not right away. Finally I managed to fix the problem by downgrading the loader also followed by removing and installing again nuxt.

Related

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"
}
}

Cannot find module '#/assets/<file-name-here>.svg'. #vue/cli Version: 4.2.3 and 4.3.1

General jist:
import Image from '#/assets/default-profile-picture.svg'
//ERROR: Cannot find module '#/assets/default-profile-picture.svg'.Vetur(2307)
I have spent the better part of today trying to find a solution to this. I know there are a lot of other posts like this one, but they are all outdated (all over a year old).
I've just generated a clean Vue CLI app, and still have the same issue.
I'm using Vue CLI Version 4.2.3, and just attempted using Vue CLI Version 4.3.1, but ran into the same issue.
I have checked that the file is in assets.
I have checked that the filename is spelled correctly.
I have a feeling this is a webpack issue, as require() would not work when called using typescript.
I have tried creating vue.config.js and manually setting the path for assets.
Project setup configuration:
Features: Babel, TS, Router, ESLint
not class-style syntax
Babel used alongside Typescript
No history mode for router
eslint with error prevention only
Lint on save
Configs placed in package.json.
Error in Component.vue
<script lang="ts">
import Vue from 'vue'
/* Cannot find module '#/assets/default-profile-picture.svg'.Vetur(2307) */
import Image from '#/assets/default-profile-picture.svg'
export default Vue.extend({
components: {
},
props: [
'employeeImage',
'employeeName',
'employeeAge',
'employeeSalary'
],
data () {
return {
marked: false,
result: [],
name: this.employeeName,
age: this.employeeAge,
salary: this.employeeSalary
}
},
computed: {
compClasses: function () {
return {
marked: this.marked
}
},
imageDefault: function () {
if (this.employeeImage === '') {
console.log('employee image empty: ' + this.employeeImage)
return '#/assets/default-profile-picture.svg'
} else {
console.log('employee image set: ' + this.employeeImage)
return this.employeeImage
}
}
}
})
</script>
Typescript Config
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": [
"webpack-env"
],
"paths": {
"#/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"/src/**/*.*",
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
What am I doing wrong?
Thanks in advance!
Please keep this in mind, that this answer is not a solution but more like a work-around for this issue by the time this question has been asked/answered for vue-svg-loader(#vue/cli Version: 4.2.3 and 4.3.1).
You can use absolute path instead of using # to reference the file when you want to import .vue components. Here is an example:
Instead of this:
Read more about this issue and any possible solutions on official repository for this issue on GitHub:
Typescript Cannot find module '#/assets/svg/register.svg?inline' #92
Typescript does not support svg files.
Create a svg.d.ts file in your project source folder with the following content:
declare module '*.svg';
and restart your editor

VueJs 3 + Vuetify: Not working in IE and Edge

I'm not sure what I'm doing wrong here. I have VueJs 3 with Vuetify. Works great with Chrome and Firefox, but it is not loading in IE and Edge. I am attempting to load polyfills with Babel and forcing Vue CLI to transpile dependencies for Vuetify.
package.json
"babel": {
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry"
}
]
]
}
vue.config.js
module.exports: {
transpileDependencies: ['vuetify']
}
main.ts
import 'core-js/es6';
import 'regenerator-runtime/runtime';
The imports are included at the top of my main.ts file. I have been using the official documentation to set this up.
What am I missing here?
If you created the project using vue-cli and added vuetify using vue add vuetify, then the solution to make it work in Edge should be to add transpileDependencies: ['vuetify'] to the vue.config.js file.
But in my case I added vue/vuetify to an already existing project and did not use vue-cli. So to make it work I installed core-js npm install core-js#2 --save and added this to the rules in my webpack.config.js
{
test: /\.js$/,
exclude: /node_modules\\(?!(vuetify)).*/,
use: [
{
loader: 'babel-loader',
options: {
configFile: './babel.config.js',
}
}
]
}
Then I added the babel.config.js file to the root of the project.
module.exports = {
presets: [
['#babel/preset-env', {
debug: true,
useBuiltIns: 'usage',
corejs: { "version": 2, "proposals": true }
}],
],
plugins: [
'#babel/plugin-proposal-object-rest-spread',
'#babel/plugin-transform-spread',
]
}
A little late reply, but I couldn't find this solution anywhere else and this was one of the first posts showing up when I was searching for it myself. So I figured I'll post what worked for me here.
I ended up just removing Vuetify (I was only using one feature from it which was easily replaced) and using the babel polyfill cdn. Probably not the best solution but got it working for now.

Vue components does not appear on IE11 (Laravel)

All my vue components cannot be rendered in IE11. After searching, it looks like the reason is that IE does not support ES6 and above.
So my attempt at the moment is use babel:
My .babelrc:
{
"presets": [
[
"#babel/preset-env",
{
"debug": true,
"modules": false,
"forceAllTransforms": true,
"useBuiltIns": "usage",
"targets": "last 1 version, > 1%",
"corejs": 3
}
]
]
}
And I am using laravel-mix to compile the asset:
const mix = require("laravel-mix")
mix.js("resources/js/app.js", "public/js/app.js")
.sass("resources/sass/app.scss", "public/css/app.css")
.options({
processCssUrls: false
});
The compilation was running ok, but my vue components are still not rendered.
Any pointers to solve the problem?
Thanks.
// SOLUTION: Convert ES6 to ES2015 using babel and laravel-mix
Try this.
Install babel polyfill
npm install --save #babel/polyfill or yarn add #babel/polyfill
Add the code import #babel/polyfill to src/main.js.
import '#babel/polyfill'
import Vue from 'vue'
// ...
Change the babel.config.js as follows:
module.exports = {
presets: [
[
'#vue/app',
{
'useBuiltIns': 'entry'
}
]
]
}
Create the vue.config.js file and create:
(Add existing settings if they already exist.)
const ansiRegex = require('ansi-regex')
module.exports = {
......(기존 설정이 있다면 다음에 추가)
transpileDependencies: [ansiRegex]
}
Note. Use es6-promise when using a promise pattern.

Unexpected token 'import' error while running Jest tests?

I realize this question has been asked several times but all of the solutions I've come across don't seem to work for me. I'm running into the following error while trying to run Jest tests for a Vue app.
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://facebook.github.io/jest/docs/en/configuration.html
Details:
/node_modules/vue-awesome/icons/expand.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
^^^^^^
SyntaxError: Unexpected token import
> 17 | import 'vue-awesome/icons/expand'
.babelrc:
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}]
],
"env": {
"test": {
"presets": [
["env", { "targets": { "node": "current" }}]
]
}
}
}
jest config in package.json:
"jest": {
"moduleFileExtensions": [
"js",
"vue"
],
"moduleNameMapper": {
"^#/(.*)$": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"snapshotSerializers": [
"<rootDir>/node_modules/jest-serializer-vue"
],
"moduleDirectories": [
"node_modules",
"src"
]
}
It looks like the initial import in the script for the Vue component being mounted for the test is working but the import within the module itself (import Icon from '../components/Icon.vue) is not recognized.
boiler plate repo to re-creates the issue: github.com/DonaldPeat/stackoverflow-jest-question
How can I resolve this?
You just need to make sure that vue-awesome will be transformed by jest, so add
following to your jest config:
transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],
which means: "Ignore everything in node_modules except for vue-awesome.
Also here is exhausive list of other issues that might cause this error: https://github.com/facebook/jest/issues/2081
If you are encountering this problem after updating to a newer Jest version, try clearing Jest's internal cache:
jest --clearCache
Adding this in the package.json works for me (replace <package_name> with causing package name)
"jest": {
"transformIgnorePatterns": ["node_modules/(?!<package_name>)/"]
}
We had the same issue with another library. The root cause was that we had a circular dependency in code. But the error text did not refer to it at all. just like in this post: "Jest encountered an unexpected token..."
In my case I needed testEnvironment: "node" in jest.config.js file. The error came out when I started tests against Vue Router.
// jest.config.js
module.exports = {
preset: "#vue/cli-plugin-unit-jest/presets/typescript",
transform: {
"^.+\\.vue$": "vue-jest",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
"jest-transform-stub",
},
moduleNameMapper: {
"^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$":
"jest-transform-stub",
},
testEnvironment: "node", // It fixes my issue
};