Related
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.
i am trying to test my quasar project but i am using #i in my project but jest can't find it. When I edit and run my Jest config file as below, I get a resolver not found error. Where do you think I am doing wrong?
I get an error when I edit the module Name Mapper as follows
const esModules = ['quasar', 'quasar/lang', 'lodash-es'].join('|')
/* eslint-env node */
module.exports = {
globals: {
__DEV__: true,
// TODO: Remove if resolved natively
// See https://github.com/vuejs/vue-jest/issues/175
'vue-jest': {
pug: { doctype: 'html' }
},
// Remove if using `const enums`
// See https://huafu.github.io/ts-jest/user/config/isolatedModules#example
'ts-jest': {
isolatedModules: true
}
},
moduleDirectories: ['node_modules', 'src'],
// Jest assumes we are testing in node environment, specify jsdom environment instead
testEnvironment: 'jsdom',
// noStackTrace: true,
// bail: true,
// cache: false,
// verbose: true,
// watch: true,
collectCoverage: false,
coverageDirectory: '<rootDir>/test/jest/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.vue',
'<rootDir>/src/**/*.js',
'<rootDir>/src/**/*.ts',
'<rootDir>/src/**/*.jsx',
'<rootDir>/src/**/*.tsx'
],
coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
coverageThreshold: {
global: {
// branches: 50,
// functions: 50,
// lines: 50,
// statements: 50
}
},
testMatch: [
// Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
// Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
'<rootDir>/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
'<rootDir>/src/**/*.jest.(spec|test).+(ts|js)?(x)'
],
// Extension-less imports of components are resolved to .ts files by TS,
// grating correct type-checking in test files.
// Being 'vue' the first moduleFileExtension option, the very same imports
// will be resolved to .vue files by Jest, if both .vue and .ts files are
// in the same folder.
// This guarantee a great dev experience both for testing and type-checking.
// See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
moduleNameMapper: {
'^quasar$': 'quasar/dist/quasar.esm.prod.js',
'^~/(.*)$': '<rootDir>/$1',
'#(.*)$': '<rootDir>/src/$1',
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^layouts/(.*)$': '<rootDir>/src/layouts/$1',
'^pages/(.*)$': '<rootDir>/src/pages/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^boot/(.*)$': '<rootDir>/src/boot/$1',
'.*css$': '#quasar/quasar-app-extension-testing-unit-jest/stub.css'
},
transform: {
// See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
[`^(${esModules}).+\\.js$`]: 'babel-jest',
'^.+\\.(ts|js|html)$': 'ts-jest',
// vue-jest uses find-babel-file, which searches by this order:
// (async) .babelrc, .babelrc.js, package.json, babel.config.js
// (sync) .babelrc, .babelrc.js, babel.config.js, package.json
// https://github.com/tleunen/find-babel-config/issues/33
'.*\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub'
},
transformIgnorePatterns: [`node_modules/(?!(${esModules}))`],
snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue']
}
package.json
"scripts": {
"dev": "quasar dev",
"build": "quasar build",
"start": "node server.js",
"lint": "eslint --ext .js,.ts,.vue ./",
"format": "prettier --write \"**/*.{js,ts,vue,scss,html,md,json}\" --ignore-path .gitignore",
"test": "echo \"See package.json => scripts for available tests.\" && exit 0",
"heroku-postbuild": "yarn && yarn build",
"test:unit:ui": "majestic",
"test:unit": "jest --updateSnapshot",
"test:unit:ci": "jest --ci",
"test:unit:coverage": "jest --coverage",
"test:unit:watch": "jest --watch",
"test:unit:watchAll": "jest --watchAll",
"serve:test:coverage": "quasar serve test/jest/coverage/lcov-report/ --port 8788",
"concurrently:dev:jest": "concurrently \"quasar dev\" \"jest --watch\""
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.1",
"#fortawesome/free-regular-svg-icons": "^6.1.1",
"#fortawesome/free-solid-svg-icons": "^6.1.1",
"#fortawesome/vue-fontawesome": "^3.0.0-5",
"#quasar/extras": "^1.13.6",
"#types/lodash-es": "^4.17.6",
"axios": "^0.27.2",
"connect-history-api-fallback": "^1.6.0",
"core-js": "^3.22.3",
"crypto": "^1.0.1",
"crypto-browserify": "^3.12.0",
"echarts": "^5.3.2",
"express": "^4.18.1",
"froala-editor": "^4.0.11",
"include-media": "^1.4.10",
"lodash-es": "^4.17.21",
"lookie": "^1.0.4",
"moment": "^2.29.3",
"moment-business-days": "^1.2.0",
"moment-timezone": "^0.5.34",
"quasar": "^2.6.6",
"reactive-state": "^3.7.2",
"sass": "^1.52.1",
"serve-static": "^1.15.0",
"stream-browserify": "^3.0.0",
"ui": "^0.2.4",
"vue": "^3.2.33",
"vue-echarts": "^6.0.2",
"vue-froala-wysiwyg": "^4.0.11",
"vue-i18n": "^9.2.0-beta.36",
"vue-moment-tz": "^2.1.1",
"vue-router": "^4.0.14",
"yarn": "^1.22.18"
},
"devDependencies": {
"#prettier/plugin-pug": "^2.0.0",
"#quasar/app-webpack": "^3.5.3",
"#quasar/quasar-app-extension-qcalendar": "^4.0.0-beta.15",
"#quasar/quasar-app-extension-testing": "^2.0.4",
"#quasar/quasar-app-extension-testing-unit-jest": "^3.0.0-alpha.10",
"#types/node": "^17.0.29",
"#typescript-eslint/eslint-plugin": "^5.21.0",
"#typescript-eslint/parser": "^5.21.0",
"eslint": "^8.14.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-jest": "^25.2.2",
"eslint-plugin-vue": "^8.7.1",
"eslint-webpack-plugin": "^3.1.1",
"majestic": "^1.7.0",
"prettier": "^2.6.2",
"pug": "^3.0.2",
"pug-plain-loader": "^1.1.0",
"workbox-webpack-plugin": "^6.5.3"
},
"browser": {
"crypto": false,
"stream": false
},
"browserslist": [
"last 10 Chrome versions",
"last 10 Firefox versions",
"last 4 Edge versions",
"last 7 Safari versions",
"last 8 Android versions",
"last 8 ChromeAndroid versions",
"last 8 FirefoxAndroid versions",
"last 10 iOS versions",
"last 5 Opera versions"
],
"engines": {
"node": ">= 12.22.1",
"npm": ">= 6.13.4",
"yarn": ">= 1.21.1"
},
"overrides": {
"#types/eslint": "8.4.3"
},
"resolutions": {
"#types/eslint": "8.4.3"
}
and the error message that drove me crazy.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/#(.*)$/": "/Users/exampleUser/exampleProject/src/$1"
},
"resolver": undefined
}
Babel config.js
/* eslint-env node */
// eslint-disable-next-line #typescript-eslint/no-var-requires
const fs = require('fs-extra');
let extend = undefined;
/**
* The .babelrc file has been created to assist Jest for transpiling.
* You should keep your application's babel rules in this file.
*/
if (fs.existsSync('./.babelrc')) {
extend = './.babelrc';
}
module.exports = {
presets: ['#quasar/babel-preset-app'],
extends: extend,
};
quasar config file I wrote to use # throughout the project
/* eslint-env node */
/*
* This file runs in a Node context (it's NOT transpiled by Babel), so use only
* the ES6 features that are supported by your Node version. https://node.green/
*/
// Configuration for your app
// https://v2.quasar.dev/quasar-cli-webpack/quasar-config-js
/* eslint-disable #typescript-eslint/no-var-requires */
const ESLintPlugin = require('eslint-webpack-plugin')
const { configure } = require('quasar/wrappers')
const path = require('path')
module.exports = configure(function (ctx) {
return {
// https://v2.quasar.dev/quasar-cli-webpack/supporting-ts
supportTS: {
tsCheckerConfig: {
eslint: {
enabled: true,
files: './src/**/*.{ts,tsx,js,jsx,vue}'
}
}
},
// https://v2.quasar.dev/quasar-cli-webpack/prefetch-feature
// preFetch: true,
// app boot file (/src/boot)
// --> boot files are part of "main.js"
// https://v2.quasar.dev/quasar-cli-webpack/boot-files
boot: ['app', 'i18n'],
// https://v2.quasar.dev/quasar-cli-webpack/quasar-config-js#Property%3A-css
css: ['app.scss'],
// https://github.com/quasarframework/quasar/tree/dev/extras
extras: [
// 'ionicons-v4',
// 'mdi-v5',
'fontawesome-v6',
// 'eva-icons',
// 'themify',
// 'line-awesome',
// 'roboto-font-latin-ext', // this or either 'roboto-font', NEVER both!
'roboto-font', // optional, you are not bound to it
'material-icons', // optional, you are not bound to it
'material-icons-outlined'
],
// Full list of options: https://v2.quasar.dev/quasar-cli-webpack/quasar-config-js#Property%3A-build
build: {
vueRouterMode: 'history', // available values: 'hash', 'history'
// transpile: false,
// publicPath: '/',
// Add dependencies for transpiling with Babel (Array of string/regex)
// (from node_modules, which are by default not transpiled).
// Applies only if "transpile" is set to true.
// transpileDependencies: [],
// rtl: true, // https://quasar.dev/options/rtl-support
// preloadChunks: true,
// showProgress: false,
// gzip: true,
// analyze: true,
// Options below are automatically set depending on the env, set them if you want to override
// extractCSS: false,
// https://v2.quasar.dev/quasar-cli-webpack/handling-webpack
// "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
chainWebpack(chain) {
chain.plugin('eslint-webpack-plugin').use(ESLintPlugin, [{ extensions: ['ts', 'js', 'vue'] }])
},
extendWebpack(cfg) {
cfg.resolve.alias = {
...cfg.resolve.alias, // This adds the existing alias
// Add your own alias like this
'#': path.resolve(__dirname, './src')
}
cfg.module.rules.push({
test: /\.pug$/,
loader: 'pug-plain-loader'
})
cfg.module.rules.push({
test: /\.scss$/,
loader: 'sass-loader',
options: {
additionalData: '#import "src/css/shared/index.scss";'
}
})
}
},
// Full list of options: https://v2.quasar.dev/quasar-cli-webpack/quasar-config-js#Property%3A-devServer
devServer: {
server: {
type: 'http'
},
port: 8080,
open: true // opens browser window automatically
},
// https://v2.quasar.dev/quasar-cli-webpack/quasar-config-js#Property%3A-framework
framework: {
config: {
notify: {
timeout: 2500,
textColor: 'white',
position: 'bottom-right'
}
},
// iconSet: 'material-icons', // Quasar icon set
// lang: 'en-US', // Quasar language pack
// For special cases outside of where the auto-import strategy can have an impact
// (like functional components as one of the examples),
// you can manually specify Quasar components/directives to be available everywhere:
//
// components: [],
// directives: [],
// Quasar plugins
plugins: ['Notify', 'AppFullscreen', 'Dialog', 'Loading']
},
// animations: 'all', // --- includes all animations
// https://quasar.dev/options/animations
animations: [],
// https://v2.quasar.dev/quasar-cli-webpack/developing-ssr/configuring-ssr
ssr: {
pwa: false,
// manualStoreHydration: true,
// manualPostHydrationTrigger: true,
prodPort: 3000, // The default port that the production server should use
// (gets superseded if process.env.PORT is specified at runtime)
maxAge: 1000 * 60 * 60 * 24 * 30,
// Tell browser when a file from the server should expire from cache (in ms)
// chainWebpackWebserver (/* chain */) {},
middlewares: [
ctx.prod ? 'compression' : '',
'render' // keep this as last one
]
},
// https://v2.quasar.dev/quasar-cli-webpack/developing-pwa/configuring-pwa
pwa: {
workboxPluginMode: 'GenerateSW', // 'GenerateSW' or 'InjectManifest'
workboxOptions: {}, // only for GenerateSW
// for the custom service worker ONLY (/src-pwa/custom-service-worker.[js|ts])
// if using workbox in InjectManifest mode
// chainWebpackCustomSW (/* chain */) {},
},
// Full list of options: https://v2.quasar.dev/quasar-cli-webpack/developing-cordova-apps/configuring-cordova
cordova: {
// noIosLegacyBuildFlag: true, // uncomment only if you know what you are doing
},
// Full list of options: https://v2.quasar.dev/quasar-cli-webpack/developing-capacitor-apps/configuring-capacitor
capacitor: {
hideSplashscreen: true
},
// Full list of options: https://v2.quasar.dev/quasar-cli-webpack/developing-electron-apps/configuring-electron
electron: {
bundler: 'packager', // 'packager' or 'builder'
packager: {
// https://github.com/electron-userland/electron-packager/blob/master/docs/api.md#options
// OS X / Mac App Store
// appBundleId: '',
// appCategoryType: '',
// osxSign: '',
// protocol: 'myapp://path',
// Windows only
// win32metadata: { ... }
},
builder: {
// https://www.electron.build/configuration/configuration
},
// "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
chainWebpackMain(/* chain */) {
// do something with the Electron main process Webpack cfg
// extendWebpackMain also available besides this chainWebpackMain
},
// "chain" is a webpack-chain object https://github.com/neutrinojs/webpack-chain
chainWebpackPreload(/* chain */) {
// do something with the Electron main process Webpack cfg
// extendWebpackPreload also available besides this chainWebpackPreload
}
}
}
})
I created a Vue 3 project and using webpack for bundling the package. Since I have in-DOM templates, I cannot go with the default #runtime-dom. So I have aliased Vue to point to vue.esm-bundler.js.
The issue I am facing is that, when I take a prod build, my vendor bundle is bloated with #babel/parser/lib.
Sample project to reproduce this issue is available here
Steps to follow:
npm install
npm run bundle
Open dist folder and see the Webpack bundle analyser report.
For ease of config, pasting the configs below.
webpack.config.js
const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
const { VueLoaderPlugin } = require("vue-loader");
const TerserPlugin = require("terser-webpack-plugin");
module.exports = (env, options) => {
const devMode = options.mode != "production";
return {
context: path.resolve(__dirname, "src"),
entry: {
"vue-bundle": "./entry/main.js",
},
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].js",
chunkFilename: "[name].js",
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: {
loader: "babel-loader",
options: {
presets: [
[
"#babel/preset-env",
{
targets: [">25%"],
debug: true,
corejs: "3.6.5",
useBuiltIns: false,
},
],
],
},
},
},
{
test: /\.vue$/,
use: "vue-loader",
},
],
},
plugins: [
new CleanWebpackPlugin(),
new VueLoaderPlugin(),
new BundleAnalyzerPlugin({
openAnalyzer: false,
analyzerMode: "static",
reportFilename: "webpack_bundle_analyser_report.html",
defaultSizes: "gzip",
}),
],
optimization: {
mangleWasmImports: true,
removeAvailableModules: true,
sideEffects: true,
minimize: devMode ? false : true,
minimizer: [
new TerserPlugin({
test: /\.js(\?.*)?$/i,
exclude: /\/node-modules/,
parallel: 4,
extractComments: false,
}),
],
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: "vendor-bundle",
chunks: "all",
},
},
},
},
devtool: devMode ? "eval-cheap-source-map" : false,
resolve: {
extensions: [".ts", ".js", ".vue", ".json"],
alias: {
vue: "vue/dist/vue.esm-bundler.js"
},
},
};
};
package.json
{
"name": "testPro",
"version": "1.0.0",
"private": true,
"scripts": {
"bundle": "webpack --mode=production --config webpack.config.js",
"bundle-dev": "webpack --mode=development --config webpack.config.js"
},
"devDependencies": {
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#babel/preset-typescript": "^7.12.1",
"#vue/compiler-sfc": "^3.0.2",
"babel-loader": "^8.1.0",
"clean-webpack-plugin": "^3.0.0",
"core-js": "^3.6.5",
"regenerator-runtime": "^0.13.7",
"terser-webpack-plugin": "^5.0.3",
"vue-loader": "^16.0.0-beta.4",
"webpack": "^5.3.0",
"webpack-bundle-analyzer": "^3.9.0",
"webpack-cli": "^4.1.0"
},
"dependencies": {
"vue": "^3.0.2"
}
}
Entry file main.js
import { createApp } from 'vue';
import App from '../App.vue';
createApp(App).mount('#app');
Not able to get what I am missing.
I strongly believe it is a bug in Vue 3 so I submitted a bug report - you can track it here
...I reproduced it myself using Vue CLI just to eliminate the chance the problem is in your Webpack config
You have 2 options to workaround this issue:
If you don't need to release right now, just work on your project and wait for a fix (I'm pretty sure it will be fixed - Vue builds for a browser which include compiler does not depend on #babel/parser so it's clear Vue don't need it to work correctly inside browser)
Don't use in-DOM templates and template option (string templates) - put everything in .vue files, <template></template> blocks - Runtime + Compiler vs. Runtime-only. Then you don't need a build with compiler...
EDIT: removed the part about missing process.env.NODE_ENV as --mode param to Webpack CLI does exactly that...
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
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'))
});