NestJS access static resource image in code - nestjs

I have an existing NestJS app with main.ts granting static resources in 'public' dir as :
app.useStaticAssets(join(__dirname, '..', 'public'));
I am able to build a PDF resource using Tea-School (https://github.com/AmirTugi/tea-school), by correctly accessing the templates in the static public path. However the same code fails to add the logo image 'public/templates/logo.png' as seen below. I am also unable to download the logo image and even the pdf template when I access the following paths :
http://host:port/templates/dir1/template1.pug
http://host:port/templates/logo.png
Code written for generating PDF is as follows :
public static async createDoc1(createDoc1Dto: CreateDoc1Dto): Promise<Buffer> {
const teaSchoolOptions: GeneratePdfOptions = {
styleOptions: {
file: path.resolve(process.cwd(), 'public/templates/dir1/template1.scss')
},
htmlTemplatePath: path.resolve(process.cwd(), 'public/templates/dir1/template1.pug'),
htmlTemplateOptions: {
...createDoc1Dto,
logoPath: path.resolve(process.cwd(), 'public/templates/logo.png')
},
pdfOptions: {
format: 'A4',
printBackground: true,
margin: { top: '1cm', bottom: '1cm' }
},
puppeteerOptions: { headless: true, args: ['--no-sandbox'] }
};

Related

i18next - Loading translations from a JSON file

I'm trying to load translations from a JSON file using i18next library on Node. The path of the JSON file points to the correct location.
I'm getting the following error:
i18next::translator: missingKey en translation test test
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});
JSON file:
{
"foo": "bar"
}
Specifying the translations directly in createInstance using resources property works perfectly.
I tried everything I could think of, with no success.
Found the solution!
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance();
instance.init({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});

process.env is always empty event though i am using webpack.defineplugin

I have tried with adding webpack.defineplugin in my code and I am not able to get data from process.env object i.e object is empty then next I try with adding node:{process:false} in module.export but my project is not able to render app.js file
When I run the npm script and start the local browser I am not able to figure out why process.env is empty all the time
Then I try with adding node:{process:false} so that we can touch global process.env by using webpack.defineplugin but then i am not able to see my react.dom element or Login page , my react code in not getting executed
webpack.config.js file
module.exports = (env) => {
// Get the root path (assuming your webpack config is in the root of your project!)
const currentPath = path.join(__dirname);
console.log(__dirname);
// Create the fallback path (the production .env)
const basePath = currentPath + '/.env';
// We're concatenating the environment name to our filename to specify the correct env file!
const envPath = basePath + '.' + env.ENVIRONMENT;
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
console.log("final path" + finalPath);
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
console.log("env keys ", envKeys);
return {
node: {
process: true
},
entry: [
// POLYFILL: Set up an ES6-ish environment
// 'babel-polyfill', // The entire babel-polyfill
// Or pick es6 features needed (included into babel-polyfill)
'core-js/fn/promise',
'core-js/es6/object',
'core-js/es6/array',
'./src/index.jsx', // your app's entry point
],
devtool: process.env.WEBPACK_DEVTOOL || 'eval-source-map',
output: {
path: path.join(__dirname, 'public'),
filename: "bundle.js",
publicPath: '/'
},
module: {
rules: loadersConf
},
resolve: {
extensions: ['.js', '.jsx'],
modules: [
path.join(__dirname, "src"),
path.join(__dirname, "node_modules"), // the old 'fallback' option (needed for npm link-ed packages)
],
alias: {
"styles": path.resolve(__dirname, 'styles/'),
}
},
devServer: {
contentBase: "./public",
// do not print bundle build stats
noInfo: true,
// enable HMR
hot: true,
// embed the webpack-dev-server runtime into the bundle
inline: true,
// serve index.html in place of 404 responses to allow HTML5 history
historyApiFallback: true,
port: PORT,
host: HOST,
},
plugins: [
new webpack.DefinePlugin(envKeys),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new ExtractTextPlugin({
filename: 'style.css',
allChunks: true
}),
new DashboardPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
files: {
css: ['style.css'],
js: ["bundle.js"],
}
}),
]
}
};

Vue Website Returns "Cannot Get /path" On All Pages EXCEPT Index

