Trying to create SharedWorker with worker-loader
It doesnt create it, just Worker is created. Seems like it ignores options.
Usage in parent code
import SharedWorker from "worker-loader!./workers/get-nth-fibonacci-number.shared-worker.js";
import "./styles/style.scss";
const btn = document.getElementById("calc-btn");
const input = document.getElementById("nth-input");
const result = document.getElementById("result-el");
const worker = new SharedWorker();
console.log("worker", worker);
worker.port.addEventListener("message", (e) => {
result.innerHTML = e.data;
});
worker.port.addEventListener("error", (e) => {
result.innerHTML = `message: ${e.message}; filename: ${e.filename}; line: ${e.lineno}`;
console.error(e);
});
//...
worker code
import { getNthFobonacciNumber } from "../helpers/get-nth-fibonacci-number.js";
console.log("hello from worker");
self.addEventListener("connect", function (e) {
const port = e.ports[0];
console.log("port", port);
port.addEventListener("message", function (e) {
const num = e.data;
if (Number.isInteger(parseInt(num))) {
const result = getNthFobonacciNumber(num);
port.postMessage({ result, port });
} else {
throw new Error("Is not a number");
}
});
port.start();
});
webpack rule
{
test: /\.shared-worker\.(c|m)?js$/i,
loader: "worker-loader",
options: {
worker: "SharedWorker",
},
},
But in console it is shown as Worker class. What is wrong with it?
dependencies
"#babel/core": "^7.7.7",
"#babel/plugin-syntax-dynamic-import": "^7.2.0",
"#babel/preset-env": "^7.7.7",
"babel-loader": "^8.0.6",
"brotli-webpack-plugin": "^1.1.0",
"clean-webpack-plugin": "^3.0.0",
"compression-webpack-plugin": "^3.0.1",
"css-loader": "^3.4.1",
"cssnano": "^4.1.0",
"file-loader": "^5.0.2",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"purgecss-webpack-plugin": "^1.6.0",
"sass-loader": "^8.0.0",
"style-loader": "^1.1.2",
"terser-webpack-plugin": "^2.3.1",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"worker-loader": "^3.0.5"
This thing asks me to add some more details: "It looks like your post is mostly code; please add some more details." This is just a stub text. I'm sorry.
Solved by using alternative plugin https://github.com/GoogleChromeLabs/worker-plugin
with worker-loader you can, create the file with the extension .sharedworker.js and in webpack rules you do this
{
test: /\.sharedworker\.js$/,
use: [
{
loader: 'worker-loader',
options: {
filename: '[name].[hash:8].js',
inline: 'fallback',
worker: {
type: 'SharedWorker',
options: {
credentials: 'omit',
name: 'mySharedWorker' // for debbuging
}
}
}
},
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
]
}
you can delete worker-loader! in your import code.
worker-loader! will change options to {}
just use webpack config only.
I have same question, and sovled it
Related
I am trying to use ArcballControls.js controls inside my vue js application. This Class has functions which uses arrow syntax, and every other class in controls does not use arrow syntax. This is the only difference i could understand between other files.
Below is the ArcballControls.js provided by three js
https://github.com/mrdoob/three.js/blob/dev/examples/jsm/controls/ArcballControls.js
This below is the whole jsm/controls from three.js
https://github.com/mrdoob/three.js/tree/dev/examples/jsm/controls
When i try to use this controls inside my application i am getting this error.
error in ./node_modules/three/examples/jsm/controls/ArcballControls.js
Module parse failed: Unexpected token (238:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| //listeners
|
> onWindowResize = () => {
|
| const scale = ( this._gizmos.scale.x + this._gizmos.scale.y + this._gizmos.scale.z ) / 3;
# ./node_modules/cache-loader/dist/cjs.js??ref--13-0!
./node_modules/#vue/cli-plugin-babel/node_modules/babel-loader/lib!
./node_modules/cache-loader/dist/cjs.js??ref--1-0!
./node_modules/vue-loader/lib??vue-loader-options!
./src/components/Sidebar/ThreeDCanvas.vue?vue&type=script&lang=js
This is my package.json file
"dependencies": {
"#babel/plugin-transform-arrow-functions": "^7.16.7",
"three": "^0.133.0",
"vue": "^2.6.11",
"vue-style-loader": "^4.1.2",
"vuetify": "^2.6.3",
"vuex": "^3.1.2"
},
"devDependencies": {
"#babel/core": "^7.17.8",
"#babel/preset-env": "^7.16.11",
"#mdi/font": "^6.5.95",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "^3.12.1",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.2.31",
"#vue/eslint-config-prettier": "^4.0.1",
"babel-core": "^6.26.3",
"babel-eslint": "^10.1.0",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"css-loader": "^3.5.3",
"less-loader": "^5.0.0",
"node-sass": "^7.0.1",
"prettier-eslint": "^13.0.0",
"sass": "^1.49.7",
"sass-loader": "^7.3.1",
"vue-svg-loader": "^0.12.0",
"vue-template-compiler": "^2.6.11",
"webpack": "^4.46.0"
},
Inside config/index.js, in module property, this is how i set up the babel loader, i am not sure if its the right way to do it.
module: {
rules: [
{
test: /\.s(c|a)ss$/,
use: [
'vue-style-loader',
'css-loader',
{
loader: 'sass-loader',
// Requires sass-loader#^7.0.0
options: {
implementation: require('sass'),
indentedSyntax: true, // optional
},
},
],
},
{
test: /\.js$/,
exclude: /node_modules(?!\/three)/,
use: [
{
loader: 'babel-loader',
options: {
presets: [['#babel/preset-env', { targets: 'defaults' }]],
},
},
],
},
],
},
This is my component where i initialize the threed scene
<script type="module">
import * as Three from 'three'
import ThreeScene from '#/components/Scene/ThreeScene.js'
import Renderer from '#/components/Scene/Renderer.js'
import Camera from '#/components/Scene/Camera.js'
import HLight from '#/components/Scene/HLight.js'
import DLight from '#/components/Scene/DLight.js'
//import is here
import { ArcballControls } from 'three/examples/jsm/controls/ArcballControls.js'
import ObjectLoader from '#/components/Scene/ObjectLoader.js'
import CubeLoader from '#/components/Scene/CubeLoader.js'
export default {
name: 'ThreeDCanvas',
data() {
return {}
},
methods: {
init() {
this.scene = new ThreeScene()
this.camera = new Camera()
this.renderer = new Renderer({ antialias: true })
this.objectLoader = new ObjectLoader()
this.controls = new ArcballControls(
this.camera,
this.renderer.domElement,
this.scene
)
Could some one help me to find what i am doing wrong here ?
Inside the file config/index.js on module added babel loader.
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader']
},
in package.json removed unnecessary dependencies and downgraded some.
Node version i am using is 14.17.4 and because of that, node-sass had to downgrade to 4.14.1,
after the issue with loader for threejs was fixed, i had issues with
sass loader.
"node-sass": "^4.14.1",
"prettier-eslint": "^13.0.0",
"sass": "^1.49.7",
"sass-loader": "^7.3.1",
"#babel/core": "^7.12.16",
"#babel/eslint-parser": "^7.12.16",
i removed babel-loader and babel-preset-es2015 from package.json.
This is my babel-config.js
module.exports = {
presets: ['#vue/cli-plugin-babel/preset'],
}
When i made these changes i am able to access the arcballcontrol from threejs.
I am facing an issue in my Node.js app, where the log says "Invalid shorthand initializer". However, I checked online, and the official syntax to declare super constructor objects, is by doing objectname = {property: 'X'};
However, for the options = { line, it gives me this error message.
What am I doing wrong here? How is options declared correctly?
const { Sequelize } = require("sequelize");
module.exports = class Database extends Sequelize {
constructor() {
super({
database : process.env.DatabaseName,
username : process.env.DatabaseUsername,
password : process.env.DatabasePassword,
options = {
host: process.env.DatabaseHost,
dialect: "mysql"
}
})
};
Authenticate() {
this
.authenticate()
.then(() => console.log(`Logged in to Database ${process.env.DatabaseName}!`))
.catch(err => console.log(err));
};
};
My dependencies in the package.json:
"dependencies": {
"abort-controller": "^3.0.0",
"asynckit": "^0.4.0",
"callsites": "^3.1.0",
"combined-stream": "^1.0.8",
"delayed-stream": "^1.0.0",
"discord-api-types": "^0.20.2",
"discord.js": "^13.3.1",
"dot-prop": "^6.0.1",
"dotenv": "^10.0.0",
"event-target-shim": "^5.0.1",
"form-data": "^3.0.1",
"is-obj": "^2.0.0",
"lodash.isequal": "^4.5.0",
"mime-db": "^1.51.0",
"mime-types": "^2.1.34",
"mysql2": "^2.3.3",
"node-fetch": "^2.6.6",
"ow": "^0.27.0",
"sequelize": "^6.12.0-alpha.1",
"tr46": "^0.0.3",
"ts-mixer": "^6.0.0",
"tslib": "^2.3.1",
"type-fest": "^1.4.0",
"vali-date": "^1.0.0",
"webidl-conversions": "^3.0.1",
"whatwg-url": "^5.0.0",
"ws": "^8.2.3"
}
Looking forward to your answers guys.
Thank you for your help :)
I'm developing react app. Ejected from create-react-app.
npm start works fine. No console errors.
npm run build builds app with success. But when I try to open index.html there is blank page. No errors. Every file in network tab downloaded with success.
I have no idea how to debug? Tried lots of solutions but none worked.
package.json
{
"name": "frontend",
"version": "0.4.0",
"homepage": ".",
"debug": true,
"private": true,
"dependencies": {
"autoprefixer": "7.1.6",
"babel-core": "6.26.0",
"babel-eslint": "7.2.3",
"babel-jest": "20.0.3",
"babel-loader": "7.1.2",
"babel-preset-react-app": "^3.1.1",
"babel-runtime": "6.26.0",
"bootstrap": "4.0.0",
"case-sensitive-paths-webpack-plugin": "2.1.1",
"chalk": "1.1.3",
"css-loader": "0.28.7",
"dotenv": "4.0.0",
"dotenv-expand": "4.0.1",
"eslint": "4.10.0",
"eslint-config-react-app": "^2.1.0",
"eslint-loader": "1.9.0",
"eslint-plugin-flowtype": "2.39.1",
"eslint-plugin-import": "2.8.0",
"eslint-plugin-jsx-a11y": "5.1.1",
"eslint-plugin-react": "7.4.0",
"extract-text-webpack-plugin": "3.0.2",
"file-loader": "1.1.5",
"font-awesome": "4.7.0",
"fs-extra": "3.0.1",
"html-webpack-plugin": "2.29.0",
"jest": "20.0.4",
"jquery": "3.3.1",
"jquery.easing": "^1.4.1",
"lodash": "4.17.*",
"magnific-popup": "^1.1.0",
"object-assign": "4.1.1",
"postcss-flexbugs-fixes": "3.2.0",
"postcss-loader": "2.0.8",
"promise": "8.0.1",
"raf": "3.4.0",
"react": "^16.2.0",
"react-dev-utils": "^5.0.0",
"react-dom": "^16.2.0",
"react-redux": "5.0.*",
"react-router-dom": "^4.2.2",
"react-router-hash-link": "1.2.*",
"react-router-redux": "4.0.*",
"react-scrollchor": "4.2.*",
"recharts": "0.22.*",
"redux": "3.7.*",
"redux-thunk": "2.2.*",
"scrollreveal": "3.3.6",
"seamless-immutable": "7.1.*",
"semantic-ui": "2.3.*",
"semantic-ui-css": "2.3.*",
"semantic-ui-react": "0.78.*",
"style-loader": "0.19.0",
"sw-precache-webpack-plugin": "0.11.4",
"url-loader": "0.6.2",
"webpack": "3.8.1",
"webpack-dev-server": "2.9.4",
"webpack-manifest-plugin": "1.3.2",
"whatwg-fetch": "2.0.3",
"react-google-recaptcha": "0.11.*",
"react-async-script": "0.9.*",
"raven-js": "3.25.*",
"babel-preset-es2015": "6.24.*",
"each-async": "*",
"indent-string": "*",
"validator": "*"
},
"devDependencies": {
"browser-sync": "2.23.6",
"gulp": "^3.9.1",
"gulp-clean-css": "3.9.2",
"gulp-header": "2.0.1",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.1.0",
"gulp-uglify": "3.0.0",
"node-sass": "^4.7.2",
"rebuild-node-sass": "*",
"sass-loader": "^6.0.6",
"console-log-shortcut": "1.0.*"
},
"scripts": {
"start": "node scripts/start.js",
"build": "node scripts/build.js",
"test": "node scripts/test.js --env=jsdom"
},
"jest": {
"collectCoverageFrom": [
"**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"mjs",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
"babel": {
"presets": [
"react-app"
]
},
"eslintConfig": {
"extends": "react-app"
}
}
build.js
'use strict';
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
// Ensure environment variables are read.
require('../config/env');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs-extra');
const webpack = require('webpack');
const config = require('../config/webpack.config.prod');
const paths = require('../config/paths');
const checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
const printHostingInstructions = require('react-dev-utils/printHostingInstructions');
const FileSizeReporter = require('react-dev-utils/FileSizeReporter');
const printBuildError = require('react-dev-utils/printBuildError');
const measureFileSizesBeforeBuild =
FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
const useYarn = fs.existsSync(paths.yarnLockFile);
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
measureFileSizesBeforeBuild(paths.appBuild)
.then(previousFileSizes => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuild);
// Merge with the public folder
copyPublicFolder();
// Start the webpack build
return build(previousFileSizes);
})
.then(
({ stats, previousFileSizes, warnings }) => {
if (warnings.length) {
console.log(chalk.yellow('Compiled with warnings.\n'));
console.log(warnings.join('\n\n'));
console.log(
'\nSearch for the ' +
chalk.underline(chalk.yellow('keywords')) +
' to learn more about each warning.'
);
console.log(
'To ignore, add ' +
chalk.cyan('// eslint-disable-next-line') +
' to the line before.\n'
);
} else {
console.log(chalk.green('Compiled successfully.\n'));
}
console.log('File sizes after gzip:\n');
printFileSizesAfterBuild(
stats,
previousFileSizes,
paths.appBuild,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE
);
console.log();
const appPackage = require(paths.appPackageJson);
const publicUrl = paths.publicUrl;
const publicPath = config.output.publicPath;
const buildFolder = path.relative(process.cwd(), paths.appBuild);
printHostingInstructions(
appPackage,
publicUrl,
publicPath,
buildFolder,
useYarn
);
},
err => {
console.log(chalk.red('Failed to compile.\n'));
printBuildError(err);
process.exit(1);
}
);
// Create the production build and print the deployment instructions.
function build(previousFileSizes) {
console.log('Creating an optimized production build...');
let compiler = webpack(config);
return new Promise((resolve, reject) => {
compiler.run((err, stats) => {
if (err) {
return reject(err);
}
const messages = formatWebpackMessages(stats.toJson({}, true));
if (messages.errors.length) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (messages.errors.length > 1) {
messages.errors.length = 1;
}
return reject(new Error(messages.errors.join('\n\n')));
}
if (
process.env.CI &&
(typeof process.env.CI !== 'string' ||
process.env.CI.toLowerCase() !== 'false') &&
messages.warnings.length
) {
console.log(
chalk.yellow(
'\nTreating warnings as errors because process.env.CI = true.\n' +
'Most CI servers set it automatically.\n'
)
);
return reject(new Error(messages.warnings.join('\n\n')));
}
return resolve({
stats,
previousFileSizes,
warnings: messages.warnings,
});
});
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml,
});
}
after looking at the possible solutions for the issue i had, couldn't find a way to solve this error:
Uncaught SyntaxError: Unexpected token import
Im stuck at this point and cant seem to solve it (feel a bit restless when trying to learn and work).
P.S. I appreciate your time and help. Im relatively a new developer, pardon me if i have asked anything stupid. thanks
For your expert review, here's the relevant files that im working with:
package.json
{
"name": "",
"version": "1.0.0",
"dependencies": {
"browser-sync": "^2.18.6",
"browsersync": "0.0.1-security",
"jquery": "^3.1.1",
"jquery-smooth-scroll": "^2.1.2",
"lazysizes": "^3.0.0-rc3",
"normalize.css": "^5.0.0",
"picturefill": "^3.0.2",
"waypoints": "^4.0.1"
},
"devDependencies": {
"autoprefixer": "^6.7.0",
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"del": "^2.2.2",
"gulp": "^3.9.1",
"gulp-cssnano": "^2.1.2",
"gulp-imagemin": "^3.1.1",
"gulp-modernizr": "^1.0.0-alpha",
"gulp-postcss": "^6.3.0",
"gulp-rename": "^1.2.2",
"gulp-rev": "^7.1.2",
"gulp-svg-sprite": "^1.3.1",
"gulp-svg2png": "^0.3.0",
"gulp-uglify": "^2.0.1",
"gulp-watch": "^4.3.11",
"postcss-hexrgba": "^0.2.1",
"postcss-import": "^9.1.0",
"postcss-mixins": "^5.4.1",
"postcss-nested": "^1.0.0",
"postcss-simple-vars": "^3.0.0",
"webpack": "^2.2.1"
}
}
webpack.config.js
module.exports = {
entry: {
app: "./app/assets/scripts/App.js"
},
output: {
path: "./app/temp/scripts",
filename: "App.js"
},
module: {
loaders: [
{
loader: 'babel-loader',
query: {
presets: ['es2015']
},
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
App.js
import MobileMenu from './modules/MobileMenu';
var mobileMenu = new MobileMenu();
MobileMenu.js
class MobileMenu {
constructor() {
alert("testing 123")
}
}
export default MobileMenu;
scripts.js
var gulp = require('gulp'),
webpack = require('webpack');
gulp.task('scripts', ['modernizr'], function(callback) {
webpack(require('../../webpack.config.js'), function(err, stats) {
if (err) {
console.log(err.toString());
}
console.log(stats.toString());
callback();
});
});
Solution
As it seems that it doesnt really matter which version of the babel core, babel-loader we actually use. Also .babelrc file was not required for me. What worked for me was to include the bundled file in my HTML which was generated at temp/scripts/App.js, instead of including the original source at assets/scripts/App.js. Thats it ! cheers
Thanks to #MichaelJungo
I'm developing a site on React, and I'm trying to generate the bundle with browserify throuhg gulp
This is my gulpfile:
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var babel = require('babelify');
var gulp = require('gulp');
var util = require("gulp-util");
var log = util.log;
var path = require('path');
function compile(watch) {
var bundler = watchify(browserify('./app.js', { debug: true }));
function rebundle() {
bundler.bundle()
.on('error', function(err) { console.error(err); this.emit('end'); })
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./dist/js'));
}
if (watch) {
bundler.on('update', function() {
console.log('-> bundling...');
rebundle();
});
}
rebundle();
}
function watch() {
return compile(true);
}
gulp.task('build', function() { return compile(); });
gulp.task('watch', ['sass:watch'], function() { return watch(); });
gulp.task('default', ['watch']);
It correclty runs the build, and generates the bundle. But after that, when I import to the site I get the error:
ReferenceError: define is not defined
I guess browserify, or the bundle generated is expecting some other package that has the define? What I'm missing?
Here is my package.json:
{
"name": "react-test",
"version": "0.0.1",
"license": "",
"browserify": {
"transform": [
"babelify"
]
},
"dependencies": {
"react": "^0.14.3",
"react-dom": "^0.14.3",
"react-redux": "^4.4.0",
"redux": "^3.3.1",
"redux-happy-async": "0.0.4",
"redux-thunk": "^1.0.3",
"rest": "^1.3.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-cli": "^6.5.1",
"babel-core": "^5.8.25",
"babel-loader": "^5.3.2",
"babelify": "^6.1.2",
"browserify": "^13.0.0",
"gulp": "^3.9.1",
"gulp-cssnano": "^2.1.1",
"gulp-sass": "^2.2.0",
"gulp-sourcemaps": "^1.6.0",
"gulp-util": "^3.0.7",
"jasmine": "^2.4.1",
"jasmine-core": "^2.4.1",
"karma": "^0.13.21",
"karma-jasmine": "^0.3.7",
"karma-phantomjs-launcher": "^1.0.0",
"karma-webpack": "^1.7.0",
"phantomjs-prebuilt": "^2.1.4",
"reactify": "^1.1.1",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0",
"watchify": "^3.7.0",
"webpack": "^1.12.2",
"webpack-stream": "^3.1.0"
}
}