How to use javascript webworker in webpack? - javascript

i'm trying to use web workers in my web app but i'm having a hard time. Adding a new entry to the webpack.config.js does not work.
so, I'm trying to use the npm package called worker-loader but there is no proper example on how to use it. All of my attempts to use it has failed. Can you guys please show me a simple example on how to use it.
import Worker from "worker-loader!./Worker.js";
const myworker = new Worker();
myworker.postMessage(songs);
myworker.onmessage = function(Data) {
//do something
}
my webpack.config.js file is like this with
entry: __dirname + "/js/index.js",
output: {
path: __dirname + "/dist",
filename: "bundle.js"
},
{
module: {
rules: [
{
test: /\.worker\.js$/,
use: { loader: 'worker-loader' }
}
]
}
}
My server tells me the following:
"GET /279b1e1fcb403131377a.worker.js HTTP/1.1" 404
Since my 279b1e1fcb403131377a.worker.js is inside /dist its giving me 404 error. How can i make the request to go inside /dist.

There are plenty of examples given on the official Github page:
https://github.com/webpack-contrib/worker-loader
That should easily get you going.

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.

Sapper/Svelte.js - How to specify client-side assets location?

I have a Sapper.js application that I have successfully running on AWS Lambda. Lambda is able to deliver the server-side generated HTML created by Sapper to AWS API Gateway which then serves the app to the user. I am using S3 to host the client side assets (scripts, webpack chunks, etc). The S3 bucket is on a different domain than API Gateway.
The issue I'm having is that I need to set an asset prefix for these scripts so that Sapper can find them. Currently all of my client side scripts include relative links and look like this: <script src="/client/be33a1fe9c8bbaa6fa9d/SCRIPT_NAME.js"></script> I need to have them look like this: <script src="https://AWS_S3_BUCKET_ENDPOINT.com/client/be33a1fe9c8bbaa6fa9d/SCRIPT_NAME.js"></script>
Looking in the Sapper docs, I see that I can specify a base url for the client and server. However, changing this base url breaks my app and causes the Lambda rendering the pages to return 404 errors.
I know that when using, say, Next.js, I can accomplish this by modifying the next.config.js file to include the following:
module.exports = {
assetPrefix: "https://AWS_S3_BUCKET_ENDPOINT.com/client",
}
But I don't know how to do this in Sapper. Do I need to modify the bundler (using webpack) config? Or is there some other way?
Thank you.
I think I've figured it out.
I had to change two sapper files. First I went into sapper/dist/webpack.js and modified it like so:
'use strict';
var __chunk_3 = require('./chunk3.js');
var webpack = {
dev: __chunk_3.dev,
client: {
entry: () => {
return {
main: `${__chunk_3.src}/client`
};
},
output: () => {
return {
path: `${__chunk_3.dest}/client`,
filename: '[hash]/[name].js',
chunkFilename: '[hash]/[name].[id].js',
// change this line to point to the s3 bucket client key
publicPath: "https://AWS_S3_BUCKET_ENDPOINT.com/client"
};
}
},
server: {
entry: () => {
return {
server: `${__chunk_3.src}/server`
};
},
output: () => {
return {
path: `${__chunk_3.dest}/server`,
filename: '[name].js',
chunkFilename: '[hash]/[name].[id].js',
libraryTarget: 'commonjs2'
};
}
},
serviceworker: {
entry: () => {
return {
'service-worker': `${__chunk_3.src}/service-worker`
};
},
output: () => {
return {
path: __chunk_3.dest,
filename: '[name].js',
chunkFilename: '[name].[id].[hash].js',
// change this line to point to the s3 bucket root
publicPath: "https://AWS_S3_BUCKET_ENDPOINT.com"
}
}
}
};
module.exports = webpack;
//# sourceMappingURL=webpack.js.map
Then I had to modify sapper/runtime/server.mjs so that the main variable points to the bucket like so:
...
const main = `https://AWS_S3_BUCKET_ENDPOINT.com/client/${file}`;
...
Testing with the basic sapper webpack template, I can confirm that the scripts are loading from the s3 bucket successully. So far this all looks good. I will mess around with the sapper build command next to make it so I can pass these hacks in as command line arguments so I don't have to hardcode them every time.
Now, I'm not sure if this will hold up as the app becomes more complicated. Looking into the sapper/runtime/server.mjs file, I see that the req.baseUrl property is referenced in several different locations and I don't know if my hacks will cause any issues with this. Or anywhere else in sapper for that matter.
If anyone with more experience with the Sapper internals is reading, let me know in the comments if I screwed something up 👍

Vue js babel build error after installing prerender-spa-plugin