I am using Vue on Node.js to host my website on an AWS EC2 instance. I dont have an index node.js file, just the vue-router file. I use AWS CloudFront to bind my certificate to my traffic. The problem is that everytime i access the site through the server's link, the site works perfectly, but whenever i access it through the cloud-front link, only the index of the website will show up. No /about or /contact; instead it returns Cannot GET /about.
My Router:
import Vue from 'vue';
import Router from 'vue-router';
import VueCookies from 'vue-cookies';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';
Vue.use(Router);
Vue.use(VueCookies);
VueCookies.config('7d');
VueCookies.set('theme', 'default');
VueCookies.set('unique', Date.now());
VueCookies.set('rwapi-uuid', `v3-${Date.now()}-x9k0`)
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'INDEX', component: Home },
{ path: '/about/', name: 'ABOUT', component() { return import('./views/About.vue'); } },
{ path: '/portfolio', name: 'PORTFOLIO', component() { return import('./views/Port.vue'); } },
{ path: '/contact', name: 'CONTACT', component() { return import('./views/Contact.vue'); } },
{ path: '/login', name: 'LOGIN', component() { return import('./views/Login.vue'); } },
{ path: '/404', component: NotFound },
{ path: '*', redirect: '/404' },
],
});
I have already tried to add the historyApiFallback: true to my webpack config but it had no effect.
According to Vue Router's documentation, when using your router in history mode, your webserver requires additional configuration.
I don't exactly know how do EC2 instances work, but if you don't have a webserver proxying all your requests to index.html, Vue-router will not be able to handle the other requests.

Problem with open new browser using router in Vue/Electron. Redirecting to default route

I'm trying to open a new window using Vue/Electron but the new windows is opening on default rounte instead the needed route.
*The route on navigation-drawer is working well.
file: router/index.js
import Process from '#/components/ProcessManager/Process.vue'
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: require('#/components/LandingPage').default
},
{
path: 'process',
name: 'process',
component: Process,
},
{
path: '*',
redirect: '/'
}
]
file:main/index.js
const processURL = process.env.NODE_ENV === 'development'
? `http://localhost:9080/#/process`
: `file://${__dirname}/index.html#process`
function createWindow2 () {
let win = new BrowserWindow({ width: 400, height: 320, webPreferences: {webSecurity: false} })
win.loadURL(processURL)
win.on('closed', () => {
win = null
})
}
It looks like it loads the index.html but does not start the app, and the reason is shown in the error message in the screenshot you supplied.
Looking at the error message, you can read here what's going on.

How to deploy Vue.js application on IIS over Virtual Directory?

I need to deploy a Vue.js application on IIS over a virtual directory, but when I deploy it I have to change my routes to include the virtual directory name.
My original routes is like that:
export const routes = [
{ path: '', component: Default, props: true },
{ path: '/Path', component: Path, props: true },
{ path: '/Path/:IdPath', component: PathForm, props: true }
];
But to work, I had to change my routes to include the virtual directory name, like that:
export const routes = [
{ path: '/VirtualDirectory', component: Default, props: true },
{ path: '/VirtualDirectory/Path', component: Path, props: true },
{ path: '/VirtualDirectory/Path/:IdPath', component: PathForm, props: true }
];
And this is a problem, because if I need to change my server or my virtual directory I'll have to re-deploy my Vue.js application to include the new virtual directory name.
Are there a way to make this dinamic?
You will need to configure the publicPath, by default this is set to "/", e.g. if you look in your generated index.html you will see:
<script type="text/javascript" src="/app.js"></script></body>
Notice the "/app.js" above.
You can configure this by adding a vue.config.js file to the root of your project and adding a publicPath setting:
module.exports = {
publicPath: '/my-virtual-directory'
}
See the official Vue documentation https://cli.vuejs.org/config/#publicpath for more information.
If you are using webpack-cli, one thing you can do is to give your directory (mostly vuejs root dir) an alias. inside your webpack.config.js So, in this following example:
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': path.resolve(__dirname, 'src')
},
The # will be an alias to your /src directory. If you change this to reflect your current vue root, then you can migrate your app without a problem.

Resources