Snap.svg with Vue.js - vue.js

I'm trying to use Snap.svg in my Vue.js app, however I'm confuse with how to do so.
I used Vue CLI 3 command to initialized my project, and install the snapsvg dependency with yarn.
Also, I read this article.
But I can't find the webpack.base.conf.js file !
When I try to import the dependency into my main.js file or into any component I've got no error but my App become empty.
What did I miss to properly import Snap.svg in my Vue.js app ?

Instead of hacking webpack,
use snapsvg-cjs
This project simply unwraps the excellent SnapSVG from its published AMD format and hosts it on NPM as CommonJS in a package called snapsvg-cjs. This package then works out-of-the-box with Webpack, without needing any import-loader hax.
npm install snapsvg-cjs;
the only line of code you'll need:
import "snapsvg-cjs";

In Vue cli 3, webpack is configured in vue.config.js
To use snap place the vue.config.js with the following content in your root directory
module.exports = {
chainWebpack: config => {
config.module
.rule("snapsvg")
.test(require.resolve("snapsvg"))
.use("imports-loader?this=>window,fix=>module.exports=0")
.loader("imports-loader")
.end();
}
};
add this line to your main.js file:
const snap = require(`imports-loader?this=>window,fix=>module.exports=0!snapsvg/dist/snap.svg.js`);

Related

Liberary dotenv-webpack doesn't work with vue 3 and webpack-cli

I'm using Vue 3 and Webpack 5 and wanted to install dotenv-webpack, but I can't get it to work.
Here's full code: https://github.com/golebiewska-n/webpack5-vue3
Setup:
package.json script I'm using to launch the app
webpack-cli serve
webpack.config.js
const Dotenv = require('dotenv-webpack')
...
module.exports = (env) => {
return {
...
plugins: [
...
new Dotenv()
]
}
}
.env (added in the root folder of my app)
VUE_APP_VAR=123
main.js
console.log(process.env)
and output in console is: "MISSING_ENV_VAR"
I tried removing new webpack.DefinePlugin({...}) from plugins in webpack config, but it didn't help.
In fact you successfully loaded the .env file with dotenv-webpack and the VUE_APP_VAR is accessible. It is just you cannot use the entire process.env object as dotenv-webpack does not allow it showing you MISSING_ENV_VAR instead.
If you chnange line 12 in your src\Layout.vue as follows:
- return process.env
+ return process.env.VUE_APP_VAR
you get your 123 value of the variable in your Vue app.
The reason is at the time of building your application with webpack dotenv-webpack replaces the explicit string process.env.SOME_EXPLICIT_VARIABLE_NAME_HERE existing in your code with the actual value of SOME_EXPLICIT_VARIABLE_NAME_HERE if that exist in the Webpack JS environment's actual process.env object.
This means you never get the entire process.env object accessible in your webpack bundle, and the bundle does not comprise the variable names like VUE_APP_VAR=123. This is the goal of dotenv-webpack.
You can get some more details in my answer here.
PS: DefinePlugin, being returned in the build config, could override process.env. It does so in Vue CLI (which is hardly justifiable). So its effect there sould be neutralized manually for dotenv-webpack to work within Vue CLI (v4 and v5) applications as expected.

vitetest: Failed to resolve import "$lib/stores/store"

