Vue3 works with unpkg but not with npm + webpack - vue.js

I'm trying to set up Vue3 so that I can use it via npm + webpack. For some reason the component does not get mounted and no error is shown. If I instead use unpkg it works. How can I make the npm + webpack option work?
I have "vue": "^3.1.5" in my package.json and the following webpack config:
module.exports = {
mode: 'production',
entry: {
provider: './src/components/provider.js',
requester: './src/components/requester.js',
},
optimization: {
minimize: false
},
output: {
path: `${__dirname}/../public`,
filename: '[name].js',
}
}
requester.js:
import { createApp } from 'vue'
createApp({
template: `
<div>
<div>
<h2>Números recibidos</h2>
{{ receivedNumbers }}
<ul>
<li v-for="n in receivedNumbers">{{ n }}</li>
</ul>
</div>
</div>
`,
data() {
return {
receivedNumbers: [1,2,3],
numberRequestIsOpen: false,
}
},
}).mount('#requester-component');
requester.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>requester</h1>
<div id="requester-component"></div>
<script src="requester.js"></script>
</body>
</html>
resulting html
<h1>requester</h1>
<div id="requester-component" data-v-app=""><!----></div>
<script src="requester.js"></script>
In the other hand, if I add <script src="https://unpkg.com/vue#next"></script> in the head tag of my html and change the js to:
Vue.createApp({
//
}).mount('#requester-component');
then the resulting html is
<h1>requester</h1>
<div id="requester-component" data-v-app=""><div><div><h2>Números recibidos</h2> [
1,
2,
3
] <ul><li>1</li><li>2</li><li>3</li></ul></div></div></div>
<script src="requester.js"></script>
which is the expected output.
Link to the repo in case it helps to play around. Last commit adds the unpkg has, and the previous one has the npm version

https://github.com/vuejs/vue-next/issues/4275
In order to use the functionality of the vue.js template, you need to load the finished package with the compiler and runtime, but vue.js by default loads the runtime only version, so you need to explicitly specify the version (vue.esm-bundler.js)
Adding
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm-bundler.js'
}
}
solved the issue.

Related

Eslint CSS Modules tree shaking doesn't work in Vue template (Composition API)

I'm using Vue 3 with composition API and CSS Modules. Trying to highlight unused and undefined classes. It works correctly in <script setup>, but there are no errors in tag <template>.
<script setup>
import styles from 'view/pages/contact-form.css'; /* It has error, as it no classes used from here (except .contact-form) */
const form = styles['contact-form']; /* no error, it's correct */
const form2 = styles['contact-error']; /* error, because no class in css, it's correct */
</script>
<template>
<div :class="styles['contact-for']"> /* expected to have error because class doesn't exist, not correct */
<div :class="styles['contact-form__header']">
<div :class="styles['contact-form__header-section']">
<span :class="styles['contact-form__title']">
{{ messages.title }}
</span>
</div>
</div>
</div>
</template>
Library was used https://www.npmjs.com/package/eslint-plugin-css-modules
Also tried https://www.npmjs.com/package/postcss-modules-extract-imports because postcss is used in project
eslintrc.js config:
module.exports = {
globals: {
BUNDLE: true,
NODE_ENV: true,
},
plugins: ['postcss-modules'],
extends: [
'plugin:postcss-modules/recommended',
],
rules: {
'postcss-modules/no-unused-class': 'error'
},
settings: {
'postcss-modules': {
'baseDir': 'src/'
}
}
};

How can I use Vue2 old component (.vue file) with a new Vue3 project?