So I have a vue-js application and today I started using prerender-spa-plugin to generate some static pages for better SEO. When I run npm run build, everything works perfect, no errors. Now when I want to run the development server with npm run serve, I get the following error (only a part of it)
error in ./src/main.js
Module build failed (from ./node_modules/babel-
loader/lib/index.js):
Error: .plugins[0] must include an object
at assertPluginItem (/Users/user/Desktop/app/node_modules/#babel/core/lib/config/validation/option-assertions.js:231:13)
So I guess the problem has to do with the babel plugin loader. So I commended every part of my code using prerender-spa-plugin, but I still get the same error. I hope someone can point me to the right direction.
My babel.config.js
const removeConsolePlugin = []
if(process.env.NODE_ENV === 'production') {
removeConsolePlugin.push("transform-remove-console")
}
module.exports = {
presets: [
'#vue/app'
],
plugins: [removeConsolePlugin]
}
My vue.config.js
const path = require('path');
const PrerenderSpaPlugin = require('prerender-spa-plugin');
const productionPlugins = [
new PrerenderSpaPlugin({
staticDir: path.join(__dirname, 'dist'),
routes: ['/', '/documentation'],
renderer: new PrerenderSpaPlugin.PuppeteerRenderer({
// We need to inject a value so we're able to
// detect if the page is currently pre-rendered.
inject: {},
// Our view component is rendered after the API
// request has fetched all the necessary data,
// so we create a snapshot of the page after the
// `data-view` attribute exists in the DOM.
//renderAfterElementExists: '[data-view]',
}),
}),
];
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(...productionPlugins);
}
}
}

HMR - webpack-hot-middleware do not reload my page

I have a Vue(hello-world) application using
webpack-dev-middleware and webpack-hot-middleware
[hrm] said it's connected in the console when I run the application
Then when I made some changes on my main.js, it thorws up
bundle rebuilding
bundle.js:1382 [HMR] bundle rebuilt in 95ms
bundle.js:2336 [HMR] Checking for updates on the server...
bundle.js:2409 [HMR] Updated modules:
bundle.js:2411 [HMR] - ./src/main.js
bundle.js:2416 [HMR] App is up to date.
Which is fine, but DOM does not reflect my changes and I have to manually reload the page in order to see them.
These are the code files I have right now:
// dev-server.js
...
app.use(middleware(compiler, {
noInfo: true,
publicPath: webpackConfig.output.path
}));
app.use(webpackHotMiddleware(compiler));
...
and here my webpack config:
module.exports = {
context: srcPath,
entry: ['webpack-hot-middleware/client', './main'],
resolve: {
extensions: ['.js', '.vue'],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
output: {
path: distPath,
publicPath: distPath,
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
})
]
}
then I accept module hot changes on main.js:
import Vue from 'vue'
new Vue({
el: '#app',
data: {
message: "hello world!!"
}
})
if (module.hot) {
module.hot.accept();
}
I've struggled myself looking on forums and blog posts but seems I'm missing something, any ideas what could be the issue.
I am currently switching from Webpack 3 to 4 and I am facing the same problem as yours.
I think your dev-server.js has missing some codes. I know it is a bit late but I hope this could be an answer for someone who has been struggled few days like me.
For Webpack 4:
// dev-server.js
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
});
compiler.hooks.compilation.tap('html-webpack-plugin-after-emit', () => {
hotMiddleware.publish({
action: 'reload'
});
});
For Webpack 3:
// dev-server.js
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat: 2000
});
compiler.plugin('compilation', function (compilation) {
compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
hotMiddleware.publish({ action: 'reload' })
cb()
});
});
I'd suggest blowing away all of the options to start with, and then incrementally add them as desired once you have basic functionality working. I think that your path option is actually the default anyway, and that heartbeat looks really long. (I'm also assuming the linebreak in your webpack entry config is a typo..)
You can see a working example of applying webpack-hot-middleware to an existing webpack-dev-middleware app (albeit React instead of Vue - and please ignore the CoffeeScript), that was done about a week ago. It's pretty bare, and is pretty similar to your setup, except with fewer options. (I'm also able to avoid having to touch module.hot myself, though I imagine that depends on what other libraries are in the mix.)

sw-precache-webpack-plugin webpack service worker default template

I'm using the sw-precache-webpack-plugin to generate a service worker for my project, I can see all my fonts, js and css files in the cache storage but not the index / html file and its not working when i go offline. I also get a 'site cannot be installed: no matching service worker detected.' when i try and add to homepage on the App manifest.
My stack is a universal React + redux app, with Express + ejs for index file. I'm not sure if its because I'm using ejs rather than a default html file, but it doesnt seem to find the file. Is there a way I can specify a template? My sw-precache-webpack-plugin webpack setting is:
new SWPrecacheWebpackPlugin({
cacheId: 'tester',
filename: 'my-service-worker.js',
directoryIndex: '/',
}),
Any advice would be appreciated
You are missing a specification of a caching strategy in the plugin config.
plugins: [
new SWPrecacheWebpackPlugin({
cacheId: 'tester',
filename: 'my-service-worker.js',
runtimeCaching: [
{
urlPattern: '/',
handler: 'cacheFirst',
}
]
})
]
Documentation: https://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject

Categories