Module parse failed: Unexpected character '#' - node.js

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.

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/**/*"
]
}

Building es6 module in typescript project with webpack

I am trying to use imagemin node package in my project. It is a es6 module and I am getting error while using it.
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module. with "type" as "module" in package.json
ReferenceError: require is not defined with "type" as "commonjs" in package.json
My webpack config:
export default env => {
return {
mode: env.production ? 'production' : 'development',
entry: {
main: './src/main.ts',
worker: './src/worker.ts'
},
target: ['node', 'es2019'],
devtool: env.production ? false : 'inline-source-map',
watch: !env.production,
resolve: {
extensions: ['.ts', '.js'],
alias: {
src: _resolve(process.cwd(), './src')
}
},
module: {
rules: [{
test: /\.ts$/,
include: _resolve(process.cwd(), "src"),
use: 'ts-loader',
exclude: [/node_modules/, /\.spec\.ts/, /\.e2e-spec\.ts/]
}],
},
externalsPresets: { node: true },
externals: [nodeExternals()],
output: {
filename: '[name].js',
path: OUTPUT_DIR,
clean: !!env.production,
devtoolModuleFilenameTemplate: 'file:///[absolute-resource-path]',
library: {
type: 'module'
}
},
optimization: {
minimize: false, //!!env.production
mangleExports: true,
minimizer: [new terserPlugin({
terserOptions: {
output: {
comments: false
},
keep_classnames: true,
},
extractComments: false,
})]
},
experiments: {
outputModule: true
}
};
};
My tsconfig:
{
"compilerOptions": {
"module": "ES2020",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2019",
"sourceMap": true,
"strict": true,
"baseUrl": ".",
"esModuleInterop": true,
"noImplicitAny": true,
"moduleResolution": "node",
"outDir": "../bin/server",
"typeRoots": [
"node_module/#types",
"./typings"
],
"types": [
"node",
"#types/jest"
]
},
"exclude": [
"node_modules"
]
}
When I try to "import" imagemin in one of my .ts file, webpack convert it to "require". I have also tried using import() but it doesn't work either.
I have made a repo on github
Is there a way to get es6 bundle (preferred) or use imagemin with commonjs bundle?
I couldn't found a way to bundle es6 format through webpack but i was able to use es6 module in commonjs system while bundling through webpack.
externals: [
nodeExternals({
allowlist: ['imagemin', 'imagemin-mozjpeg']
}),
async function ({ request }) {
if (request === 'imagemin' || request === 'imagemin-mozjpeg')
return `import ${request}`;
},
]
This is how i got imagemin to work.
Change your start script
"start": "node --experimental-modules src/index.mjs "
and In package.json Add
{
...
"type": "module",
...
}

"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"
],
...
}

How do I set up Webpack, Angular 2.0, and Django together?

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

Resources