How to conditionally render JS in created() or mounted() - vue.js

I'm using Nuxt JS 2.4.5 and am building a static website in SPA mode where running npm run build && npm run generate will generate my website in a dist/ directory.
I'm trying to figure out how I can do an if () {} else {} statement within either mounted() or created() to check whether I'm running my project in dev mode or production/generated website mode so that I can include a Google Analytics snippet, or conditionally render other content on the page based on the mode.
I've taken a look through the documentation and have found the following: https://nuxtjs.org/api/configuration-dev which looks to be of some help to me, but haven't yet put this into practice as I'm unsure of the best approach and am looking for guidance or an example.
I'm potentially thinking about trying the following:
layouts/default.vue
...
mounted () {
if (process.env.NODE_ENV == 'production') {
// run code on generated static site, e.g: Google Analytics
} else {
// run code if in dev mode, e.g: http://localhost:3000/
}
}
...
...and then in my package.json file I'd need to set production mode potentially on the generate command which builds the website using: NODE_ENV=production
package.json
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "NODE_ENV=production nuxt generate"
}
If I then run npm run build && npm run generate it should then build my static website and the Google Analytics code should then work.
I'l love to find out how other people are doing this and their solutions, I'm trying to get Google Analytics to work for every page and thus the layouts directory seems a good place to put the code.

I would set this up in the created() or beforeCreate() hook in the default.vue. There's no hard and fast rules against setting it up like this.
If you were doing this not using Nuxt but instead vanilla Vue, I'd put it in the main.js file where Vue is initialized.

Related

How to determine whether the web app is running in development or production mode?

I am running a vuejs application inside ASP.NET app using visual studio. I am using webpack and have followed this tutorial for setup : https://marczak.io/posts/netcore-vuejs/. I am unable to figure out how to run the app on production mode? If I need to change my process.env.NODE_ENV, from where shall I change it?
You can access the mode that the app is running by process.env.NODE_ENV.
However you can't access it directly to the template since it's scoped by Vue's this context.
If you want to access it in the Vue template you can do it with a computed property.
computed: {
appMode () {
return process.env.NODE_ENV
}
}
And in the template:
<p> {{ appMode }} </p>
I highly recommend you to learn more here (Vue CLI Docs)
You have to be aware that when you are ready to deploy your
application you can set the modes. For example I suggest you to add 2
scripts in package.json:
scripts: {
// other scripts
"build-production": "vue-cli-service build --mode production",
"build-staging": "vue-cli-service build --mode staging",
}
When you want to deploy to staging run:
npm run build-staging
When you want to deploy to production run:
npm run build-production

capacitor ionic 4 vue project net::ERR_FILE_NOT_FOUND

I created new vue project using vue create and added ionic & capacitor based on the following tutorial vue ionic capacitor Tutorial
yarn add #capacitor/core #capacitor/cli
yarn cap init
yarn cap add android/ios and electron
update capacitor.config.json as follow
{
"appId": "xxxx.xxx.xxxx.vuecapacitordemo2",
"appName": "vuecapacitordemo2",
"bundledWebRuntime": true,
"npmClient": "yarn",
"webDir": "dist"
}
I have a problem when running electron, yarn run electron:start ,
I get net::ERR_FILE_NOT_FOUND .Googling for answers found couple of answers all lead to adding link_1 link_2 link_3 vue.config.js file with the following content. with different values for publicPath
module.exports={
publicPath: '/',
runtimeCompiler: true
}
That causes the application not to proceed beyond splash screen. Any hint/idea how to fix this ?
Thanks in Advance
I was able to get my electron app to run without errors by making two changes.
First I added (projectRoot)/vue.config.js
module.exports = {
publicPath: './',
}
I also added <base href="./"> within the <head> tag inside (projectRoot)/public/index.html
After making this change make sure to build "npm run build" and then "npx cap copy" to sync all your asset files and then test "cd electron & npm run electron:start"
For reference, I was getting errors similar to GET file:///js/chunk-de72da5c.95253596.js net::ERR_FILE_NOT_FOUND. After adding the changes to vue.config.js I noticed that links to my assets have the full path of the directory of my app.
The issues seems to be with how electron handles relative paths so you have to explicitly change how webpack compiles the paths by default. Hope this helps.

Support 2 base URL's in Vue

