How to configure rollup with Vue? - javascript

I am working on project using Vue.js, bundling with Rollup.
Here is my rollup.config.js file
import vue from 'rollup-plugin-vue2'
import less from 'rollup-plugin-less2';
import buble from 'rollup-plugin-buble'
import nodeResolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import uglify from 'rollup-plugin-uglify'
import livereload from 'rollup-plugin-livereload'
import serve from 'rollup-plugin-serve'
const plugins = [
vue({'css':'none'}),
less({output: "dist/build.css"}),
buble({exclude: 'node_modules/**'}),
nodeResolve({browser: true, jsnext: true}),
commonjs()
]
if (process.env.NODE_ENV === 'production') {
plugins.push(uglify())
}
if (process.env.NODE_ENV === 'development') {
plugins.push(livereload('dist'))
plugins.push(serve({
contentBase: "",
open: true
}))
}
export default {
input: 'src/main.js',
output: {
file: 'dist/build.js',
format: 'iife',
sourcemap: true,
//external: ["vue","vue-router"],
},
//external: ["vue","vue-router"],
plugins
}
Here is my main.js file.
import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router";
Vue.use(VueRouter);
const Foo = {template: '<div>foo</div>'}
const Bar = {template: '<div>bar</div>'}
const routes = [
{path: '/foo', component: Foo},
{path: '/bar', component: Bar}
];
const router = new VueRouter({
routes
});
var app = new Vue({
router: router,
el: '#app',
render: h => h(App)
});
I have this error after running my project
Uncaught ReferenceError: process is not defined
If I use Vue as external lib and uncomment this ["vue","vue-router"], external: ["vue","vue-router"] all working fine.
How to make my project compile and work with rollup?

I had the same problem. Found a solution here: https://github.com/rollup/rollup/issues/487
You have to use the rollup replace plugin to replace all calls to process.env.NODE_ENV in all imported files like so:
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify( 'production' )
})
]

Related

Using vue-router in a Vuejs 2 application throws '"export 'createRouter' was not found in 'vue-router'' error message

I am trying to set up a vue-router for an application in Vue 2/rails.
I installed vue-router through yarn =>
yarn add vue-router#2
That's my router =>
import { createWebHistory, createRouter } from "vue-router"
import PageHome from '../components/PageHome.vue'
import TermsAndConditions from '../components/TermsAndConditions.vue'
const routes = [
{
path: "/",
name: "PageHome",
component: PageHome,
},
{
path: "/terms-conditions",
name: "TermsAndConditions",
component: TermsAndConditions
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
and that's my application file
import Vue from 'vue/dist/vue.esm'
import router from '../router/index'
Vue.use(router)
import PageHome from '../components/PageHome.vue'
import TermsAndConditions from '../components/TermsAndConditions.vue'
const images = require.context('../images', true)
require('../stylesheets/application.scss')
document.addEventListener('DOMContentLoaded', () => {
if(document.getElementById('v-app')) {
new Vue({
el: '#v-app',
store,
components: {
PageHome,
TermsAndConditions
}
})
}
})
I have added those lines in a file where I want to see the links.
<router-link to="/">Home</router-link>
<router-link to="/TermsAndConditions">Terms and conditions</router-link>
<router-view/>
That's what is in my package.json =>
"vue": "^2.6.12",
"vue-loader": "^15.9.6",
"vue-router": "2",
"vue-template-compiler": "^2.6.12",
"vue-turbolinks": "^2.2.2",
Unfortunately I get this error message and I don't really know what to do with it.
Failed to compile.
./app/javascript/router/index.js 13:15-27
"export 'createRouter' was not found in 'vue-router'
Any help is very welcome !!
Can't find documentation for VueRouter2, but in VueRouter3 you have to do it like this:
import VueRouter from 'vue-router';
...
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/', component: Home },
{ path: '/foo', component: Foo }
]
})
The code you send as a question is for VueRouter4 that's used with Vue3
For Vue 2 projects you have to call Router.
import Router from 'vue-router';
const router = new Router({
...
})
export default router
createRouter is for Vue 3 projects(Vue Router v4).

Vue router routes are not work in MEVN stack after build project

I Created a Vue application as my project. That works fine on the development server but it is not working after the build.
This is my vue router ‘s index file.
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Dashboard from '../views/Dashboard.vue'
import ViewOrder from '../views/ViewOrder.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path:'/dashboard',
name:'Dashboard',
component:Dashboard
},
{
path:'/vieworder/:orderid',
name:'ViewOrder',
component:ViewOrder,
props:true
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
This is my props section in the vieworder route.
props:['orderid'],
This is my function for open that view in component
viewOrderData(){
if(this.selectedorder.length == 1){
var routeData = this.$router.resolve({name:"ViewOrder",params:{orderid:this.selectedorder[0]._id}});
window.open(routeData.href,'_blank')
}
}
This is my Vue.config.js file
const path = require("path");
module.exports = {
transpileDependencies: [
'vuetify'
],
outputDir:path.resolve(__dirname,'../application/public'),
devServer:{
proxy:{
'/api':{
target:'http://localhost:3000'
}
}
}
}
I use Express as server,
Mongoose to database management,
axios and bodiparser to communicate

Nothing renders in vue.js project

After creating a new Vue project with Vue CLI 3 and deleting all default views and components, I created two new views. None of them appears when changing url and instead I see blank page and no errors in console. In Chrome DevTools inspector I see that <div id="app"></div> is empty. Vue.js Devtools plugin doesn't trigger Vue on the page at all. I think I might miss something in my settings but can't find what can cause such behaviour.
This my main.js:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount('#app');
This is my App.vue:
<template>
<div id="app">
<router-view />
</div>
</template>
This is index.js of router
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
import Auth from '../views/Auth.vue';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/auth',
name: 'auth',
component: Auth,
},
];
const router = new VueRouter({
mode: 'history',
scrollBehavior() {
return { x: 0, y: 0 };
},
base: process.env.BASE_URL,
routes,
});
export default router;
This is vue.config.js
module.exports = {
configureWebpack: {
devtool: 'source-map',
},
chainWebpack: config => {
config.module
.rule('js')
.use('babel-loader')
.loader('vue-loader')
.tap(options => {
return options;
});
},
css: {
loaderOptions: {
sass: {
data: `
#import "#/assets/styles/variables.scss";
#import "#/assets/styles/global.scss";
`,
},
},
},
};
Home.vue:
<template>
<h1>Home page</h1>
</template>
<script>
export default {
name: 'home',
};
</script>
If you are using vue-cli you shouldn't have vue.config.js populated - as a fresh start -, hence there is a good chance your config is faulty.