tried running tests with vitest and it can seem to resolve dependencies from $lib/* and $app/* this is the error, Failed to resolve import "$lib/stores/store" from "src/lib/components/Hello.svelte". Does the file exist? here is the link to the playground https://gitlab.com/paulwvnjohi/hello-vitest
It seems Vitest is NOT automatically picking up your Vite config, since it's "hidden" in svelte.config.js and I'm sure there's tons of magic stuff SvelteKit adds, such as the resolve.alias paths for things like the $lib and $app imports to work.
I don't know if Vitest core would do something automatically in the future, but now there's the vitest-svelte-kit package you can use: https://github.com/nickbreaton/vitest-svelte-kit
Install the package:
npm i -D vitest-svelte-kit
Create a file vitest.config.js and put inside the method that magically extracts the correct vite config for you, according to your settings in svelte.config.js:
// vitest.config.js
import { extractFromSvelteConfig } from "vitest-svelte-kit"
export default extractFromSvelteConfig()
Worked for me!

Bundling a plugin with Rollup but having duplicate Vue.js package imported in the client app's bundle (Nuxt)

Dear Stack Overflow / Vue.js / Rollup community
This could be a noob question for the master plugin developers working with Vue and Rollup. I will write the question very explicitly hoping that it could help other noobs like me in the future.
I have simple plugin that helps with form validation. One of the components in this plugin imports Vue in order to programatically create a component and append to DOM on mount like below:
import Vue from 'vue'
import Notification from './Notification.vue' /* a very simple Vue component */
...
mounted() {
const NotificationClass = Vue.extend(Notification)
const notificationInstance = new NotificationClass({ propsData: { name: 'ABC' } })
notificationInstance.$mount('#something')
}
This works as expected, and this plugin is bundled using Rollup with a config like this:
import vue from 'rollup-plugin-vue'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
export default {
input: 'src/index.js',
output: {
name: 'forms',
globals: {
vue: 'Vue'
}
},
plugins: [
vue(),
babel(),
resolve(),
commonjs(),
terser()
],
external: ['vue']
}
As you can see, Vue.js is getting externalised in this bundle. The aim (and the assumption) is that the client app that imports this plugin will be running on Vue, therefore there's no need to bundle it here (assumption).
The very simple src/index.js that the bundler uses is below:
import Form from './Form.vue'
export default {
install(Vue, _) {
Vue.component('bs-form', Form)
}
}
Rollup creates 2 files (one esm and one umd) and references them in in the plugins package.json file like below:
"name": "bs-forms",
"main": "./dist/umd.js",
"module": "./dist/esm.js",
"files": [
"dist/*"
],
"scripts": {
"build": "npm run build:umd & npm run build:es",
"build:es": "rollup --config rollup.config.js --format es --file dist/esm.js",
"build:umd": "rollup --config rollup.config.js --format umd --file dist/umd.js"
}
Everything works as expected up to this point and the bundles are generated nicely.
The client app (Nuxt SSR) imports this plugin (using npm-link since it's in development) with a very simple import in a plugin file:
/* main.js*/
import Vue from 'vue'
import bsForms from 'bs-forms'
Vue.use(bsForms)
This plugin file (main.js) is added to nuxt.config.js as a plugin:
// Nuxt Plugins
...
plugins: [{src: '~/plugins/main'}]
...
Everything still works as expected but here comes the problem:
Since the clients is a Nuxt app, the Vue is imported by default of course but the externalised Vue module (by the forms plugin) is also imported in the client. Therefore there is a duplication of this package in the client bundle.
I guess the client app can configure its webpack config in order to remove this duplicated module. Perhaps by using something like a Dedupe plugin or something? Can someone suggests how to best handle situation like these?
But what I really want to learn, is the best practice of bundling the plugin at the first place, so that the client doesn't have to change anything in its config and simply imports this plugin and move on.
I know that importing the Vue.js in the plugin may not be a great thing to do at the first place. But there could be other reasons for an import like this as well, for example imagine that the plugin could be written in Typescript and Vue.js / Typescript is written by using Vue.extend statements (see below) which also imports Vue (in order to enable type interface):
import Vue from 'vue'
const Component = Vue.extend({
// type inference enabled
})
So here's the long question. Please masters of Rollup, help me and the community out by suggesting best practice approaches (or your approaches) to handle situations like these.
Thank you!!!!
I had the same problem and I found this answer of #vatson very helpful
Your problem is the combination of "npm link", the nature of nodejs module loading and the vue intolerance to multiple instances from different places.
Short introduction how import in nodejs works. If your script has some kind of library import, then nodejs initially looks in the local node_modules folder, if local node_modules doesn't contain required dependency then nodejs goes to the folder above to find node_modules and your imported dependency there.
You do not need to publish your package on NPM. It is enough if you generate your package locally using npm pack and then install it in your other project npm install /absolute_path_to_your_local_package/your_package_name.tgz. If you update something in your package, you can reinstall it in your other project and everything should work.
Here is the source about the difference between npm pack and npm link https://stackoverflow.com/a/50689049/6072503.
I have sorted this problem with an interesting caveat:
The duplicate Vue package doesn't get imported when the plugin is used via an NPM package (installed by npm install -save <plugin-name> )
However, during development, if you use the package vie npm link (like npm link <plugin-name>) then Vue gets imported twice, like shown in that image in the original question.
People who encounter similar problems in the future, please try to publish and import your package and see if it makes any difference.
Thank you!

webpack vuejs/ How to import a module only in Dev mode and ignore it in production mode?

In this simple vuejs application, I use axios-mock-adapter to mock all the axios request from my application.
All the mock is in the javascript module tests/mock/api.js. In order to use them, I will have to import them in main.js
import "../tests/mock/api";
It works well in Dev mode (npm run serve). However, I don't want this import in Production mode (npm run build). Is there a way to tell webpack ignore this line of import in main.js when we make npm run build?
This should work
if(process.env.NODE_ENV === 'development') require("../tests/mock/api");
See more in How can I conditionally import an ES6 module?

Add dependencies to Aurelia project

I set up an Aurelia project using the minimal project given here.
Then I added the fetch-client using npm install aurelia-fetch-client --save command. It updated package.json to contain following:
"dependencies": {
"aurelia-fetch-client": "^1.1.0"
}
But when I added import {HttpClient} from 'aurelia-fetch-client'; to my app.js file and tried running the app, but got following error:
system.js:4 GET http://localhost:5000/aurelia-fetch-client 404 (Not Found)
How do I add that? Where does this project keep track of its dependencies? I have seen lots of tutorials which help setting up the fetch client in aurelia cli projects. How about the project given here?
First, follow Fabio Luz's advice above and actually install either aurelia-cli or a skeleton framework.
Then, I have found this next step to be one of the most common sources of confusion for most people who are learning Aurelia. After installing new modules via npm, you have to manually list them as a dependency in aurelia.json (in your aurelia_project folder). For example, you would list aurelia-fetch-client as follows:
"dependencies": [
"aurelia-binding",
"aurelia-bootstrapper",
"aurelia-dependency-injection",
"aurelia-event-aggregator",
...
"aurelia-fetch-client",
...
After it is listed as a dependency, it will be included in the vendor.js bundle (in the CLI, by running au run --watch) so that it can be accessed by your application when you import it in individual components.
import {HttpClient} from 'aurelia-fetch-client';
For me it worked like this (using the project generated by the CLI):
npm i whatwg-fetch --save
npm i aurelia-fetch-client --save
add "aurelia-fetch-client" to dependencies in aurelia_project/aurelia.json
example of app.js:
import {HttpClient} from 'aurelia-fetch-client';
let client = new HttpClient();
export class App{
activate(){
client.fetch('http://...json');
.then(response => response.json())
.then(data =>{
console.log(data)
});
}
}
You can also install dependencies with the CLI itself.
It doesn't always get it 100% correct but can point you in the right direction if struggling.
For example au install aurelia-fetch-client
It will download the dependency, add to packages.json and attempt to create an entry for the bundling.