How do I set up Webpack, Angular 2.0, and Django together? - node.js

I am currently trying a setup a webpack, angular 2.0 and django stack and trying to work with all of the parts together is a bit confusing.
I am using NPM to handle the libraries.
Here are the errors when I try to compile the typescript for loading with django:
Asset Size Chunks Chunk Names
main-71f084fe9f6c4015034a.ts 5.09 MB 0, 1, 2 [emitted] main
app-71f084fe9f6c4015034a.ts 23 bytes 1, 2 [emitted] app
vendor-71f084fe9f6c4015034a.ts 3.6 kB 2, 1 [emitted] vendor
+ 329 hidden modules
ERROR in /home/bischoff_s/Code/optim/typings/globals/webpack-env/index.d.ts
(176,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'RequireFunction'.
ERROR in /home/bischoff_s/Code/optim/typings/globals/webpack-env/index.d.ts
(225,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type 'NodeModule', but here has type 'Module'
Here is my tsconfig.json file
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true
}
}
My typings.json
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
My webpack.common.js
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: {
'vendor': './assets/js/vendor.ts',
'app': './assets/js/index.ts'
},
entry: './assets/js/index.ts',
resolve: {
extensions: ['', '.js', '.ts']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['ts', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor']
})
]
};
and finally webpack.dev.js
var path = require("path")
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var BundleTracker = require('webpack-bundle-tracker');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: path.resolve('./assets/bundles/'),
filename: "[name]-[hash].ts",
},
plugins: [
new ExtractTextPlugin('[name].css'),
new BundleTracker({filename: './webpack-stats.json'})
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});

It was a problem with different typing from different webpack-env and node. here is the link for reference to the answer.
TypeScript error on compilation with webpack

Related

Building a NodeJS app with file based db using webpack, and Typescript

The problem
I am using Phaser 3 html5 framework that runs on webpack. I am trying to make an offline game that would run on desktop or mobile apps, not a browser game, so I don't want to use the local storage or other in-memory databases. The players should be able to save the game, and the game would be stored in a DB file. I am trying to find the best solution to relational DB in my app.
What I tried:
I tried implementing sqlite3, better-sqlite3, postgres and few other options, but nothing seems to be working. The client-side can't handle databases and is throwing errors. I also tried browserify to bundle sqlite3 imports into binary and call it from the index.html, but that also gave me errors:
(terminal) .src/ browserify server.js > bundle.js
.src/server.js:
const db = require('better-sqlite3')('game.db');
.src/bundle.js:
.src/index.html:
<script src="bundle.js></script>
error:
bundle.js:5638 Uncaught TypeError: The "original" argument must be of type Function
at promisify (bundle.js:5638:11)
at Object.<anonymous> (bundle.js:146:18)
at Object.<anonymous> (bundle.js:209:4)
at 4.../util (bundle.js:209:17)
at o (bundle.js:1:265)
at bundle.js:1:316
at Object.<anonymous> (bundle.js:74:29)
at Object.<anonymous> (bundle.js:88:4)
at 1.../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js (bundle.js:88:17)
at o (bundle.js:1:265)
I would like to know if there is an easy way to create and use a relational database like SQLite3 or Postgres with NodeJS without dealing with browser limitations since the app won't run in the browser eventually. Please let me know if you have any insights on this. I am also sharing my webpack.config and tsconfig files for reference:
webpack config file
const path = require("path");
const webpack = require("webpack");
const { merge } = require("webpack-merge");
const baseConfig = require("./webpack.config.base.js");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");
const LoadablePlugin = require("#loadable/webpack-plugin");
const clientConfig = {
entry: {
main: "./src/index.ts"
},
name: "client",
devtool: 'inline-source-map',
optimization: {
splitChunks: {
cacheGroups: {
phaser: {
test: /[\\/]node_modules[\\/]phaser[\\/]/,
name: "phaser",
chunks: "all",
},
}
}
},
output: {
path: path.resolve(__dirname, 'www'),
filename: "main.js"
},
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/,
},
{
test: /\.json/,
type: "asset/resource",
exclude: /node_modules/,
},
],
},
devServer: {
historyApiFallback: true,
allowedHosts: 'all',
static: {
directory: path.resolve(__dirname, "./src"),
},
open: true,
hot: true,
port: 8080,
},
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, "src/index.html"),
minify: false
}),
new CleanWebpackPlugin(),
new LoadablePlugin({
outputAsset: false, // to avoid writing loadable-stats in the same output as client
writeToDisk: true,
filename: `${__dirname}/loadable-stats.json`,
}),
new webpack.LoaderOptionsPlugin({
// test: /\.xxx$/, // may apply this only for some modules
options: {
ts: {
configFileName : 'tsconfig.client.json'
}
}
}),
new CopyPlugin({
patterns: [
{
from: "static",
globOptions: {
// asset pack files are imported in code as modules
ignore: ["**/publicroot", "**/*-pack.json"]
}
}
]
}),
]
};
module.exports = merge(baseConfig, clientConfig);
tsconfig file
{
"extends": "./tsconfig.json",
"skipLibCheck": true,
"compilerOptions": {
"module": "ES6",
"target": "ES2022",
"outDir": "./www",
"rootDir": "./src",
"esModuleInterop": true,
"typeRoots": [
"node_modules/#types",
"node_module/phaser/types"
],
"types": [
"phaser", "node"
],
},
"include": [
"src/**/*",
"types/**/*"
]
}