Vue.js ES6 import export

Well I'm facing a problem with importing multiple modules in ES6, using babel. I'm trying structure my app in Vue.js as a modular components (or in precise the structure that follows in Angular2 for features)
app/
moduleA/
components/
vuex/
index.js
routes.js
moduleB/
components/
vuex/
index.js
routes.js
index.js
routers.js
vuex.js
components.js
router/
vuex/
components/ -> shared
main.js
Now, my question is, how can I export and import all modules to work perfectly?
So let's say for the moduleA routes I've the following code
//moduleA/routes.js
export const routes = [
{ path: '', name: 'home', components: {
default: Home,
'header-top': Header
} }
];
And again for moduleB routes
//moduleA/routes.js
export const routes = [
{ path: '/user', components: {
default: User,
'header-bottom': Header
}, children: [
{ path: '', component: UserStart },
{ path: ':id', component: UserDetail },
{ path: ':id/edit', component: UserEdit, name: 'userEdit' }
] }
];
Then, how can I import and get this work. Please help.
Thanks
You'll need to tell the root router and root vuex where your modules are located.
So, bundle all your routes:
import { routes as moduleA } from './moduleA';
import { routes as moduleB } from './moduleB';
export default [ ...moduleA, ...moduleB, ];
Do the same for your vuex:
import { vuex from moduleA } from './moduleA';
import { vuex as moduleB } from './moduleB';
export default { moduleA, moduleB, };
Now, in your global vuex/:
import Vue from 'vue';
import Vuex from 'vuex';
import vuex from '../app';
export default new Vuex.Store({
modules: vuex,
});
And, for your router/:
import Vue from 'vue';
import Router from 'vue-router';
import { routers } from '../app';
Vue.use(Router);
export default new Router({
routes: routes,
});

Importing Vue components in TypeScript file

I have been trying to use Vue.js with TypeScript and I came across this repo.
I faced issues here that I am getting error while importing Vue Single Component File from TypeScript. I am using Visual Studio Code. Please see error below.
main.ts:
// 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 * as Vue from 'vue'
import App from './App'
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
VS Code error:
1 ERROR
• main.ts
[ts] Cannot find module './App'. (4 17)
From Alex Jover:
If your editor is yelling at the line import App from './App' in main.js file about not finding the App module, you can add a vue-shim.d.ts file to your project with the following content:
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
and write :
import App from './App.vue'
instead of
import App from './App'
Check out vue-class-component. Basically, you must add appendTsSuffixTo: [/\.vue$/] to ts-loader's options and esModule: true to vue-loader's options.
// webpack.config.js
{ modules: { rules: [
{
test: /\.ts$/,
exclude: /node_modules|vue\/src/,
loader: "ts-loader",
options: { appendTsSuffixTo: [/\.vue$/] }
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
esModule: true
}
}
]}}
I may have missed something else.
Had this issue even with a vue.d.ts because I had multiple declarations in the same file. Had to split them up like this:
In vue 3 this is the vue.d.ts that has to be somewhere in a path that is included in your tsconfig.json.
// vue.d.ts
declare module '*.vue' {
import { DefineComponent } from 'vue'
// eslint-disable-next-line #typescript-eslint/no-explicit-any, #typescript-eslint/ban-types
const component: DefineComponent<{}, {}, any>
export default component
}
Also I wanted to set global properties on my vue instance and have them available in any component via intellisense. After adding the following code to my vue.d.ts file, the editor complained when I imported .vue files into typescript. So I had to add a separate vue-runtime.d.ts file, or it wouldn't work:
// vue-runtime.d.ts
import '#vue/runtime-core'
declare module '#vue/runtime-core' {
interface ComponentCustomProperties {
customFunction: (val: number) => string;
}
}
Then customFunction will be registered on all components!
When using the vue-cli, adapt vue-loader-conf.js as follows:
var utils = require('./utils')
var config = require('../config')
var isProduction = process.env.NODE_ENV === 'production'
module.exports = {
loaders: utils.cssLoaders({
sourceMap: isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap,
extract: isProduction, esModule: true
}), esModule: true
}
FYI, you can generate . d.ts file for your components by turn on declaration generate in tsconfig. json, copy them to the source dir, see what you've got!

Categories