The question has it all, but basically, I set up a new vue app without webpack. When I try to do:
handleSubmit() {
axios
.post(`${process.env.VUE_APP_API_URL}`)
.then(response => (this.info = response));
this.$router.push({ name: "ConversationsList" });
}
It's undefined. In my .env file, I have:
VUE_APP_API_URL=http://localhost:3000
What do I have to do now?
Easy fix. Created a file called vue.config.js:
const webpack = require('webpack')
module.exports = {
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
})
]
}
}
Related
I'm trying to configure vue.js webpack for development mode. I have a separate folder in root directory named "styles" where I keep all my scss and include main.scss to main.js. I want to have the separate css file in the dist folder.
There is my vue.config.js:
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'development') {
return {
plugins: [new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename:'[name].css'
})],
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
}
}
}
}
Screen Result
I am trying to test my serverMiddleware in nuxt which has API routes
It has a single route /api/v1/test which returns a json true
My api/index.js file
import express from 'express'
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.get('/test', (req, res) => res.json(true))
export default {
path: '/api/v1',
handler: app,
}
Here is my api.spec.js file which contains the test returning 404
If I test my route / it returns a 200
My test/backend/api.spec.js file
import { resolve } from 'path'
import { Nuxt, Builder } from 'nuxt'
import supertest from 'supertest'
// We keep the nuxt and server instance
// So we can close them at the end of the test
let nuxt = null
// Init Nuxt.js and create a server listening on localhost:4000
beforeAll(async () => {
const config = {
dev: process.env.NODE_ENV !== 'production',
rootDir: resolve(__dirname, '../', '../'),
mode: 'universal',
}
nuxt = new Nuxt(config)
await new Builder(nuxt).build()
await nuxt.server.listen(3000, 'localhost')
}, 30000)
// Close server and ask nuxt to stop listening to file changes
afterAll(() => {
nuxt.close()
})
describe('GET /api/v1/test', () => {
test('returns status code 200', (done) => {
supertest(nuxt.server.app).get('/api/v1/test').expect(200, done)
})
})
My jest.config.js file
module.exports = {
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/$1',
'^~/(.*)$': '<rootDir>/$1',
'^vue$': 'vue/dist/vue.common.js',
},
moduleFileExtensions: ['js', 'vue', 'json'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest',
},
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/components/**/*.vue',
'<rootDir>/pages/**/*.vue',
],
}
Can someone kindly suggest why the test is failing
In my case, it was because of the jest configuration.
my jest.config.js
testEnvironment: 'jsdom'
api.test(spec).file requires node environment.
I didn't modify it. Instead, I modified the api.test.js file.
I just added the comment code below at the head of the file.
solved) my api.test.js
/**
* #jest-environment node
*/
link : https://jestjs.io/docs/configuration#testenvironment-string
In vuepress, I want to do some config for webpack devServer like below:
module.exports = { //... devServer: { https: true } };
but I don't know where I can config it. Does anyone know it?
In ..vuepress\config.js, config as below, but it doesn;t work.
module.exports = { chainWebpack (config, isServer) { } }
Thanks a lot.
You can do this configuration with .vuepress/config.js. There is two configuration for change webpack:
module.exports = {
configureWebpack: (config, isServer) => {
},
chainWebpack: (config, isServer) => {
}
}
For more details you can read the documentation: https://vuepress.vuejs.org/config/#configurewebpack
I have setup a new vue project and added storybook to the project. When I have components that use the #/components path, it does not run correctly.
Can't resolve '#/components/EntityGrid/EntityGrid.Component.vue'
I have tried multiple webpack.config.js without any luck. What is the simplest webpack.config.js to fix this
This is happening in the default configuration without a webpack.config.js.
I managed to resolve this issue by adding the following in .storybook/main.js
const path = require("path");
module.exports = {
stories: ['./../src/**/*.stories.(js|jsx|ts|tsx|mdx)'],
...
webpackFinal: async (config) => {
config.resolve.alias = {
...config.resolve.alias,
"#": path.resolve(__dirname, "../src/"),
};
// keep this if you're doing typescript
// config.resolve.extensions.push(".ts", ".tsx");
return config;
},
}
Here are some useful links to help provide further context:
StoryBook docs for webpackFinal - gives you the first clue as to how you might go about configuring your webpack configuration
And then this solution
on an issue in Github provided the final piece of the puzzle
I have no idea what the cause for your issue is, but here is my working vue.config.js
const path = require('path')
module.exports = {
chainWebpack: config => {
config.module
.rule("i18n")
.resourceQuery(/blockType=i18n/)
.type('javascript/auto')
.use("i18n")
.loader("#kazupon/vue-i18n-loader")
.end();
},
configureWebpack: {
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'#': path.join(__dirname, '/src')
}
},
module: {
rules: [
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
},
]
},
},
css: {
loaderOptions: {
sass: {
data: `#import "#/assets/sass/_variables.scss"; #import "#/assets/sass/_mixins.scss";`,
}
}
}
}
Just ignore all the stuff that you dont need
I uasing Vue.js with Vuetify and creating a PWA.
I have service-worker.js in /public folder
A snippet from vue.config.js:
pwa: {
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'public/service-worker.js',
// ...other Workbox options...
}
}
This looks too be working good and caching the shell etc.
I run build and serve up the project
npm run build
The problem i have is when i update any files, i can't see the updated changes.
when i navigate to the url in my android device the page remains as the old one (cached).
How can i get it to update?
I tried including this code in index.html, but no success:
https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users
service-worker.js
importScripts("/precache-manifest.8812c20b1b3401cbe039782d13cce03d.js", "https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js");
console.log(`Hello from service worker`);
if (workbox) {
console.log(`Workbox is loaded`);
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
addEventListener('message', (event) => {
if (event.data && event.data.type === 'SKIP_WAITING') {
skipWaiting();
}
});
}
else {
console.log(`Workbox didn't load`);
}
Not sure what exactly your setup setup is, but it should be similar. Using the #vue/cli-plugin-pwa and with minimal setup below.
This will show a dialog when a new version of your app is available. Clicking yes will update your app. You will have to refresh the page somehow to actually show the new version, but that is up to you on how solve that.
vue.config.js:
module.exports = {
pwa: {
name: "name-of-your-app",
short_name: "noya",
themeColor: "#000000",
workboxPluginMode: "InjectManifest",
workboxOptions: {
swSrc: "src/service-worker.js" // CHECK CORRECT PATH!
}
}
};
src/main.js:
import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
// whatever other imports...
new Vue({
render: h => h(App)
}).$mount("#app");
src/registerServiceWorker.js:
import { register } from "register-service-worker";
if (process.env.NODE_ENV === "production") {
register(`${process.env.BASE_URL}service-worker.js`, {
updated(registration) {
if (window.confirm("A new version is available, update now?")) {
const worker = registration.waiting;
worker.postMessage({ action: "SKIP_WAITING" });
// refresh the page or trigger a refresh programatically!
}
}
});
}
src/service-worker.js:
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
self.addEventListener("message", (event) => {
if (event.data.action == "SKIP_WAITING") self.skipWaiting();
});
I get it work by following the offer_a_page_reload_for_users. The original registerServiceWorker.js seems redundant though.
src/registerServiceWorker.js
import { Workbox } from "workbox-window";
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
const wb = new Workbox("/service-worker.js");
wb.addEventListener("waiting", () => {
const result = window.confirm("refresh now?");
if (result) {
wb.messageSW({ type: "SKIP_WAITING" });
}
});
wb.addEventListener("controlling", () => {
window.location.reload();
});
wb.register();
}