"Module not found: Error: Can't resolve..." in TS Gatsby Node project

I have a (node) server folder located in the root of my project, it is a Gatsby app written in Typescript
Here is one of the errors:
#27 27.94 ERROR in ./server/modules/version/index.ts
#27 27.94 Module not found: Error: Can't resolve '../../common/api/cache' in '/build/server/modules/version'
#27 27.94 # ./server/modules/version/index.ts 7:16-49
#27 27.94 # ./server/index.ts
The module it is referring to is this:
export class StatusCache {
private _cache: Record<string, CacheObject> = {};
private options: CacheOptions = {
expiresMinutes: 3
};
...
and the import in the other file is import { StatusCache } from "../../common/api/cache";
the folder structure of the area of interest:
server
- common
- api
- cache (StatusCache class location)
- modules
- <version>
- index.ts
and lastly my webpack.server.js
const path = require("path");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require("webpack");
const OUTPUT_FOLDER = "dist";
module.exports = env => ({
entry: "./server/index.ts",
mode: "production",
target: "node",
module: {
rules: [
{
test: /\.(tsx|ts)?$/,
use: [
{
loader: "ts-loader",
options: {
logInfoToStdOut: true,
logLevel: "info",
allowTsInNodeModules: false,
transpileOnly: true
}
}
],
exclude: /node_modules/
}
]
},
plugins: [
new CleanWebpackPlugin(),
new webpack.IgnorePlugin(/\.(test|spec)\./)
],
externals: {
bufferutil: "bufferutil",
"utf-8-validate": "utf-8-validate",
"mongodb-client-encryption": "mongodb-client-encryption"
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
filename: "server.js",
chunkFilename: "[name].bundle.js",
path: path.resolve(__dirname, OUTPUT_FOLDER),
publicPath: "/"
}
});
I found a solution that worked for me and might be useful for others.
I added and edited my tsconfig-server.json to this:
{
"compilerOptions": {
"baseUrl": "./server",
"module": "commonjs",
"esModuleInterop": true,
"target": "esnext",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"noEmit": false
},
"lib": ["es2015"]
}
particularly the baseUrl, target, and moduleResolution
I had a similar Error , the problem was in gatsby-config,I had to add ignore property like so :
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data/`,
ignore: [`**/\.*`], // ignore files starting with a dot
},
},

webpack tsx Module parse failed: Unexpected token

I am trying to write both frontend (React) and backend (Express) in TypeScript. At the moment, my webpack.config.js in the root folder encounters an error even though I have ts-loader for it.
This is webpack.config.js
const webpack = require('webpack');
const path = require('path');
const config = {
cache: true,
mode: 'development',
entry: {
'user': ['./src/client/User/index.tsx', 'webpack-hot-middleware/client']
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/static'
},
devServer: {
contentBase: './dist',
hot: true
},
plugins: [new webpack.HotModuleReplacementPlugin()],
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
exclude: /node_modules/,
include: path.join(__dirname, 'client')
}
]
},
node: { fs: 'empty' }
};
module.exports = config;
And this is my tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"outDir": "dist",
"sourceMap": true,
"baseUrl": "."
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
I got the error like this:
ERROR in ./src/client/User/index.tsx 10:1
Module parse failed: Unexpected token (10:1)
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
|
| const rootComponent = (
> <Provider store={store}>
| <BrowserRouter>
| <div id="page-container" className="sidebar-o sidebar-dark enable-page-overlay side-scroll page-header-fixed side-trans-enabled">
# multi ./src/client/User/index.tsx webpack-hot-middleware/client user[0]
Thanks to FunkeyFlo answer, I found out the answer myself. I have to change both:
tsconfig.json: include also src/**/*.tsx
webpack.config.js: entry to ./dist/src/client/User/index
change include section in tsconfig to the following
{
...
"include": [
"src/**/*.ts",
"src/**/*.tsx"
],
...
}

Module parse failed: Unexpected character '#'

I want to build my graphql server app, when i build by webpack 4, i've got this error on a decorator of typeorm :
ERROR in ./src/models/user.ts 15:0
Module parse failed: Unexpected character '#' (15:0)
You may need an appropriate loader to handle this file type.
| import { JWT } from './jwt';
|
> #Entity()
| #Unique(['username'])
| #Unique(['email'])
# ./src/server.ts 15:0-37 34:45-49
The webpack.config.js is like this :
var ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
var fs = require('fs');
var path = require('path');
var nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'production',
entry: './src/server.ts',
output: {
path: __dirname + '/dist',
filename: '[name].[chunkhash:8].js',
},
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: '/\.tsx?$/',
exclude: '/node_modules/',
include: path.resolve(__dirname, 'src'),
use: {
loader: 'ts-loader',
options: {
transpileOnly: true
}
}
}
]
},
plugins: [
new ForkTsCheckerWebpackPlugin()
],
externals: [nodeExternals()],
};
The tsconfig.json is like this :
{
"exclude": [
"fixtures",
"tests"
],
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"typeRoots": [
"node_modules/#types"
],
"lib": ["es2016", "esnext.asynciterable"]
}
}
When i compile with tsc, i've not got any error but i've got this error when i launch app by node dist/server.js :
(function (exports, require, module, __filename, __dirname) { import { Field, ID, Int, ObjectType } from 'type-graphql';
SyntaxError: Unexpected token {
Could you help me to resolve this bug ?
Thanks for advance
It looks like ts-loader isn't being used. I think that's because you've specified the test as a string instead of a regular expression. Try removing the surrounding single quotes. See the example in the documentation.

An import path cannot end with '.ts' - NodeJS and Visual Code

I've got an error while trying to build a simple NodeJS app:
Even that Visual Code prompts an error, my code got running.. When I remove the .ts extension from import statement, I got an error that the file cannot be found.
I'm using webpack, but these files are from server. Here's my folder structure:
And here's my webpack file:
var webpack = require('webpack');
var helpers = require('./helpers');
//# Webpack Plugins
var CopyWebpackPlugin = (CopyWebpackPlugin = require('copy-webpack-plugin'), CopyWebpackPlugin.default || CopyWebpackPlugin);
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
var ExtractTextPlugin = require('extract-text-webpack-plugin');
//# Webpack Constants
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
title: 'My Application',
baseUrl: '/',
host: process.env.HOST || '0.0.0.0',
port: process.env.PORT || 8080,
ENV: ENV,
HMR: HMR
};
//# Webpack Configuration
module.exports = {
metadata: METADATA,
entry: {
'polyfills': './src/polyfills.ts',
'vendor': './src/vendor.ts',
'main': './src/main.ts',
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js', '.scss'],
root: helpers.root('src'),
modulesDirectories: [
'node_modules',
'server'
]
},
module: {
preLoaders: [
{
test: /\.js$/,
loader: 'source-map-loader',
exclude: [
helpers.root('node_modules/rxjs'),
helpers.root('node_modules/#angular2-material'),
helpers.root('node_modules/#angular')
]
}
],
loaders: [
{
test: /\.ts$/,
loader: 'awesome-typescript-loader',
exclude: [/\.(spec|e2e)\.ts$/]
},
{
test: /\.json$/,
loader: 'json-loader'
},
{
test: /\.css$/,
loader: 'raw-loader'
},
{
test: /\.html$/,
loader: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
{
test: /\.scss|css$/,
loader: ExtractTextPlugin.extract({ fallbackLoader: 'style-loader', loader: 'css-loader!sass-loader' }),
exclude: [ helpers.root('node_modules') ]
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "url-loader?limit=10000&mimetype=application/font-woff"
},
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader : 'file-loader'
}
]
},
plugins: [
new ForkCheckerPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
}),
new ExtractTextPlugin("[name].css"),
new CopyWebpackPlugin([{
from: 'src/assets',
to: 'assets'
}]),
new HtmlWebpackPlugin({
template: 'src/index.html',
chunksSortMode: 'dependency'
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
"Tether": 'tether',
"window.Tether": "tether"
})
],
node: {
global: 'window',
crypto: 'empty',
module: false,
clearImmediate: false,
setImmediate: false
}
};
Can anybody help me? Tks!
I had this issue and it took me the better part of an hour to realize all I had to do was remove the .ts extension from the import. For me:
// index.ts
import { renderSection, useConfig, writeToFile } from './hooks.ts'
// changed from `./hooks.ts` to `./hooks`
import { renderSection, useConfig, writeToFile } from './hooks'
This is what I use and it works pretty well.
Full webpack config here: https://gist.github.com/victorhazbun/8c97dc578ea14776facef09a115ae3ad
webpack.config.js
'use strict';
const webpack = require('webpack');
module.exports = {
...
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
...
};
For me the case was VSCode was using different Typescript version where as the workspace was dependent on different version. Need to select the one from the workspace.
Click on version in the status bar:
and select the version from the workspace.
I had the same problem and the solution for me was to just re-run the application. In my case, I had just finished converting some files to .tsx, perhaps it explains it.
I'm not sure what the exact solution to this question is. Apparently, the solution is to remove the .ts extension — it is a configuration issue if it cannot find the file. For me the configuration issue was resolved when I started using ts-loader.
To solve your problem, you need:
Make sure that you have a tsconfig.json file in the project.json with code
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx" }, "include": ["src"] }
Check or create a react-app-env.in.ts file with the code
/// <reference types="react-scripts" />
It is this react-app-env.d.ts file that explains TypeScript how to work with ts, tsx, and so on file extensions
Remove tsx file extensions in imports. Also remove all extensions that TypeScript will swear at
For example before:
import { Header } from "./Header.tsx";
This should be the case after removing extensions:
import { Header } from "./Header";
If you had a project running at the time of these changes, stop it and start it again. Since these changes are applied only when the project is started at the compilation stage

Resources