Vue3 version is out, but I don't see any example of using old components code with the new version. How come?
Here is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Vue 3 Example using Vue 2 component</title>
<script src="https://unpkg.com/vue#next"></script>
</head>
<body>
<div id="app">
<h1>{{ product }}</h1>
<my-old-vue-component :my-prop="'my string in here'"></my-old-vue-component>
</div>
<script src="./main.js"></script>
<script src="./myOldVueComponent.vue"></script>
<!-- Mount App -->
<script>
const mountedApp = app.mount('#app')
</script>
</body>
</html>
Here is my main.js:
const app = Vue.createApp({
data() {
return {
product: 'my product',
}
}
})
Here is my old simple Vue2 component (myOldVueComponent.vue):
<template>
<div>
{{myProp}}
</div>
</template>
<script>
export default {
name: "myOldVueComponent",
props: {
myProp: { type: String }
},
data() {
return {
},
}
</script>
I'm getting error on the import of ".vue" file:
uncaught SyntaxError:
Unexpected token '<'
(meaning the <template> tag inside my old component.
Vue2 components works in Vue3. That is not the issue in your code.
The problem is here:
<script src="./myOldVueComponent.vue"></script>
You can't import .vue files directly in a browser. You could not do it in vue 1,2 and you can't yet in vue 3. The browser is not able to understand that syntax, there needs to be a bundler that converts your code is something that can be used by the browser. The most popular bundlers are webpack, rollup ecc ecc
See: https://v3.vuejs.org/guide/single-file-component.html#for-users-new-to-module-build-systems-in-javascript
I highly recommend using the Vue cli to setup your project, especially if you are a beginner to the npm/bundlers world

Vue.js routing cannot do

My vue.js app routing is not working, please help, there is not a lot of code , simply copy paste this code in your index.html, you'll see the weird errors . its like we cant use scripts when using the vue router.:
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Starter Vue.js Bt4</title>
<!-- Bootstrap CSS CDN -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<!-- Our Custom CSS -->
<link rel="stylesheet" href="style.css">
<!-- Font Awesome JS -->
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
<!-- Load polyfills to support older browsers -->
<script src="https://polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver"></script>
<!-- Required scripts -->
<script src="https://unpkg.com/vue#latest/dist/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue#latest/dist/bootstrap-vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div class="wrapper" id="app">
<router-link to="/users">Users</router-link>
<router-link to="/home">Go to HOME</router-link>
<router-view></router-view>
<script type="text/x-template" id="users">
<p>
<ul id="demo">
<li v-repeat="items" >
{parentMsg}} {{childMsg}}
</li>
</ul>
</p>
</script>
<script type="text/x-template" id="home">
<button v-on:click="count++">Vous mavez cliqué {{ count }} fois.</button>
</script>
</div>
</body>
<script>
var Home = {
data: function () {
return {count: 0}
},template: "#home"
}
const Users= {
template: "#users",
data: {
items: [
{ childMsg: 'Foo' },
{ childMsg: 'Bar' }
]
}
}
const routes = [
{ path: '/home', component:Home},
{ path: '/users', component: Users}
]
const router = new VueRouter({
routes // short for `routes: routes`
})
const app = new Vue({
router
}).$mount('#app')
</script>
this is the error it doesnt work, please help : Error nothing works, displaying users is impossible :
[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. vue.js:634:17
[Vue warn]: Property or method "count" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
(found in <Root>) vue.js:634:17
[Vue warn]: Property or method "childMsg" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
(found in <Root>) vue.js:634:17
[Vue warn]: Property or method "items" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Anonymous>
<Root> vue.js:634:17
[Vue warn]: Failed to resolve directive: repeat
(found in <Anonymous>)
AngularJs was working all of the time, why this is not working ?
Thanks for helping me, nothing works, files .vue not working either, no explanation, im going back to angularJs thank you
EDIT :
template literal not working with routing neither :
const Users= {
template: `
<p>
<ul id="demo">
<li v-repeat="items" >
{parentMsg}} {{childMsg}}
</li>
</ul>
</p>
`,
data() {
return {items: [
{ childMsg: 'Foo' },
{ childMsg: 'Bar' }
]}
}
}
the error :
[Vue warn]: Failed to resolve directive: repeat
[Vue warn]: Property or method "childMsg" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
(found in <Anonymous>)
EDIT 2: It is working with the following template litteral, but i dont want this kind of templating at all , it is not easy to write inside of the javascript, I need to use the balise or .vue files, and nothing works .:
const Users= {
template: `
<p>
<ul id="demo">
<li v-for="item in items" >
{{item.childMsg}}
</li>
</ul>
</p>
`,
data() {
return {items: [
{ childMsg: 'Foo' },
{ childMsg: 'Bar' }
]}
}
}
Edit, after reading this : https://vuejs.org/2015/10/28/why-no-template-url/
I will try to write templates inside of the JS code
EDIT : Resolved there :Unable to add any module without WebPack
You have to update couple of things
const Users= {
template: "#users",
data() {
return {
items: [
{ childMsg: 'Foo' },
{ childMsg: 'Bar' }
]
};
}
}
You haven't added Home component but still you are using, just remove Home from routes
const routes = [
{ path: '/users', component: Users}
]

Can we make vue.js application without .vue extension component and webpack?

Note: Can we write vue.js large application without using any compiler for code like currently i see all example use webpack now to make vue.js code compatible for browser .
I want make vue.js application without webpack and without using .vue extension. Is it possible? if it is possible, can you provide a link or give sample how to use routing in that case.
As we make component in .vue extension can be make component in .js extension and use application as we do in angular 1 where we can make whole app without any trans-compiler to convert the code.
Can be done that in html , css , js file only and no webpack sort of thing.
What i have done .
index.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>vueapp01</title>
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
main.js this file added in webpack load time
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
Hello route
Helloworld route
{{route}}
<router-view/>
<!-- <hello></hello> -->
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
route : "This is main page"
}
}
}
</script>
router
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '#/components/HelloWorld'
import Hello from '../components/Hello'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/hello',
name: 'Hello',
component: Hello
}
]
})
I have done something like this . Can we do this by just html , css , js file only with not webpack to compile code . Like we do in angular 1 .
Thanks
As stated in this jsFiddle: http://jsfiddle.net/posva/wtpuevc6/ , you have no obligation to use webpack or .vue files.
The code below is not from me and all credit goes to this jsFiddle creator:
Create an index.html file:
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script>
<script src="/js/Home.js"></script>
<script src="/js/Foo.js"></script>
<script src="/js/router.js"></script>
<script src="/js/index.js"></script>
<div id="app">
<router-link to="/">/home</router-link>
<router-link to="/foo">/foo</router-link>
<router-view></router-view>
</div>
Home.js
const Home = { template: '<div>Home</div>' }
Foo.js
const Foo = { template: '<div>Foo</div>' }
router.js
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo }
]
})
index.js
new Vue({
router,
el: '#app',
data: {
msg: 'Hello World'
}
})
Appreciate the framework...
Just a sidenote: .vue files are really awesome, you should definitely try them if not using them is not a requirement
I have started learning vue.js also and I am not familiar with webpack and stuff and I also wanted to still separate and use .vue files as it makes management and code cleaner.
I have found this library:
https://github.com/FranckFreiburger/http-vue-loader
and a sample project using it:
https://github.com/kafkaca/vue-without-webpack
I am using it and it seems to work fine.
You perfectly can, but with a lot of disadvantages. For example: you cannot easily use any preprocessor, like Sass or Less; or TypeScript or transpile source code with Babel.
If you don't need support for older browser, you can use ES6 modules today. Almost all browsers support it. See: ES6-Module.
But Firefox doesn't support dynamic import(). Only Firefox 66 (Nightly) support it and need to be enabled.
And if that wasn't enough, your web application will not be indexed. It's bad for SEO.
For example, Googlebot can craw and index Javascript code but still uses older Chrome 41 for rendering, and it's version don't support ES6 modules.
If that are not disadvantages for you, then you can do this:
Remove any thirty party library import like Vue, VueRouter, etc. And include those in the index.html file using script tags. All global variables are accesible in all es6 modules. For example, remove this line from main.js and all .vue files:
import Vue from 'vue';
And add this line in your index.html:
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
Rewrite all .vue files and change file extension to .js. For example, rewrite something like this:
<template>
<div id="home-page">
{{msg}}
</div>
</template>
<script>
export default {
data: function() {
return { msg: 'Put home page content here' };
}
}
</script>
<style>
#home-page {
color: blue;
}
</style>
to something like this:
let isMounted = false; /* Prevent duplicated styles in head tag */
export default {
template: `
<div id="home-page"> /* Put an "id" or "class" attribute to the root element of the component. Its important for styling. You can not use "scoped" attribute because there isn't a style tag. */
{{msg}}
</div>`,
mounted: function () {
if (!isMounted) {
let styleElem = document.createElement('style');
styleElem.textContent = `
#home-page {
color: blue;
}
`;
document.head.appendChild(styleElem);
isMounted = true;
}
},
data: function () {
return {
msg: 'Put home page content here'
};
}
}
It is all. I put an example in this link
P.S. Text editing without syntax highlighting can be frustrating. If you use Visual Studio Code you can install Template Literal Editor extension. It allows editing literal strings with syntax highlight. For styles select CSS syntax, and for templates HTML syntax. Unknown tag in HTML are highlighted differently. For solve this, change the color theme. For example, install Brackets Dark Pro color theme or any theme do you like.
Regards!
For sure you can. We did a project with Vue, and we had couple of problems during compiling .vue files.
So we switched to structure with three separate files.
But be aware that you need webpack anyway. The idea of Vue was to split huge projects into components, so using template inside .js file it's pretty normal.
So take a look at
html-loader
And
css-loader
Using these modules you can write something like this:
component.js
// For importing `css`. Read more in documentation above
import './component.css'
// For importing `html`. Read more in documentation above
const templateHtml = require('./component.html')
export default {
name: 'ComponentName',
components: { /* your components */ },
mixins: [/* your mixins */ ],
template: templateHtml,
computed: .....
}
component.css
#header {
color: red
}
component.html
<div id="header"></div>
BUT
You need to know that HTML file should be written in the same way as I you will have it in template property.
Also, take a look at this repo, maybe you will find something useful here
Vue-html-loader. It is a fork from html-loader by Vue core team.
In vuejs 3 you you can do it in an ES6 modular fashion (no webpack or other tools required):
index.html
<!DOCTYPE html>
<html>
<head>
<script type="importmap">
{
"imports": {
"vue": "https://unpkg.com/vue#3.0.11/dist/vue.esm-browser.js",
"vue-router": "https://unpkg.com/vue-router#4.0.5/dist/vue-router.esm-browser.js",
"html" : "/utils/html.js"
}
}
</script>
<script src="/main.js" type="module"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>
main.js
import { createApp, h } from 'vue';
import {createRouter, createWebHashHistory} from 'vue-router';
import App from './components/App.js';
const routes = [//each import will be loaded when route is active
{ path: '/', component: ()=>import('./components/Home.js') },
{ path: '/about', component: ()=>import('./components/About.js') },
]
const router = createRouter({
history: createWebHashHistory(),
routes,
})
const app = createApp({
render: () => h(App),
});
app.use(router);
app.mount(`#app`);
components/App.js
import html from 'html';
export default {
name: `App`,
template: html`
<router-link to="/">Go to Home</router-link>
<router-link to="/about">Go to About</router-link>
<router-view></router-view>
`};
components/Home.js
import html from 'html';
export default {
template: html`
<div>Home</div>
`};
components/About.js
import html from 'html';
export default {
template: html`
<div>About</div>
`};
utils/html.js
// html`..` will render the same as `..`
// We just want to be able to add html in front of string literals to enable
// highlighting using lit-html vscode plugin.
export default function () {
arguments[0] = { raw: arguments[0] };
return String.raw(...arguments);
}
Notes:
Currently (04/2021) importmap works only on chrome (firefox in progress). To make the code compatible with other browsers also, just import (on each .js file) the dependencies directly from the urls. In this case though vue-router.esm-browser.js still imports 'vue', so you should serve an updated version of it, replacing import { .... } from 'vue' with import { .... } from 'https://unpkg.com/vue#3.0.11/dist/vue.esm-browser.js'
To avoid waterfall loading effect, you can add <link rel="modulepreload" href="[module-name]"> entries to index.html to start preloading some or all modules asynchronously before you need them.
A Related article
Vue can be included on a single html page quite simply:
Vue 3 minimal example:
<script src="https://unpkg.com/vue#3/dist/vue.global.js"></script>
<div id="app">{{ message }}</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
message: 'Hello Vue!'
}
}
}).mount('#app')
</script>
Vue 2 minimal example, with Vuetify
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/#mdi/font#6.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div id="app">
<v-app>
<v-main>
<v-container>Hello world</v-container>
</v-main>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2.x/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify#2.x/dist/vuetify.js"></script>
<script>
new Vue({
el: '#app',
vuetify: new Vuetify(),
})
</script>
</body>
</html>
vue 2 guides:
https://v2.vuejs.org/v2/guide/installation.html#CDN
https://vuetifyjs.com/en/getting-started/installation/#usage-with-cdn
vue 3 guide: https://v2.vuejs.org/v2/guide/installation.html#CDN