Is it possible to support 2 base URL's, /test/app and /app with the Vue router? The http requests also have to use the updated path for API calls.
Maybe it's possible to do this with aliases in vue router. But this doesn't solve the API call problem for vue resource. And this would mean I have to create 2 paths for every page.
First and foremost, just so that you're aware, Vue-Resource has been deprecated from official recommendation status because they don't perceive Ajax as a functionality that requires deep integration with the Vue ecosystem.
Now, to the larger question. It sounds like you're trying to use different urls based on which environment you're in (ie. local development vs. production). The easiest way to do this would be to go to the file where you define your Vue-Resource root url and add the following:
var isProduction = process.env.NODE_ENV === 'production'
var rootUrl = (isProduction) ? 'http://production.domain/api' : 'http://localhost:8080/api'
Vue.http.options.root = rootUrl;
This code basically tests if you're in production and, if you are, assigns the production domain api to the variable, otherwise it assigns the local development domain api.
[EDIT]
I took for granted that you would be using the Vue-CLI which sets this up for you. If you are using NPM to start your Vue server, you're probably running a command like npm run dev, which references this line in your package.json:
{
// ...
"scripts": {
"dev": "node build/dev-server.js",
// ...
}
You can change that "dev" line to something like this:
{
// ...
"scripts": {
"dev": "NODE_ENV=dev node build/dev-server.js",
// ...
}
And that will create the NODE_ENV variable with your Node script which should allow you to use it now within the Vue context.

How to run task after the blocking action like webpack:watch in NPM

I am using webpack:watch to compile and watch all css and js, and then I would like to restart express server. However, it seems like the thread is blocked by webpack:watch, so it wont execute subsequent script to start express
Here is the code
"scripts": {
"start": "webpack:watch express:restart",
"express:restart" : "....."
},
I am using node 6. I wonder is there any npm script I can use to achieve that ?
Thanks in advance

How to integrate karma in webpack

I am a webpack newbie and have a question about testing.
I have a project which uses webpack, typescript and karma as test runner and I would like to run my tests on every file change (e.g. in "watch" mode)
I am aware of karma-webpack and it works well when I run karma as own process (karma start ...)
But what I want is to integrate karma in the webpack flow.
So, from my naive point of view, I thought karma has to be defined in preloading of webpack (such as a linter).
But I found nothing....
I can not believe that this common workflow is not possible (run tests on every source change)
Can anybody of you give me a suggestion?
Time flies and it's June 2018 already. As there isn't much documentation about this online I want to give out my 2 cents.
I have currently a setup working where I bundle my tests with webpack a watch for changes in order to rerun automatically the tests.
I'm using karma-webpack using the configuration explained in the Alternative usage section and I think it's the proper way to solve the problem asked in the question.
karma.conf.js
{
...
files: [
// only specify one entry point
// and require all tests in there
'test/index_test.js'
],
preprocessors: {
// add webpack as preprocessor
'test/index_test.js': [ 'webpack' ]
},
...
}
test/index_test.js
// require all modules ending in "_test" from the
// current directory and all subdirectories
const testsContext = require.context(".", true, /_test$/)
testsContext.keys().forEach(testsContext)
Watching for changes of the whole bundle as #Adi Prasetyo suggests is wrong in my opinion. We should only watch for changes in the tests files and the files that are imported inside them, which can be achieved with configuration shown in the last URL.
Very important for hot reloading to work (at least in my case it was what made it work), you need to setup webpack-dev-middleware configuration in order to update the tests bundle everytime a change happens in some test file or the files being imported inside them. This is the config I'm using:
karma.config.js
{
...
webpackMiddleware: {
watchOptions: {
aggregateTimeout: 300,
poll: 1000, // customize depending on PC power
},
},
...
}
More info about it here.
I have same problem, as the TDD workflow that i use. After writing test then change the code the test doesn't re-run. Run test on every file change is possible.
As karma files have 3 options: Included, served, watched.
You can specify the bundle as pattern then tell karma to watch it
karma.config.js
files: [
// watch final file so when source change and it's final file, re run the test
{ pattern: './dist/js/*.wp.js', watched: true},
],
but when we use karma start no webpack active and watching. So use concurrently to run karma and webpack. Note that webpack should watch only the source code and karma should watch the bundle file.
Then we can add script property to package.json like so
package.json
"scripts": {
"test": "karma start karma.config.js",
"build": "webpack",
"dev": "concurrently \"webpack --progress --colors --watch\" \"karma start karma.config.js --colors\"",
},
Then run npm run dev to start coding
Well I've never heard of webpack up until now, but I know karma fairly well. I'm not 100% sure what you are asking here, so let me know if this isn't helpful at all. You can setup karma to do exactly what you want it to do (run tests on every file change).
There are two options that you must set in the karma.conf.js file: autoWatch: true and singleRun: false.
karma.conf.js
module.exports = function(config) {
config.set({
// set other options and stuff...
autoWatch: true,
singleRun: false
});
};
autoWatch set to true enables watching files and executing tests whenever any file changes. Setting singleRun to false means that you only need to execute karma start (or however you integrate it into webpack) once to run your tests, instead of having to enter the command every single time you make a change or want to run your suite; it just keeps karma running in the background.