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

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

Related

Nuxt 'npm run dev' running but the webpage is not responding and won't load

I have been working with nuxt for my personal website. but suddenly the page won't load even though my nuxt dev running perfectly on the console. here is my nuxt-config.js:
// import { auth } from 'firebase'
import colors from 'vuetify/es5/util/colors'
export default {
srcDir: 'src/',
components: {
// global: true,
dirs: [
'~/components',
'~/components/main',
'~/components/user',
'~/components/feedback',
'~/components/auxiliary',
],
},
buildDir: 'functions/.nuxt',
mode: 'universal',
/*
** Headers of the page
*/
head: {
custom title page
title: process.env.npm_package_name || '',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{
hid: 'description',
name: 'description',
content: process.env.npm_package_description || '',
},
],
link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
},
/*
** Customize the progress-bar color
*/
loading: { color: '#5f24', size: '30px' },
/*
** Global CSS
*/
css: [],
/*
** Plugins to load before mounting the App
*/
plugins: [
'~/plugins/components.js',
'~/plugins/icons-fa.js',
'~/plugins/filter.js',
],
/*
** Nuxt.js dev-modules
*/
buildModules: ['#nuxtjs/vuetify'],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://axios.nuxtjs.org/usage
'#nuxtjs/axios',
// Doc: https://github.com/nuxt-community/dotenv-module
'#nuxtjs/dotenv',
['vue-scrollto/nuxt', { duration: 1000 }],
[
'#nuxtjs/firebase',
{
config: {
serverDev: {
apiKey: process.env.FIREBASE_API_KEY_DEV,
authDomain: process.env.FIREBASE_AUTH_DOMAIN_DEV,
databaseURL: process.env.FIREBASE_DATABASE_URL_DEV,
projectId: process.env.FIREBASE_PROJECT_ID_DEV,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET_DEV,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_DEV,
appId: process.env.FIREBASE_APP_ID_DEV,
measurementId: process.env.FIREBASE_MEASUREMENT_ID_DEV,
},
serverPrd: {
apiKey: process.env.FIREBASE_API_KEY_PRD,
authDomain: process.env.FIREBASE_AUTH_DOMAIN_PRD,
databaseURL: process.env.FIREBASE_DATABASE_URL_PRD,
projectId: process.env.FIREBASE_PROJECT_ID_PRD,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET_PRD,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID_PRD,
appId: process.env.FIREBASE_APP_ID_PRD,
measurementId: process.env.FIREBASE_MEASUREMENT_ID_PRD,
},
},
services: {
auth: true,
firestore: true,
storage: true,
analytics: true,
functions: true,
},
onFirebaseHosting: true,
customEnv: true,
},
],
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
baseURL: process.env.BASE_URL,
credentials: false,
},
/*
** vuetif module configuration
** https://github.com/nuxt-community/vuetify-module
*/
vuetify: {
customVariables: ['~/assets/variables.scss'],
theme: {
dark: false,
themes: {
dark: {
primary: colors.blue.darken2,
accent: colors.grey.darken3,
secondary: colors.amber.darken3,
info: colors.teal.lighten1,
warning: colors.amber.base,
error: colors.deepOrange.accent4,
success: colors.green.accent3,
},
},
},
icons: {
iconfont: ['mdi', 'fa'],
},
},
/*
** Build configuration
*/
build: {
extractCSS: true,
extend(config, ctx) {},
transpile: ['vuetify/lib'],
babel: {
plugins: [['#babel/plugin-proposal-private-methods', { loose: true }]],
},
},
env: {
baseURL: process.env.BASE_URL,
apiKey: null,
FIRE_ENV: process.env.FIRE_ENV,
// Declare another env here
},
pageTransition: {
name: 'fade',
mode: 'out-in',
},
pluginOptions: {
ssr: {
nodeExternalsWhitelist: [/^vuetify/],
},
},
}
and here is my package-lock.json:
{
"name": "",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "FIRE_ENV=serverDev nuxt",
"build": "FIRE_ENV=serverPrd nuxt build",
"start": "FIRE_ENV=serverPrd nuxt start",
"generate": "FIRE_ENV=serverPrd nuxt generate",
"build:firebase": "FIRE_ENV=serverPrd npm run clean && npm run build && npm run copy && cd \"functions\" && npm i",
"clean": "npm run clean:public && npm run clean:functions && npm run clean:static",
"clean:functions": "rimraf \"functions/node_modules\" && rimraf \"functions/.nuxt\"",
"clean:public": "rimraf \"public/**/*.*!(md)\" && rimraf \"public/_nuxt\"",
"clean:static": "rimraf \"src/static/sw.js\"",
"copy": "npm run copy:nuxt && npm run copy:static",
"copy:nuxt": "mkdir public/_nuxt && cp -r functions/.nuxt/dist/* public/_nuxt",
"copy:static": "cp -r src/static/* public",
"start:firebase": "FIRE_ENV=serverPrd firebase serve --only functions,hosting",
"deploy": "FIRE_ENV=serverPrd firebase deploy --only functions,hosting"
},
"dependencies": {
"#loadingio/loading.css": "^2.0.1",
"#nuxtjs/axios": "^5.13.6",
"#nuxtjs/dotenv": "^1.4.1",
"#nuxtjs/firebase": "^7.6.1",
"#vue/compiler-dom": "^3.2.45",
"core-js": "^3.9.1",
"express": "^4.18.2",
"firebase": "^8.10.1",
"firebase-admin": "^11.4.1",
"firebase-functions": "^4.1.1",
"nuxt": "^2.15.3",
"vue": "^2.7.14",
"vue-scrollto": "^2.20.0"
},
"devDependencies": {
"#fortawesome/fontawesome-free": "^5.15.3",
"#mdi/js": "^5.9.55",
"#nuxtjs/vuetify": "^1.12.3",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"material-design-icons-iconfont": "^6.1.0",
"prettier": "^2.2.1"
}
}
there are no error or warning, either on the server and client.
I have tried removing the package-lock.json, node_modules folder and .nuxt folder then npm install again but it still not working. I also tried using npm -i --legacy-peer-deps also not helping. any ideas what is wrong with my project? or shall i migrate to nuxt3?
Thank you

How can I show the JEST config file that the # sign points to the src path?

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
}
}
}
})

Trying to get a simple webpack build using tailwind, getting unknown word error

I'm trying to get tailwindcss to work with webpack.
Currently I am getting the following error when running npx webpack:
ERROR in ./src/index.js
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError
(2:3) Unknown word
1 | function hello(){
> 2 | console.log('hi');
| ^
3 | }
4 |
package.json
{
"name": "blank",
"version": "1.0.0",
"license": "MIT",
"private": true,
"scripts": {
"test": "echo \" no tests specified yo \" && exit 1",
"build": "webpack"
},
"dependencies": {
"tailwindcss": "^1.4.6"
},
"devDependencies": {
"css-loader": "^3.5.3",
"postcss": "^7.0.32",
"postcss-loader": "^3.0.0",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
}
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
// ...
use: [
// ...
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
plugins: [
require('tailwindcss'),
require('autoprefixer'),
],
},
},
],
}],
}
}
tailwind.config.js
module.exports = {
purge: [],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
src/index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
</head>
<body>
<script src="main.js"></script>
<p>hello</p>
</body>
</html>
src/index.js
function hello(){
console.log('hi');
}
src/styles.css
/* src/styles.css */
#tailwind base;
#tailwind components;
#tailwind utilities;
Also, how can I reference the styles.css in my index.html file? Do I have to grab it from the /dist folder once it is built?

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']
}

Browserify cannot find children's required dependencies

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'))
});