How to import index.vue by just mentioning the parent directory name rather than filename? - vue.js

I've been building my Vue application by using Vue Cli 3.
If I need to import an index.js which is in directory named Dir1, I can import it using
import file1 from '#/components/Dir1/
but somehow it doesn't work with .vue extension files.
I have to expicitly mention the file name such as import Title from #/components/Title/index.vue.
What changes do I have to make in the settings in order to import the .vue extension file without mentioning the filename?

This is how I would do it with Vue.
You may need to tweak the config a little bit to suit your dev environment needs.
Note that this is not a full config but a guideline on what should be done based on NPM directory-named-webpack-plugin documentation.
In your webpack.config.js you should have the following (Webpack 3):
const DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
// ...
let config = {
// ...
module: {
rules: [
{
test: /\.(js|vue)$/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
},
resolve: {
modules: ['components', 'node_modules'],
extensions: ['.js', '.vue'],
plugins: [
new DirectoryNamedWebpackPlugin(true)
]
}
// ...
}
modules.exports = config;
taken and modified for Vue from: Recursive import of components using webpack in React

Related

Is it possible to configure Vite to build for use inside Android app (CORS error)

Scenario
I'm using Vue2 with Vue CLI as the bundling tool, now I want to migrate Vue CLI to Vite to enhance the development experience, and the migration process is somewhat successful (thanks to this guide).
Problem
Due to a specific reason, I need to keep the production build accessible statically, without any local server required (the web app should run simply by opening up the index.html file on my machine). And with this, I encounter the problem due to the fact that Vite bundles my code in ESM format that has to be served through some server to resolve CORS policy (error screenshot below). And hence the question: Is it possible to configure Vite to build in plain JS rather than ESM?
Any help is appreciated. Thank you.
Attachments
My vite.config.js as below if it helps:
import path from "path";
import { defineConfig } from "vite";
import { createVuePlugin } from "vite-plugin-vue2";
export default defineConfig({
base: "",
css: {
preprocessorOptions: {
scss: {
additionalData: `
#use "sass:math";
#import "#/scss/utils.scss";`,
},
},
},
plugins: [createVuePlugin()],
resolve: {
extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"]
alias: {
"#": path.resolve(__dirname, "./src"),
},
},
});

Symfony: How to Import a Sass File into Every Vue Component

I am currently struggling with this. In my Symfony project I have a _variables.scss file, where I keep my global variables (e.g. colors).
This is included in my main scss file like this #import "variables"; - which works fine. Now I also use VueJs in my project and I would like to use my global variables inside Vue components. Now one way to achieve this is just importing the variables.scss itself:
//CustomButton.vue
<template>
...
</template>
<script>
export default {
name: "CustomButton"
}
</script>
<style lang="scss" scoped>
#import "../../scss/_variables.scss";
//able to use variables here
</style>
However with a growing project and different paths, this seems to be unnecessary work. What I'd like to achieve is to load the variables.scss into every Vue component automatically.
This is quite well explained here: [css-tricks.com - How to Import a Sass File into Every Vue Component in an App][1]
Sadly this does not work in my case (I think the vue.config.js is ignored completly) - the variables are still not usable inside the Vue component. I also tried to add the JavaScript into my main js file - where I load Vue - however this seems to break stuff (some module exception).
Is there any specific way to achieve this with symfony?
PS: I am using Symfony 5, Sass-Loader 9.0.1, Vue 2.6.12, Vue-Loader 15, Vue-Template-Compiler 2.6.12
[1]: https://css-tricks.com/how-to-import-a-sass-file-into-every-vue-component-in-an-app/
Solution 1:
//webpack.config.js
.enableSassLoader(options => {
options.additionalData = `
#import "./assets/scss/_variables.scss"; //path.resolve is not working in my case to import the absolute path
`
})
```
Webpack config:
module.exports = {
...
module: {
rules: [
{
test: /\.scss$/,
use: [
process.env.NODE_ENV !== 'production'
? 'vue-style-loader'
: MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'sass-loader',
options: {
data: `
#import "functions";
#import "variables";
#import "mixins";
`,
includePaths: [
path.resolve(__dirname, "../asset/scss/framework")
]
}
}
]
},
]
}
this config imports 3 files: "_functions.scss", "_variables.scss", "_mixins.scss" from folder"../asset/scss/framework" and no need to use #import "../../scss/_variables.scss"; every time in your vue components. Maybe, you will adapt this webpack config to your needs or will get some idea to resolve your issue.
This is what you need c:
Since you are using Encore, modify your webpack.config.js, add this code
var Encore = require('#symfony/webpack-encore');
Encore.configureLoaderRule('scss', (loaderRule) => {
loaderRule.oneOf.forEach((rule) => {
rule.use.push({
loader: 'sass-resources-loader',
options: {
resources: [
// Change this url to your _variables.scss path
path.resolve(__dirname, './assets/app/styles/_vars.scss'),
]
},
})
})
})
You also are going to have to install sass-resources-loader
npm install sass-resources-loader
Then compile your code again and your sass variables will be available everywhere
Solution to my question:
//webpack.config.js
.enableSassLoader(options => {
options.additionalData = `
#import "./assets/scss/_variables.scss"; //path.resolve is not working in my case to import the absolute path
`
})
this will import the file in every sass template + vue component

Embed react-native-web app into existing website

I want to embed a react-native-web application into an existing website and am currently looking for options how to do so.
The application should be a quite simple questionnaire which needs to be embedded into a website created with Elementor. My idea was to use the Elementor HTML widget and insert my application somehow, but unfortunately I cannot figure out how to do this.
I've got a bit of experience developing React Native(RN) apps but I am pretty new to web development and therefore thought it would be easier for me to go with RN and the react-native-web library.
So far, I've created a RN project using npx react-native init WebApp, copied the App.js, index.js and package.json files from react-native-web CodeSandbox template, deleted the node_modules folders and ran npm install. Then I was able to start and build this example web app with the scripts from the package.json.
Now my question, how can I use the output from the build directory and embed it into an html tag?
I also tried to use webpack with the configuration from the react-native-web docs to bundle the app but I always got a new error as soon as I fixed the last one. Is it possible to bundle a RN app into a single JS file which I could then insert into the website?
Looking forward to any advice!
Marco
I solved it by using the below webpack config. The created bundle.web.js' content is put into a script tag (<script>...</script>). This can be embedded into the HTML widget.
// web/webpack.config.js
const path = require('path');
const webpack = require('webpack');
const appDirectory = path.resolve(__dirname, '');
// This is needed for webpack to compile JavaScript.
// Many OSS React Native packages are not compiled to ES5 before being
// published. If you depend on uncompiled packages they may cause webpack build
// errors. To fix this webpack can be configured to compile to the necessary
// `node_module`.
const babelLoaderConfiguration = {
test: /\.js$/,
// Add every directory that needs to be compiled by Babel during the build.
include: [
path.resolve(appDirectory, 'index.web.js'),
path.resolve(appDirectory, 'src'),
path.resolve(appDirectory, 'node_modules/react-native-uncompiled'),
],
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
// The 'metro-react-native-babel-preset' preset is recommended to match React Native's packager
presets: ['module:metro-react-native-babel-preset'],
// Re-write paths to import only the modules needed by the app
plugins: ['react-native-web'],
},
},
};
// This is needed for webpack to import static images in JavaScript files.
const imageLoaderConfiguration = {
test: /\.(gif|jpe?g|png|svg)$/,
use: {
loader: 'url-loader',
options: {
name: '[name].[ext]',
},
},
};
module.exports = {
entry: [
// load any web API polyfills
// path.resolve(appDirectory, 'polyfills-web.js'),
// your web-specific entry file
path.resolve(appDirectory, 'src/index.js'),
],
// configures where the build ends up
output: {
filename: 'bundle.web.js',
path: path.resolve(appDirectory, 'dist'),
},
// ...the rest of your config
module: {
rules: [babelLoaderConfiguration, imageLoaderConfiguration],
},
resolve: {
// This will only alias the exact import "react-native"
alias: {
'react-native$': 'react-native-web',
},
// If you're working on a multi-platform React Native app, web-specific
// module implementations should be written in files using the extension
// `.web.js`.
extensions: ['.web.js', '.js'],
},
};

Dedupe CSS in Vue.js development mode

I am working on a Vue.js project that heavily uses single file components. These components have scss styles associated with them.
In production mode the duplicate css that occurs from importing the same component multiple times is filtered out. But in development mode the same scss is imported multiple times.
This leads to slow downs with the chrome debugger when inspecting and modifying the css.
Does anone know a way to dedupe the css/scss attatched to single file components in developlment mode?
Here is my current vue config:
module.exports = {
lintOnSave: false,
configureWebpack: {
resolve: {
alias: require("./aliases.config").webpack
},
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
_: "lodash"
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
}
Here's how we ended up solving it.
Import only pure SCSS in components (ie. mixins, variables, functions). If a file with CSS is imported in each component the sass loader will NOT dedupe the CSS in development mode.
In your vue config add the following to include you scss variables in every single file component:
module.exports = {
...
css: {
loaderOptions: {
sass: {
data: `
#import "#src/_variables.scss";
`
}
}
},
...
}
Import your global scss in your app entry (main.js or equivalent)
import "bootstrap";
import "#src/global.scss";
In your global.scss file you can import your variables file so that it can also access your scss variables.

Field 'browser' doesn't contain a valid alias configuration

I've started using webpack2 (to be precise, v2.3.2) and after re-creating my config I keep running into an issue I can't seem to solve I get (sorry in advance for ugly dump):
ERROR in ./src/main.js
Module not found: Error: Can't resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
resolve 'components/DoISuportIt' in '[absolute path to my repo]/src'
Parsed request is a module
using description file: [absolute path to my repo]/package.json (relative path: ./src)
Field 'browser' doesn't contain a valid alias configuration
aliased with mapping 'components': '[absolute path to my repo]/src/components' to '[absolute path to my repo]/src/components/DoISuportIt'
using description file: [absolute path to my repo]/package.json (relative path: ./src)
Field 'browser' doesn't contain a valid alias configuration
after using description file: [absolute path to my repo]/package.json (relative path: ./src)
using description file: [absolute path to my repo]/package.json (relative path: ./src/components/DoISuportIt)
as directory
[absolute path to my repo]/src/components/DoISuportIt doesn't exist
no extension
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt.js doesn't exist
.jsx
Field 'browser' doesn't contain a valid alias configuration
[absolute path to my repo]/src/components/DoISuportIt.jsx doesn't exist
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt]
[[absolute path to my repo]/src/components/DoISuportIt.js]
[[absolute path to my repo]/src/components/DoISuportIt.jsx]
package.json
{
"version": "1.0.0",
"main": "./src/main.js",
"scripts": {
"build": "webpack --progress --display-error-details"
},
"devDependencies": {
...
},
"dependencies": {
...
}
}
In terms of the browser field it's complaining about, the documentation I've been able to find on this is: package-browser-field-spec. There is also webpack documentation for it, but it seems to have it turned on by default: aliasFields: ["browser"]. I tried adding a browser field to my package.json but that didn't seem to do any good.
webpack.config.js
import path from 'path';
const source = path.resolve(__dirname, 'src');
export default {
context: __dirname,
entry: './src/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].js',
},
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components'),
},
extensions: ['.js', '.jsx'],
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: source,
use: {
loader: 'babel-loader',
query: {
cacheDirectory: true,
},
},
},
{
test: /\.css$/,
include: source,
use: [
{ loader: 'style-loader' },
{
loader: 'css-loader',
query: {
importLoader: 1,
localIdentName: '[path]___[name]__[local]___[hash:base64:5]',
modules: true,
},
},
],
},
],
},
};
src/main.js
import DoISuportIt from 'components/DoISuportIt';
src/components/DoISuportIt/index.jsx
export default function() { ... }
For completeness, .babelrc
{
"presets": [
"latest",
"react"
],
"plugins": [
"react-css-modules"
],
"env": {
"production": {
"compact": true,
"comments": false,
"minified": true
}
},
"sourceMaps": true
}
What am I doing wrong/missing?
Turned out to be an issue with Webpack just not resolving an import - talk about horrible horrible error messages :(
// I Had to change:
import DoISuportIt from 'components/DoISuportIt';
// to (notice the missing `./`)
import DoISuportIt from './components/DoISuportIt';
Just for record, because I had similiar problem, and maybe this answer will help someone: in my case I was using library which was using .js files and I didn't had such extension in webpack resolve extensions. Adding proper extension fixed problem:
module.exports = {
(...)
resolve: {
extensions: ['.ts', '.js'],
}
}
I'm building a React server-side renderer and found this can also occur when building a separate server config from scratch. If you're seeing this error, try the following:
Make sure your entry value is properly pathed relative to your context value. Mine was missing the preceeding ./ before the entry file name.
Make sure you have your resolve value included. Your imports on anything in node_modules will default to looking in your context folder, otherwise.
Example:
const serverConfig = {
name: 'server',
context: path.join(__dirname, 'src'),
entry: {serverEntry: ['./server-entry.js']},
output: {
path: path.join(__dirname, 'public'),
filename: 'server.js',
publicPath: 'public/',
libraryTarget: 'commonjs2'
},
module: {
rules: [/*...*/]
},
resolveLoader: {
modules: [
path.join(__dirname, 'node_modules')
]
},
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
I encountered this error in a TypeScript project. In my webpack.config.js file I was only resolving TypeScript files i.e.
resolve: {
extensions: [".ts"],
}
However I noticed that the node_module which was causing the error:
Field 'browser' doesn't contain a valid alias configuration
did not have any ".ts" files (which is understandable as the module has been converted to vanilla JS. Doh!).
So to fix the issue I updated the resolve declaration to:
resolve: {
extensions: [".ts", ".js"],
}
I had the same issue, but mine was because of wrong casing in path:
// Wrong - uppercase C in /pathCoordinate/
./path/pathCoordinate/pathCoordinateForm.component
// Correct - lowercase c in /pathcoordinate/
./path/pathcoordinate/pathCoordinateForm.component
Add this to your package.json:
"browser": {
"[module-name]": false
},
Changed my entry to
entry: path.resolve(__dirname, './src/js/index.js'),
and it worked.
This also occurs when the webpack.config.js is simply missing (dockerignore 🤦‍♂️)
In my case it was a package that was installed as a dependency in package.json with a relative path like this:
"dependencies": {
...
"phoenix_html": "file:../deps/phoenix_html"
},
and imported in js/app.js with import "phoenix_html"
This had worked but after an update of node, npm, etc... it failed with the above error-message.
Changing the import line to import "../../deps/phoenix_html" fixed it.
My case was rather embarrassing: I added a typescript binding for a JS library without adding the library itself.
So if you do:
npm install --save #types/lucene
Don't forget to do:
npm install --save lucene
Kinda obvious, but I just totally forgot and that cost me quite some time.
In my case, to the very end of the webpack.config.js, where I should exports the config, there was a typo: export(should be exports), which led to failure with loading webpack.config.js at all.
const path = require('path');
const config = {
mode: 'development',
entry: "./lib/components/Index.js",
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: path.resolve(__dirname, "node_modules")
}
]
}
}
// pay attention to "export!s!" here
module.exports = config;
I had aliases into tsconfig.json:
{
"compilerOptions": {
"paths": {
"#store/*": ["./src/store/*"]
}
},
}
So I solved this issue by adding aliases to webpack.config also:
module.exports = {
//...
resolve: {
alias: {
'#store': path.resolve(__dirname, '../src/store'),
},
},
};
I got same problem and fixed with adding file extension.
// Old:
import RadioInput from './components/RadioInput'
// New:
import RadioInput from './components/RadioInput.vue'
Also, if you still want to use without extensions, you can add this webpack config: (Thanx for #matthew-herbst for the info)
module.exports = {
//...
resolve: {
extensions: ['.js', '.json', '.wasm'], // Add your extensions here.
},
};
For anyone building an ionic app and trying to upload it. Make sure you added at least one platform to the app. Otherwise you will get this error.
In my experience, this error was as a result of improper naming of aliases in Webpack.
In that I had an alias named redux and webpack tried looking for the redux that comes with the redux package in my alias path.
To fix this, I had to rename the alias to something different like Redux.
In my case, it was due to a broken symlink when trying to npm link a custom angular library to consuming app. After running npm link #authoring/canvas
"#authoring/canvas": "path/to/ui-authoring-canvas/dist"
It appear everything was OK but the module still couldn't be found:
When I corrected the import statement to something that the editor could find Link:
import {CirclePackComponent} from '#authoring/canvas/lib/circle-pack/circle-pack.component';
I received this which is mention in the overflow thread:
To fix this I had to:
cd /usr/local/lib/node_modules/packageName
cd ..
rm -rf packageName
In the root directory of the library, run:
a) rm -rf dist
b) npm run build
c) cd dist
d) npm link
In the consuming app, update the package.json with:
"packageName": "file:/path/to/local/node_module/packageName""
In the root directory of the consuming app run npm link packageName
In my case (lolz),
I was importing a local package (that I was developing, and building with rollup) via NPM/Yarn link, into another package I was developing. The imported package was a load of React components, and was configured to have a peerDependency of react and react-dom.
The consuming package was being built with Webpack and obviously wasn't correctly feeding the installed react and react-dom libraries into my local dependency as it was compiling it.
I adjusted my webpack configuration to indicate it should alias those peer dependencies to the correct dependencies in the consuming package:
/* ... */
resolve: {
extensions: [/* make sure you have them all correct here, as per other answers */],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
/* ... */
Obviously you need to import path in the webpack.config.js file in order to use the methods seen above.
A more detailed explanation can be found in this article
My case was similar to #witheng's answer.
At some point, I noticed some casing error in some file names in my development environment. For example the file name was
type.ts
and I renamed it to
Type.ts
In my Mac dev environment this didn't register as a change in git so this change didn't go to source control.
In the Linux-based build machine where the filenames are case-sensitive it wasn't able to find the file with different casing.
To avoid issues like this in the future, I ran this command in the repo:
git config core.ignorecase false
In my case, I imported library files like:
import { MyFile } from "my-library/public-api";
After I removed the public-api from the import everything worked fine:
import { MyFile } from "my-library";
MyFile is exported in the public-api file in the library.
In my case,
I have mistakenly removed a library ("mini-create-react-context") from package.json. I added that back, and did yarn install and build the app and it start working properly. So please take a look at your package.json file once.
In my case I had accidentally imported this package while trying to use process.env:
import * as process from 'process';
Removing it fixed the problem.
For everyone with Ionic:
Updating to the latest #ionic/app-scripts version gave a better error message.
npm install #ionic/app-scripts#latest --save-dev
It was a wrong path for styleUrls in a component to a non-existing file.
Strangely it gave no error in development.
In my situation, I did not have an export at the bottom of my webpack.config.js file. Simply adding
export default Config;
solved it.
In my case, it is due to a case-sensitivity typo in import path. For example,
Should be:
import Dashboard from './Dashboard/dashboard';
Instead of:
import Dashboard from './Dashboard/Dashboard';
In my case I was using invalid templateUrl.By correcting it problem solved.
#Component({
selector: 'app-edit-feather-object',
templateUrl: ''
})
I am using single-spa, and encountered this issue with the error
Module not found: Error: Can't resolve '/builds/**/**/src\main.single-spa.ts' in /builds/**/**'
I eventually figured out that in angular.json build options "main" was set to src\\main.single-spa.ts. Changing it to src/main.single-spa.ts fixed it.
Had the same issue with angular was importing
import { Injectable } from "#angular/core/core";
changed it to
import { Injectable } from "#angular/core";
I was getting this error when running a GitHub action. The issue was because I'd listed the package as a peer dependency instead of a dependency.
Since I'm using Rollup, the solution was to install the package both as a peer dependency and a dev dependency, and use rollup-plugin-peer-deps-external to remove the dev dependency from the final build.
For me the issue was, I was importing
.ts files into .js files
changing them to ts as well solved the issue.
In my case, I had a mixture of enum and interface in the index.d.ts file.
I extracted enums into another file and the issue resolved.