javascript file is not working in vue cli html template - javascript

I'm using vue cli to create a multipage web app.
The file structure is like below:
- public
- index.html
- tables.html
- us.html
- guide.html
- src
- main.js
and the main.js is:
import Vue from 'vue'
import router from './router'
Vue.config.productionTip = false
console.log('hello world!');
let appExists = document.querySelector('#app') != undefined;
if(appExists){
new Vue({
router,
render: h => h(App),
mounted(){
console.log('hi!');
}
}).$mount('#app')
}
What I'm looking for:
I want main.js file to be loaded into tables.html file.
What is happening:
main.js is not working in any file except index.html.
What I have done:
As I searched, I realized that vue cli loads the main.js only in index.html and not in any other file. when I try to load the main.js using <script src="/src/main.js"></script> in tables.html, I always get the error Uncaught SyntaxError: expected expression, got '<'. I tried some solutions like https://cli.vuejs.org/config/#pages but it didn't change anything at all.
And the question is:
What should I do to use main.js in other files?

I figured it out. Everything in vue cli works with the combination of webpack plugins.
The plugin which connects the files together is called "HtmlWebpackPlugin".
First, install the plugin using:
npm i html-webpack-plugin
Then you can tell this plugin: "Hey I have another page in my project! Please connect main.js to it" by writing the code below in vue.config.js:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
configureWebpack: {
plugins: [
new HtmlWebpackPlugin({
filename: 'tables.html',
template: './public/tables.html',
}),
new HtmlWebpackPlugin({
filename:'index.html',
template: './public/index.html',
}),
]
}
}
Hope it will help other people who are facing the same issue!

Related

Vue 3 & Vite built application shows blank page

I have a problem trying to make a build of a new Vue3.js + Vite.js application. Once my application is finished i made the npm run build action in order to generate the final deployment files.
Problem is that when I try to see the generated page, it only shows a white page.
Opening the inspection tool I can see how the main generated javascript files are like not being found by the static index.html:
Failed to load resource: net::ERR_FAILED index.7b66f7af.js:1
Ok. I found the solution searching a bit, and I see how this problem also occurred actually in Vue 2.
The only thing that you have to do for solvif is add base: './' in your vite.config.js, like this:
import {
defineConfig
} from 'vite'
import vue from '#vitejs/plugin-vue'
import vuetify from '#vuetify/vite-plugin'
const path = require('path')
export default defineConfig({
plugins: [
vue(),
vuetify({
autoImport: true,
}),
],
define: {
'process.env': {}
},
resolve: {
alias: {
'#': path.resolve(__dirname, 'src'),
},
},
base: './',
})
Hope it helps you all!
I had this problem also, and found a solution:
It looks like the awnser given by #javi But it's different. I found out that the situation changes when you deploy your application.
In vite config there is a setting called 'base' filled in like: base: mode === 'production' ? '/nameExample/' : '/', this will put the output of your project on the endpoint : 'nameExample'. If you go in production this fails and shows a blank page, and you need to changes this nameExample to '/' to show the projectbuild online. But than it shows a blank page in development because it mismatches the name of the project. Hope this will help you.

Uncaught TypeError: $(...).hsSideNav is not a function, with webpacker in Rails 6

I have a Rails 6 application working with the asset pipeline, which I'm trying to move to webpacker in order to use turbo. So far I've managed to correctly set up turbo. The app uses some bootstrap plugins though, hsSideNav among them, and I'm getting an error I haven't been able to solve: Uncaught TypeError: $(...).hsSideNav.
I've placed a copy of the hsSideNav file in app/javascript/hs-navbar-vertical-aside/hs-navbar-vertical-aside.js.
Here's my app/javascript/packs/application.js:
require("#rails/ujs").start()
import "#hotwired/turbo-rails"
require("#rails/activestorage").start()
require("channels")
require("jquery")
import 'bootstrap/dist/js/bootstrap'
import 'bootstrap/dist/css/bootstrap'
require("hs-navbar-vertical-aside/hs-navbar-vertical-aside")
And my config/webpack/environment.js:
const { environment } = require('#rails/webpacker')
const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/dist/jquery.min',
jQuery: 'jquery/dist/jquery.min'
})
)
module.exports = environment
What am I doing wrong? Is there another way to load jQuery plugins in webpacker?

When I use env files I got undefined when I read the vars

I created a Vue application using vue/cli: vue create my-vue. I want to build this project in next mode (like qa, stage, next ...), so I followed the steps in the Vue docs. I created the .env.next file in the root project with this content:
FOO=next
In my main.js, I log it to the console:
import Vue from 'vue'
import App from './App.vue'
console.log({ f: process.env.FOO }); // <----- undefined. why?
console.log({ f: process.env.VUE_APP_FOO }); // <----- undefined. why?
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
After that, I run the build:
npm run build -- --mode next
When I run the dist folder in the console, I get undefined. I searched for "next" in the bundle, but it's not there.
Why? How can I use .env vars in my build output?
As stated in the docs you've linked:
Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. It is to avoid accidentally exposing a private key on the machine that could have the same name.
For FOO to be available in the build output, rename it to VUE_APP_FOO in your .env file, and update references accordingly:
console.log({ f: process.env.VUE_APP_FOO })

import Stencil in Svelte