Load script inside the <template> tag using nuxt.js and vue.js

I am using nuxt.js (which is based on vue.js) to build a custom website, I need to load an Ad on my website using a provided by my partners, and I need to place it at a specific place on my html code. So I add it to my component template but it does not render.
Here is a sample of the code I'm trying to get to work
<template>
<div>
<div class="columns is-centered is-mobile">
<p>Hello World</p>
</div>
<div>
<script type="text/javascript" src="sampleSource"></script>
</div>
</div>
</template>
<script>
export default {
}
</script>
the script that comes from src="sampleSource" doesn't load and doesn't execute, any help is appreciated. Thank you very much.
On the page, use in metadata with body: true for add script inside body
<script>
export default {
head: {
script: [
{ src: '/head.js' },
// Supported since Nuxt 1.0
{ src: '/body.js', body: true },
{ src: '/defer.js', defer: '' }
]
}
}
</script>
You need to create a (sample-source.vue) component and take it to the /components dir.
After that you need to create a plugin for your component: /plugins/sample-source.js
sample-source.js :
import Vue from 'vue'
import SampleSource from '~/components/sample-source.vue'
Vue.use(SampleSource)
nuxt.config.js:
...
module.export
...
plugins: [
'~/plugins/sample-source.js'
]
After these steps you can use your component everywhere.
Or the easiest way:
<template>
<div>
<div class="columns is-centered is-mobile">
<p>Hello World</p>
</div>
</div>
</template>
<script>
export default {
mounted () {
----your code here from sampleSource.js----
}
}
</script>