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

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

Related

How to setup SASS/SCSS/sass-loader in Nuxt

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.

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.

How to workaround the "Unexpected Token Operator (>)" error when packaging a React app?

I am having some problems building the distributable package for a React app.
I'm trying to execute the following sentence:
rimraf dist && env-cmd .env cross-env NODE_ENV=production webpack -p --config ./config/webpack/prod.js
And receiving this error:
ERROR in a86e50ffd4893c44fdfd.app.js from UglifyJs Unexpected token:
operator (>) [a86e50ffd4893c44fdfd.app.js:10679,43]
The line indicated in that trace corresponds to one of the libraries being loaded as dependencies, and not to the actual code of my app. This is the line itself (line 10679 corresponds to the declaration of the const method with the arrow function):
const DEFAULT_DISPLAY_LABEL_FOR_NULL_VALUES = '';
/* unused harmony export DEFAULT_DISPLAY_LABEL_FOR_NULL_VALUES */
const getAllColumnLabels = (columnLabels) => {
const columnNames = [];
columnLabels.forEach((value) => {
columnNames.push(value.label);
});
return columnNames;
};
At first I thought it could be related to Babel config, but it is identical to another project which is building correctly. The content of my .babelrc file is shown below, loaded using babel-preset-env:
{
"presets": [
[
"env", {
"modules": false,
"targets": {
"browsers": [
"Chrome >= 52",
"FireFox >= 44",
"Safari >= 7",
"Explorer 11",
"last 4 Edge versions"
]
},
"useBuiltIns": true
}
]
]
}
An additional test to rule out some possibilities has been done using the default presets for Babel, though no success was achieved with this test.
{
"presets": [
[
"env",
{
"modules": false
}
]
]
}
The settings in tsconfig.json could also be of interest, so i'm showing them here even though they also are identical to the ones in this another project mentioned above, which builds correctly:
{
"compilerOptions": {
"target": "es6",
"module": "es6",
"lib": ["dom", "es2017"],
"moduleResolution": "node",
"declaration": false,
"noImplicitAny": false,
"sourceMap": true,
"jsx": "react",
"noLib": false,
"allowJs": true,
"suppressImplicitAnyIndexErrors": true,
"skipLibCheck": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
},
"compileOnSave": true,
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
I've tried to delete node_modules and re-install the dependencies, also played setting uglify to false in the env for Babelrc, but surprisingly (at least, to me!) it didnt help.
There is a thread in the webpack-contrib Github site which is marked as closed but I didnt find anything that helped me.
Any ideas? I have some experience with npm but this issue certainly is blocking me.
Thanks!
Updating webpack to version 4 (currently 4.17) solved the problem. A few other dependencies needed to be updated to work properly with webpack 4, most importantly the Extract Text Webpack Plugin hasn't at this moment a stable release that works with webpack4, but the 4.0.0-beta works around the issue and may be used until a better replacement is found.

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

TypeScript bundling not working for External Modules

I've a sample TypeScript code and I'm trying to bundle multiple ts/tsx files using typescript compiler (tsc).
Here is the code:
File: ISample.ts
class ISample{
constructor(public value:string){
}
}
export = ISample;
File: Sample.ts
import ISample = require('./ISample');
class SampleImpl{
value: ISample;
constructor(sample:number){
this.value = new ISample(sample+'');
}
}
File: tsconfig.json
{
"compilerOptions": {
"module": "amd",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"jsx": "react",
"outFile": "./dist/bundle.js",
"target": "es3",
"listFiles": true,
"sourceMap": false
},
"files": [
"./src/Sample.ts",
"./src/ISample.ts"
]
}
When I run the command:
tsc
bundle.js is generated but it is completely blank.
Observations:
The problem doesn't occur when I move the code to Internal Modules
The problem also doesn't occur when I omit the import/require statement and use a declaration for ISample class, but in that case bundle.js does not contain the code of ISample class
Any ideas why this is happening?
This is not supported for now: Suggestion: multi-file external modules.
There are a set of workarounds, e.g. Compile TypeScript with modules and bundle to one file