I have a Monorepo with a svelte project and a Stencil component library. On the Stencil website they very clearly describe how to integrate the library with, for example, Angular
import { defineCustomElements } from 'test-components/loader';
defineCustomElements(window);
Super easy. But now I would like to use it too in a Svelte project ..... not so super easy anymore :(
When I try to do something similar as described above I get serious errors
fbp/dist is where the Stencil files are.
When I build my Stencil project first and copy my dist into the public folder and load ./dist/fbp.js in the head of index.html it all works. But it would be a lot easier if I could include it similar as it does with Angular. Any suggestions?
Update: Added emitCss which gives
Somewhere at the end it stats: Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
UPDATE: With the fixes of #Sambor, Svelte is now able to download the web component, which unfortunately fails
I have created a new project and I manage to reproduce the same problem.
At first, I was thinking is related to typescript and I've tried bunch of plugins in rollup like : #tscc/rollup-plugin-tscc, rollup-plugin-typescript but it didn't work.
I also tried rollup-plugin-amd with same results...
Then I've tried to change the main output format and use es instead of iife.
This way it also required to change the output to a directory instead of file (because of multiple file generation).
And surprisingly this way it seems to work.
here is my code:
/// index.html
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<title>Test</title>
<link rel='stylesheet' href='build/bundle.css'>
<script type="module" defer src='build/main.js'></script>
</head>
<body>
</body>
</html>
Note: main.js is imported as module.
/// main.js
import App from './App.svelte';
import { applyPolyfills, defineCustomElements } from '../my-comp/loader';
applyPolyfills().then(() => {
defineCustomElements(window);
});
const app = new App({ target: document.body });
export default app;
/// rollup.config
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import postcss from 'rollup-plugin-postcss';
import autoPreprocess from 'svelte-preprocess';
import json from '#rollup/plugin-json';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'es',
name: 'app',
dir: 'public/build'
},
plugins: [
json(),
svelte({
// Enables run-time checks when not in production.
dev: !production,
// Extracts any component CSS out into a separate file — better for performance.
css: css => css.write('public/build/bundle.css'),
// Emit CSS as "files" for other plugins to process
emitCss: true,
preprocess: autoPreprocess()
}),
resolve({
browser: true,
dedupe: importee => importee === 'svelte' || importee.startsWith('svelte/')
}),
commonjs(),
postcss({
extract: true,
minimize: true,
use: [
['sass', {
includePaths: ['./node_modules']
}]
]
}),
// In dev mode, call `npm run start` once the bundle has been generated
!production && serve(),
// Watches the `public` directory and refresh the browser on changes when not in production.
!production && livereload('public'),
// Minify for production.
production && terser()
],
watch: {
clearScreen: false
}
};
function serve() {
let started = false;
return {
writeBundle() {
if (!started) {
started = true;
require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
}
}
};
}
Note: I took my config from another svelte project (you can ignore uninteresting plugins)
Now it seems to be working fine, but I think is just the starting point :) because there are some known issues with stencil itself which I come across;
core-3d1820a5.js:97 TypeError: Failed to fetch dynamically imported module: http://localhost:57231/build/my-component.entry.js
core-3d1820a5.js:863 Uncaught (in promise) TypeError: Cannot read property 'isProxied' of undefined
https://github.com/sveltejs/sapper/issues/464
https://github.com/ionic-team/stencil/issues/1981
same with react: Unable to integrate stenciljs component in React application
This is not the completely working solution, but I thought it may help you for the next steps...
I’m still having the same issue in 2020. Surprisingly, the webpack template is working fine. Switching to that for now, until this is resolved.
https://github.com/sveltejs/template-webpack

Vue.js: Laravel Mix not combining files

I'm using Laravel 5.4 with Node.js 6, and Vue.js 2.
In resources/assets/js/app.js I have:
require('./bootstrap');
window.Vue = require('vue');
Vue.use(require('vue-resource'));
In webpack.mix.js I have:
mix.combine([
'resources/assets/js/app.js',
'resources/assets/js/enhanced.js',
'resources/assets/js/search.js'
], 'public/js/app.js')
.sass('resources/assets/sass/app.scss', 'public/css');
In resources/assets/js/enhanced.js I have:
require('./app')
var Search = require('./components/Enhanced.vue');
const app = new Vue({
el: '#app_page_enhanced',
render: app_page_enhanced => app_page_enhanced(Page_Enhanced)
});
In resources/assets/js/search.js I have:
require('./app')
var Search = require('./components/Search.vue');
new Vue({
el: '#app_search',
render: app_search => app_search(Search)
})
I have npm run watch-poll running in a Terminal window.
However, I keep getting an error on line 8 of app.js:
require('./bootstrap');
When I comment that line out, the process goes through without additional errors, but when I look at: public/js/app.js the separate .js files aren't included.
I've tried removing: require('./app') from the two .js files, and:
mix.combine([ ... ], 'public/js/')
... and:
mix.combine([ ... ], 'public/js/', 'public/js/app.js')
... but it made no difference.
It's worth mentioning that the code for Vue works when in the app.js file.
I've cobbled this together based on the bits I've scavenged, as I've not been able to find an official guide.
Update
In terms of the core problem, #tompec has helped fix it.
However, I thought this would cure the massive number of errors I get when running the search page and featured results page, where each page is executing the Vue code for both pages, causing the errors.
Try to do something like that
mix.js([
'resources/assets/js/app.js',
'resources/assets/js/enhanced.js',
'resources/assets/js/search.js'
], 'public/js/app.js')
.sass('resources/assets/sass/app.scss', 'public/css');
and remove require('./app') from resources/assets/js/enhanced.js and from resources/assets/js/search.js.
And here's the doc: https://github.com/JeffreyWay/laravel-mix/tree/master/docs

Categories