Browserify cannot find children's required dependencies - npm

I have a repository with a simple index.js:
(function() {
"use strict";
var angular = require('angular');
})();
I use gulp to bundle (full file down below in Edit):
gulp.task('browserify', function() {
return browserify({
entries: './dist/childRepository.js',
insertGlobals : true
})
.transform(to5ify)
.bundle()
.on('error', errorWarning)
.pipe(source('childRepository.bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'))
});
This creates my bundle file in the correct order and runs just fine in the browser. Now in another repository I made the first a dependency using npm.
npm install childRepository.git --save
In the second repository I created another index.js:
(function() {
"use strict";
var angular = require('angular');
var childRepository = require('childrepository');
})();
I have a similar gulpfile for browserify and bundling however it fails with an error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: Cannot find module './angular' from '/Users/jrquick/uabshp/childRepository/dist'
at /Users/jrquick/node_modules/browser-resolve/node_modules/resolve/lib/async.js:55:21
at load (/Users/jrquick/node_modules/browser-resolve/node_modules/resolve/lib/async.js:69:43)
at onex (/Users/jrquick/node_modules/browser-resolve/node_modules/resolve/lib/async.js:92:31)
at /Users/jrquick/node_modules/browser-resolve/node_modules/resolve/lib/async.js:22:47
at FSReqWrap.oncomplete (fs.js:123:15)
I have tried several setups, adding source maps, flipping flags but cannot get around this error. Does anyone have any advice? Thanks.
Edit, my package.json for the childRepository:
{
"name": "childRepository",
"version": "1.0.0",
"description": "",
"main": "./dist/childRepository.bundle.js",
"directories": {
"example": "example"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+ssh://git#bitbucket.org/uabshp/childRepository.git"
},
"author": "",
"license": "ISC",
"homepage": "https://bitbucket.org/uabshp/childRepository#readme",
"devDependencies": {
"6to5ify": "^4.1.1",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.1",
"gulp-jshint": "^2.0.4",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.0.0",
"gulp-sourcemaps": "^2.6.0",
"gulp-uglify": "^2.0.0",
"jshint": "^2.9.4",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"dependencies": {
"angular": "^1.6.0"
}
}
package.json for paren repository:
{
"name": "parentrepository",
"version": "1.0.0",
"description": "### How do I get set up? ###",
"main": "./dist/parentRepository.bundle.js",
"directories": {
"example": "example"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+ssh://git#bitbucket.org/uabshp/parentRepository.git"
},
"author": "",
"license": "ISC",
"homepage": "https://bitbucket.org/uabshp/parentRepository#readme",
"devDependencies": {
"6to5ify": "^4.1.1",
"gulp": "^3.9.1",
"gulp-concat": "^2.6.1",
"gulp-jshint": "^2.0.4",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.0.0",
"gulp-sourcemaps": "^2.6.0",
"gulp-uglify": "^2.0.0",
"jshint": "^2.9.4",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"dependencies": {
"angular": "^1.6.4",
"childRepository": "git+ssh://git#bitbucket.org/uabshp/childRepository.git"
}
}
gulpfile.js (same for both besides name):
var gulp = require('gulp');
var concat = require('gulp-concat');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var jshint = require('gulp-jshint');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var to5ify = require('6to5ify');
var uglify = require('gulp-uglify');
gulp.task('sass', function() {
return gulp.src('sass/*.sass')
.pipe(sass())
.pipe(gulp.dest('dist/css'));
});
gulp.task('lint', function() {
return gulp.src('src/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('scripts', function() {
return gulp.src('src/*.js')
.pipe(concat('childRepository.js'))
.pipe(gulp.dest('dist'))
.pipe(rename('childRepository.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('browserify', function() {
return browserify({
entries: './dist/childRepository.js',
insertGlobals: true,
standAlone: true
})
.transform(to5ify)
.bundle()
.on('error', errorWarning)
.pipe(source('childRepository.bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'))
});
gulp.task('watch', function() {
gulp.watch('src/*.js', ['build']);
gulp.watch('dist/childRepository.js', ['browserify']);
gulp.watch('sass/*.sass', ['sass']);
});
gulp.task('build', [
'sass',
'lint',
'scripts',
'browserify'
]);
gulp.task('default', [
'build',
'watch'
]);
function errorWarning(error) {
console.log(error.toString());
this.emit('end');
}

I solved this by install derequire: npm install gulp-derequire --save-dev
Then added to my gulpfile.js:
gulp.task('browserify', function() {
return browserify('./dist/uabError.js')
.transform(to5ify)
.bundle()
.on('error', errorWarning)
.pipe(source('uabError.bundle.js'))
.pipe(derequire())
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'))
});
This does cause a problem where I get a warning about attempting to load angular more than once. I also have another work around that does not require derequire. Just set ignoreMissing to true.
gulp.task('browserify', function() {
return browserify('./dist/uabError.js', { ignoreMissing: true })
.transform(to5ify)
.bundle()
.on('error', errorWarning)
.pipe(source('uabError.bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('dist'))
});

Related

Mobx statechange not detected

I have a small simple setup. With mobx and preact.
class AppStore {
loadingobjects = true;
constructor() {
makeObservable(this, {
loadingobjects: observable,
});
this.fetchCommonObjects();
}
fetchCommonObjects = () => {
window
.fetch(url)
.then((res) => res.json())
.then((json) => {
/* data processing */
this.loadingobjects = false;
});
};
}
export const AppStoreContext = createContext();
function AppStoreProvider({ children }) {
return (
<AppStoreContext.Provider value={new AppStore()}>
{children}
</AppStoreContext.Provider>
);
}
export default AppStoreProvider;
export default function useAppStore() {
return useContext(AppStoreContext);
}
const List = observer(() => {
const store = useAppStore();
if (store.loadingobjects) {
return <div class="ui active centered inline loader"></div>;
} else {
return (page content);
}
});
problem is that store.loadingobjects Is always false. Seems like im doing something wrong but i cant put my finger on it...
What am i missing or doing wrong?
Edit addding my configs:
package.json
{
"name": "project",
"version": "0.0.2",
"license": "MIT",
"scripts": {
"start": "set NODE_ENV=dev && webpack serve --mode=development",
"build": "set NODE_ENV=production && webpack -p",
},
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/plugin-transform-runtime": "^7.19.6",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"babel-plugin-import": "^1.13.6",
"html-webpack-plugin": "^5.5.0",
"surge": "^0.19.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1",
"webpack-dev-server": "^4.11.1"
},
"dependencies": {
"#babel/polyfill": "^7.12.1",
"mobx": "^6.7.0",
"mobx-react": "^7.6.0",
"preact": "^10.11.3"
}
}
webpack.config.js
const path = require('path');
const isProd = (process.env.NODE_ENV === 'production');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//input
entry: ["#babel/polyfill",'./src'],
resolve: {
alias:{
"react": "preact/compat",
"react-dom": "preact/compat",
"react/jsx-runtime": "preact/jsx-runtime"
}
},
//output
output: {
path : path.join(__dirname, 'build'),
filename : 'bundle.js'
},
//transformations
module: {
rules : [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
}
]
},
//sourcemaps
devtool: 'source-map',
plugins: [new HtmlWebpackPlugin({
template: './src/index.html',
favicon: "./src/favicon.ico"
})],
//server
devServer: {
compress: true,
historyApiFallback: true
}
}
.babelrc
{
"presets": ["#babel/preset-react", ["#babel/preset-env", {"useBuiltIns": "usage",}]],
"plugins": [
["#babel/plugin-transform-runtime"],
[
"#babel/plugin-transform-react-jsx",
{
"pragma": "h",
"pragmaFrag": "Fragment"
}
]
]
}
I found the issue. I started cutting the components into smaller pieces and then adding and removing them into the component hierarchy until i found the component causing the issue. It turned out that i had done onClick={method()} and this was changeing state causing the endless rerenders.

Error with ExpressJS when serving static files - The Resource was blocked due to MIME type (“text/html”) mismatch

I am trying to develop a multiplayer HTML 5 game with Phaser3, ExpressJS (& SocketIO in the future).
this is my
folder structure
I want to serve my phaser game via the index.html to the client , but whenever I try to load the scripts I get MIME Errors on Firefox and 404 not found on Chromium.
These are the Firefox errors and these are the Chromium errors.
server.ts
// #ts-ignore
import { Socket } from "socket.io";
import { Request, Response } from "express";
import * as path from "path";
const express = require("express");
const app = express();
const http = require("http").Server(app);
const io = require("socket.io")(http);
// #ts-ignore
const uuid = require("uuid");
app.use(express.static('public'));
app.get('/', function (req: Request, res: Response) {
res.sendFile(path.resolve('./index.html'));
});
class GameServer {
constructor() {
this.socketEvents();
}
public connect(port: number): void {
http.listen(port, () => {
console.info(`Listening on port ${port}`);
});
}
private socketEvents(): void {
io.on('connected', () => {
console.log("user connected");
});
}
}
const gameSession = new GameServer();
gameSession.connect(3000);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="public/dist/socket.io.js"></script>
<script src="public/dist/phaser.min.js"></script>
<script src="public/dist/bundle.js" async></script>
<script src="http://localhost:9000/livereload.js"></script>
</body>
</html>
package.json
{
"name": "lasttryphaser",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"precommit": "npm run lint",
"lint": "tslint -c tslint.json -p .",
"prestart:dev": "npm run prestart",
"start:dev": "webpack -w & tsc -w --noEmit src/server/server & nodemon src/server/server.js",
"build:release": "webpack --env=dev --optimize-minimize",
"prestart": "npm i && tsc -p ./",
"start": "webpack && node ./src/server/server.js",
"webpack": "webpack --config webpack.dev.config.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"phaser": "^3.20.1",
"socket.io": "^2.3.0",
"socket.io-client": "^2.3.0",
"uuid": "^3.3.3",
"whatwg-fetch": "^3.0.0"
},
"devDependencies": {
"#types/express": "^4.17.2",
"#types/pixi.js": "^5.0.0",
"#types/socket.io": "^2.1.4",
"#types/socket.io-client": "^1.4.32",
"#types/uuid": "^3.4.6",
"awesome-typescript-loader": "^5.2.1",
"ignore-loader": "^0.1.2",
"nodemon": "^2.0.0",
"npm": "^6.13.1",
"prettier": "^1.19.1",
"resolve": "^1.12.2",
"ts-loader": "^6.2.1",
"tslint": "^5.20.1",
"typescript": "^3.7.2",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-livereload-plugin": "^2.2.0"
}
}
webconfig.dev.js
const path = require("path");
const tsconfig = require("./tsconfig.json");
const { TsConfigPathsPlugin } = require("awesome-typescript-loader");
const LiveReloadPlugin = require("webpack-livereload-plugin");
module.exports = {
entry: "./main",
output: {
path: path.resolve(__dirname, "public/dist"),
filename: "bundle.js",
},
mode: "development",
resolve: {
extensions: [".ts", ".js"],
plugins: [new TsConfigPathsPlugin()],
},
plugins: [
new LiveReloadPlugin({
port: 9000,
hostname: "localhost",
protocol: "http",
}),
],
module: {
rules: [
{
test: /\.ts$/,
loader: "awesome-typescript-loader",
exclude: [
path.resolve(__dirname, "typings"),
path.resolve(__dirname, "node_modules"),
],
options: tsconfig,
},
{
test: /\.spec.ts$/,
use: "ignore-loader",
},
],
},
};
tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"baseUrl": ".",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["dom", "es2017"],
"module": "commonjs",
"noEmitOnError": false,
"skipLibCheck": true,
"moduleResolution": "node",
"alwaysStrict": true,
"noUnusedLocals": true,
"noImplicitAny": true,
"sourceMap": true
},
"paths": {
"client/*": ["src/client/*"],
"server/*": ["src/server/*"],
"shared/*": ["src/shared/*"]
},
"typeRoots": [
"./node_modules/#types",
"./node_modules/phaser/types"
],
"files": [
"src/server/server.ts",
"main.ts",
"./node_modules/phaser/types/phaser.d.ts"
],
"exclude": ["node_modules", "*.spec.ts"],
"awesomeTypescriptLoaderOptions": {
"transpileOnly": true
}
}
I looked up everything I could possibly find on the Internet, and read a book about building multiplayer games with phaser. I tried rebuilding that application from the book (which executes fine on all browsers) and I still get those errors.
Thanks for any help

Gulp sourcemaps module not creating file, no errors

I am working on a gulp workflow, and have just piped gulp-sourcemaps to my pipeline. However it id not creating a sourmapfile as it should. I freely admint that the i am confused by the folder destination parameter. I would like the sourcemap to be in the same folder as my css file, unless there is good reason for not doing that.
package.json
{
"name": "gulp-intro",
"version": "1.0.0",
"description": "Simple Gulp introduction",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"gulp": "^3.9.1",
"gulp-autoprefixer": "^5.0.0",
"gulp-rename": "^1.2.3",
"gulp-sass": "^4.0.1",
"gulp-sourcemaps": "^2.6.4"
}
}
Gulpfile.js
/**
* = Gulp specific dependencies
*/
const gulp = require('gulp');
const rename = require('gulp-rename');
/**
* = CSS Style task
*/
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const styleSrc = './src/scss/style.scss';
const styleDist = './assets/css/';
gulp.task('style', () => {
gulp.src(styleSrc)
.pipe(sass({
errorLogToConsole: true,
outputStyle: 'compressed'
}))
.on('error', console.error.bind(console))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(styleDist));
});
This turned out to be a silly mistake, but i forgot to initialize gulp-sourcemaps at the beginning of my gulp task using sourcemaps.init().
Example:
gulp.task('style', () => {
gulp.src(styleSrc)
// Initialize sourcemaps
===> .pipe(sourcemaps.init() <===
.pipe(sass({
errorLogToConsole: true,
outputStyle: 'compressed'
}))
.on('error', console.error.bind(console))
.pipe(autoprefixer({
browsers: ['last 2 versions'],
cascade: false
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(styleDist));
});

Webpack 2 bundle typescript files with same namespace into a single file

I am new to Webpack and bundling typescript files into a single file. I got the following setup where I would like to achieve a single JS files with all my typescript bundled.
tsconfig.json:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"noEmitOnError": true,
"noImplicitAny": false,
"removeComments": true,
"sourceMap": true,
"target": "es6",
"moduleResolution": "node"
},
"exclude": [
"node_modules",
"libs"
]
}
Webpack.config.js
var path = require("path");
const { CheckerPlugin } = require('awesome-typescript-loader');
const config = {
entry: {
Bootstrap: "./Bootstrapper.ts"
},
output: {
//output file naming conventions https://webpack.js.org/configuration/output/#output-filename when having more different configs with outputs
filename: "[name].bundle.js",
path: path.resolve(__dirname, "wwwroot/dist")
},
context: path.resolve(__dirname, "App"),
devtool: "inline-source-map",
module: {
rules: [
{
test: /\.tsx?$/,
loader: "awesome-typescript-loader"
}
]
},
plugins: [
new CheckerPlugin()
]
}
module.exports = config;
Bootstrap typescript file where I incude some node_module that actually work. JQuery works for instance. But If I try to use the class and subclasses that I use from a single namespace I walk against a wall.
Bootstrapper.ts
import * as $ from "jquery";
import * as Konva from "konva";
import * as SignalR from "#aspnet/signalr";
import * as ko from "knockout";
//How do I use these classes that are in different files
import App = Project.Web.Core.App;
$("document").ready(() => {
let app = new App();
alert("This works if I leave the App reference out!");
});
This is the App.ts that I try to use (import App = Project.Web.Core.App;)
namespace Project.Web.Core {
export class App {
pageId: number = 0;
pageRequestId: string = "";
//drawingManager = new Managers.KonvaDrawManager();
signalRmanager = new Managers.SignalRmanager("");
constructor() {
$("document").ready(() => {
this.pageId = $("#container").data("pageid");
this.pageRequestId = $("#container").data("pagerequestid");
this.signalRmanager.pageRequestId = this.pageRequestId;
//this.signalRmanager.setupSignalRConnection(this.drawingManager);
this.loadCanvasData();
});
window.onresize = () => {
//this.drawingManager.rescale();
};
window.onunload = () => {
this.signalRmanager.notifyPageUnloaded();
}
}
loadCanvasData() {
this.pageId = $("#container").data("pageid");
$.get({
dataType: "json",
url: `api/page/${this.pageId}/stage`,
success: (data: any) => {
//this.drawingManager.initializeStage(data);
},
complete: (data: any) => {
if (data.status === 200) {
this.signalRmanager.notifyPageLoaded();
}
}
});
}
}
}
Packages I use
{
"name": "Project.Web_core",
"private": true,
"version": "0.0.0",
"scripts": {
"build": "./node_modules/.bin/webpack -d",
"build:prod": "./node_modules/.bin/webpack -p",
"watch": "./node_modules/.bin/webpack --watch",
"dev": "./node_modules/.bin/webpack-dev-server"
},
"devDependencies": {
"#types/jquery": "^3.3.1",
"#types/knockout": "^3.4.53",
"#types/knockout.mapping": "^2.0.33",
"#types/webpack-env": "1.13.5",
"aspnet-prerendering": "^3.0.1",
"aspnet-webpack": "^2.0.3",
"awesome-typescript-loader": "^5.0.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"event-source-polyfill": "0.0.12",
"json-loader": "0.5.7",
"node-sass": "^4.8.3",
"sass-loader": "^6.0.7",
"style-loader": "0.20.1",
"typescript": "2.7.1",
"uglifyjs-webpack-plugin": "^1.2.4",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-middleware": "^3.1.2",
"webpack-dev-server": "^3.1.3",
"webpack-merge": "4.1.1"
},
"dependencies": {
"#aspnet/signalr": "^1.0.0-preview1-update1",
"es5-shim": "^4.5.10",
"es6-shim": "^0.35.3",
"jquery": "3.3.1",
"knockout": "^3.4.2",
"knockout-mapping": "^2.6.0",
"konva": "^2.0.2",
"watchpack": "^1.4.0"
}
}
I hope someone can help me out clearify my wrong way of thinking.
There are several things:
Typescript config, you can copy. With your types
change import export and remove namespace
export class App { ... }
import { App } from '/path/to/your/file';
class needs a destroyer
and finally in webpack.config.js you can set properties
entry: {
Bootstrap: "./Bootstrapper.ts",
namespace: "./path-to-your-namespace.ts",
anotherNamespace: "./path-to-your-anotherNamespace.ts"
},
resolve: {
extensions: ['.js', '.ts', '.json']
}

plugin("aurelia-chart") throws 404 error

Am new to aurelia framework, current project technology is aurelia-react. Here i need do some charts, i refered this link for setup. Am done setup but it throwing error
"GET /jspm_packages/npm/aurelia-chart#0.2.5.js" Error (404): "Not found"
main.js
export function configure(aurelia) {
aurelia.use
.defaultBindingLanguage()
.defaultResources()
.developmentLogging()
.router()
.history()
.eventAggregator()
.plugin("aurelia-materialize-css")
.plugin('aurelia-react-loader')
.plugin("aurelia-chart");
aurelia.start().then(() => aurelia.setRoot()); }
Package.json
{ "jspm": {
"dependencies": {
"aurelia-bootstrapper": "npm:aurelia-bootstrapper#^1.0.0",
"aurelia-chart": "npm:aurelia-chart#^0.2.5",
"aurelia-framework": "npm:aurelia-framework#^1.0.1",
"aurelia-materialize-css": "npm:aurelia-materialize-css#^0.0.14",
"aurelia-react-loader": "npm:aurelia-react-loader#^1.0.4",
"chartjs": "npm:chartjs#^0.3.24",
"css": "github:systemjs/plugin-css#^0.1.25",
"grofit/aurelia-chart": "github:grofit/aurelia-chart#^0.2.5",
"jsx": "github:floatdrop/plugin-jsx#^1.2.1",
"react": "npm:react#^15.2.1",
"react-dom": "npm:react-dom#^15.2.1"
},
"devDependencies": {
"babel": "npm:babel-core#^5.8.24",
"babel-runtime": "npm:babel-runtime#^5.8.24",
"core-js": "npm:core-js#^1.1.4"
},
"overrides": {
"npm:chartjs#0.3.24": {
"format": "global"
}
}
},
"devDependencies": {
"jspm": "^0.16.41" },
"dependencies": {
"aurelia-chart": "^0.2.5",
},
"aurelia": {
"build": {
"resources": [
"aurelia-chart/elements/chart-element",
"aurelia-chart/attributes/chart-attribute"
]
}
}