I have a nuxt2-webapp with a lot of routes and for all routes except 2, I need a script to be injected. Is there a way to disable the injecting?
Nuxt config:
meta: [
script: [
{
id: 'Cookiebot',
src: 'https://consent.cookiebot.com/uc.js',
'data-cbid': 'xxxxx',
type: 'text/javascript',
async: true,
},
],
]
No, there is no way to do so.
If you inject a script, it will be on the window object. Hence available everywhere in your DOM.
What's the issue with that? You could hide your thing with some CSS if it's annoying visually.
The best way to achieve this behaviour is via a plugin:
export default (context: Context) => {
if (!context.route.name?.includes('embed')) {
const scriptTag = document.createElement('script');
scriptTag.id = 'Cookiebot';
scriptTag.src = 'https://consent.cookiebot.com/uc.js';
scriptTag.setAttribute('data-cbid', 'xxxx');
scriptTag.type = 'text/javascript';
scriptTag.async = true;
document.head.appendChild(scriptTag);
}
};
Related
My plan is to send the token to the server. I could do this script inside of the page.vue (and it's working fine):
mounted() {
this.socket = this.$nuxtSocket({
channel: "/",
auth: {
token: 'abc'
}
})
} // socket.handshake.auth.token = abc
But I need the options on the nuxt.config.js, here's my attempt :
io: {
sockets: [{
url: 'http://localhost:3000',
auth: {
token: 'abc'
},
}]
}, // socket.handshake.auth.token = undefined
Any help are appreciated!
Sorry if my question is unclear, anyway I solve it using built-in RuntimeConfig, and call it in page.vue. I'm not sure if it safe, but it's kinda solve my problem.
I am newish to Nuxt world so I will try to describe what I need and what I was failing to do.
I am trying to programmatically build Nuxt application, bundle it and to mount it to a route
const { Nuxt, Builder } = require('nuxt');
const options = require('./nuxt.config.js');
const nuxt = new Nuxt(options);
try {
await new Builder(nuxt).build();
} catch(error) {
logger.error('Error building');
logger.log({ level: 'error', message: error });
}
So what I am interested in is programmatically controlling on how my Nuxt application will be bundled. That should not be an issue since my app is aware of their environment during build time.
So for production environment I would like to load everything bundled and minified/uglified and what else... So if possible I would like to load all html stuff + 1 JS file + 1 css file.
my example config file is
module.exports = {
build: {
// I should put something here
}
},
srcDir: 'app/view/',
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
head: {
script: [
{ rel: 'preload', src: `https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2&appId=${facebookAppId}&autoLogAppEvents=1` }
],
meta: [
]
},
axios: {
port: 3010
},
router: {
middleware: [ /*my middlewares*/ ]
}
};
So the question is how can I control build in order to achieve what I want? Bonus point for me would be if I managed to load scripts from head.script and merge it to bundle.js file
I want to get the data from http://localhost:5438/api/change?id=123 when visiting http://localhost:8080/change/detail/123, but it's not working when using history mode.
The dev config
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: 'http://127.0.0.1:5438/api/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
The router config
{
path: '/change/detail/:id',
name: 'ChangeDetail',
component: ChangeDetail
}
ChangeDetail
this.$axios.get('api/change?id=' + id)
.then(response => {
......
})
However, I find the url axios is actually calling is,
http://localhost:8080/change/detail/api/change?id=123 instead of http://localhost:8080/api/change?id=123
But when I turn off the history mode, everything is fine when the url is turned to http://localhost:8080/#/change/detail/123.
So what's wrong? Please help me to find a solution for this. Thanks in advance.
I am doing a rather strange thing where I am having express directly compile Javascript on every request (please pretend, for the moment, that this is a reasonable thing to do; needless to say, it is for internal development use only).
Unfortunately, though I have tried in several configurations, I cannot get sourcemaps to work.
My express route looks like this:
app.get(`/js/${f.script}`, async (req, res) => {
try {
const bundle = await rollup.rollup({
input: `./examples/src/${f.script}`,
external: ['React', 'ReactDOM'],
treeshake: false,
plugins: [
resolvePlugin({ jsnext: true, extensions: ['.js', '.jsx'] }),
commonjsPlugin({ include: 'node_modules/**' }),
babelPlugin({
babelrc: false,
presets: [
[
'env',
{ modules: false, targets: { browsers: ['last 2 versions'] } },
],
'react',
],
plugins: ['external-helpers', 'transform-class-properties'],
exclude: 'node_modules/**',
}),
],
});
const { code, map } = await bundle.generate({
format: 'iife',
sourcemap: 'inline',
intro: `var process = {
env : {
NODE_ENV : 'development',
}
}`,
});
res.set('Content-Type', 'text/javascript');
res.send(
`${code}\n//# sourceMappingURL=data:application/json;charset=utf-8,${map}`,
);
// eslint-disable-next-line no-console
console.log(`Served ${f.script}`);
} catch (e) {
// eslint-disable-next-line no-console
console.log('oh bad no no', e);
res.sendStatus(500);
}
});
This gets me a script, followed by:
//# sourceMappingURL=data:application/json;charset=utf-8,{"version":3,"file":...
It's long, but it looks to my relatively untrained eye like a sourcemap. The browser completely ignores it.
I have tried this by just using sourcemap: 'inline' and none of the other bits, which appends no sourcemap to the end. I have now made several goes at manually 'tacking on' the generated sourcemap to the end of the script, but Chrome won't recognize it. Is there a simple syntax error here, or is my entire approach wrong?
You're almost there — you're correct that you need to manually append a comment when using bundle.generate (it's done for you automatically if you use bundle.write instead, but that doesn't make sense here).
Most likely, the JSON is causing the data URI to be invalid, so it needs to be rendered as base64. There's a method attached to the map object that lets you do this easily:
res.send(
`${code}\n//# sourceMappingURL=${map.toUrl()}`,
);
The implementation of toUrl can be seen here.
Note that I'm using //# instead of //# — both work, but //# is officially 'preferred' (the //# is a legacy artifact, according to the spec).
This question already has answers here:
Async load routes data and build route instruction for Angular 2
(4 answers)
Closed 6 years ago.
Maybe anyone know how to dynamicly build routes (or just dynamic import Components).
For example:
I have JSON that contains objects with RouteName, path, ComponentNames (string).
I want to iterate it and build dynamicly routes definitions (route config). But I don`t know, how to make dynamic Component import.
I can passs string "ComponentName" from JSON to import rule, because import want static definition (finded it on some soure from googling).
failed
let a = "MyComponentName"
import {a} from ......
(One idea that I came up with - its like create some map key-value, and keep into key - route, value - Component, and after that equals routename from JSON and my MAP and push needed component into final route config array. But its so ugly solution) Maybe another way exists?
I stuck. Many thanks for any help.....
You could leverage Async routes to do this. Based on your route configuration, you could load route from modules. In this case, you need to add the module path to get the components to associate with routes.
Here is a sample:
var routes = {
path: '/path',
name: 'some name',
module: './my.component',
component: 'MyComponentName'
}
routes.forEach((route : any) => {
this.routeConfigArray.push(
new AsyncRoute({
path : route.path,
loader : () => System.import(route.module).then(m => m[route.component]),
name : route.name
});
);
});
this._router.config(this.routeConfigArray);
Another approach could be to add a function to get the name of functions. Based on this you can check if you have a potential component that matches.
Here is a sample:
ngOnInit() {
this.routes = [
{
path: '/test', component: 'OtherComponent', name: 'Test'
}
];
this.configureRoutes(this.routes);
this.router.config( this.routes);
}
configureRoutes(routes) {
var potentialComponents = [ OtherComponent ];
routes.forEach((route) => {
route.component = potentialComponents.find((component) => {
return component.name === route.component;
});
});
}
See this plunkr: https://plnkr.co/edit/KKVagp?p=preview.
See this question for more details:
Dynamic Route Loading in Angular 2 Fails. (Beta)
https://github.com/angular/angular/issues/11437#issuecomment-245995186 provides an RC.6 Plunker
update
In the new router (>= RC.3) https://angular.io/docs/js/latest/api/router/index/Router-class.html#!#resetConfig-anchor resetConfig can be used
router.resetConfig([
{ path: 'team/:id', component: TeamCmp, children: [
{ path: 'simple', component: SimpleCmp },
{ path: 'user/:name', component: UserCmp }
] }
]);
original
What should work is
import from 'myComponents' as myComponents;
...
someFunc(name:string) {
console.debug(myComponents[name]);
}
Routes can be loaded using
constructor(private router:Router) { }
someFunc() {
this.router.config([
{ 'path': '/', 'component': IndexComp },
{ 'path': '/user/:id', 'component': UserComp },
]);
}
I haven't tried this myself.
See also this related question Angular2 App Routing through Services
say. three screens as page1, page2 and page3 and components as app/page1.ts, app/page2.ts and app/page3.ts
let screens : Array<string> = ["Page1","Page2","Page3"];
let aRouter : RouteDefinition;
this.routes = new Array<RouteDefinition>();
screens.map(function(screenId){
aRouter = new AsyncRoute({
path: "/" + screenId,
name: screenId,
loader: () => System.import("app/" + screenId).then(c => c[screenId]) // not import {page1, page2, page3}}
});
this.routes.push(aRouter);
}.bind(this)); //we need to bind to current "this" instead of global this
this.router.config(this.routes);
trick is .bind(this), which is vanella javscript
for whole sulution, check this
Dynamically load Angular 2 Async router
https://github.com/Longfld/DynamicalAsyncRouter