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

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

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

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

Webpack build fail when adding a specific external lib

It happens on a build for server side, i am already using a lot of external modules and everything worked great until now.
I am trying to add the module auth0-js and the error happens when i add the import on this lib var crypto = require('crypto'); TypeError: require is not a function.
Here is my webpack config (for server side):
const path = require('path');
const webpack = require('webpack');
const StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: './handler.js',
target: 'node',
profile: false,
output: {
path: path.resolve(__dirname, '../dist-server'),
publicPath: '/',
filename: 'handler.js',
libraryTarget: 'commonjs'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '..'),
use: 'babel-loader'
},
{
test: /\.pug$/,
use: 'pug-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
__CLIENT__: false,
__SERVER__: true
}),
new StatsPlugin('stats.json', {
chunkModules: true,
exclude: [/node_modules[\\\/]react/]
})
],
resolve: {
modules: [
path.resolve('./src'),
path.resolve('./node_modules')
]
},
devtool: 'source-map'
};
My .babelrc file is:
{
"presets": [
"react",
"latest"
],
"plugins": [
"transform-object-rest-spread",
"transform-runtime"
]
}
I tried to remove the exclude node_modules but i get other errors.
I am curious to know how a single library can break everything, what should i do?

"npm run" hanging on ts-loader (webpack)

I am building a web app that consists of static HTML and other assets using webpack on Mac OS X 10.11.3. The app talks to an API that is on another server.
I am having trouble building my app using webpack. The build process appears to hang at or around the ts-loader execution. I am running my build like this:
npm run go --loglevel verbose
which executes this command from my package.json:
./node_modules/.bin/webpack-dev-server --display-reasons --display-chunks --watch
The output in the Terminal window ends with
ts-loader: Using typescript#1.7.5 and /Users/mn/Documents/source/J/appstore/store-front/app/ts/tsconfig.json
I have tried deleting the node_modules folder and reinstalling these; I have tried uninstalling webpack and reinstalling; I have tried reverting my webpack.config.js to a version I know works; but it just hangs here!
My webpack.config.js looks like this:
var webpack = require('webpack'),
ReloadPlugin = require('webpack-reload-plugin'),
path = require('path'),
ChunkManifestPlugin = require('chunk-manifest-webpack-plugin'),
HtmlWebpackPlugin = require('html-webpack-plugin'),
WebpackNotifierPlugin = require('webpack-notifier'),
ExtractTextPlugin = require("extract-text-webpack-plugin");
/**
* optimist has been depracted. Find an alternative? minimist?
*/
var argv = require('optimist')
.alias('r', 'release').default('r', false)
.argv;
/**
* Useful variables
*/
var cwd = process.cwd();
var DEBUG = !argv.release;
var isDevServer = process.argv.join('').indexOf('webpack-dev-server') > -1;
var version = require(path.resolve(cwd, 'package.json')).version;
var reloadHost = "0.0.0.0";
var npmRoot = __dirname + "/node_modules";
var appDir = __dirname + "/app";
var entry = ["./app/ts/bootstrap"]
if (isDevServer) {
entry.unshift("webpack-dev-server/client?http://" + reloadHost + ":8080");
}
function makeConfig(options) {
return {
cache: true,
debug: true,
verbose: true,
displayErrorDetails: true,
displayReasons: true,
displayChunks: true,
context: __dirname,
entry: {
app: entry,
vendor: './app/ts/vendor.ts'
},
stats: {
colors: true,
reasons: DEBUG
},
devtool: 'source-map',
recordsPath: path.resolve('.webpack.json'),
devServer: {
inline: true,
colors: true,
contentBase: path.resolve(cwd, "build"),
publicPath: "/"
},
output: {
path: path.resolve(cwd, "build"),
filename: "[name].js",
publicPath: "/",
chunkFilename: "[id].bundle.js",
// Hot Module Replacement settings:
hotUpdateMainFilename: "updates/[hash].update.json",
hotUpdateChunkFilename: "updates/[hash].[id].update.js"
},
plugins: [
new webpack.IgnorePlugin(/spec\.js$/),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new webpack.optimize.CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] }),
new ExtractTextPlugin("styles.css"),
new webpack.DefinePlugin({
VERSION: JSON.stringify(version),
ENV: JSON.stringify(options.env)
}),
new HtmlWebpackPlugin({
template: path.join(appDir, "index.html"),
}),
new ReloadPlugin(isDevServer ? 'localhost' : ''),
new WebpackNotifierPlugin({
title: "Jisc AppStore App"
}),
],
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
modulesDirectories: ['node_modules'],
fallback: path.join(__dirname, "node_modules")
},
resolve: {
root: [path.resolve(cwd)],
modulesDirectories: [
'node_modules', 'app', 'app/ts', '.'
],
extensions: ["", ".ts", ".js", ".json", ".css"],
alias: {
'app': 'app',
'scripts': npmRoot
}
},
module: {
preLoaders: [
{ test: /\.ts$/, loader: "tslint" }
],
loaders: [
{ test: /\.(png|jp?g|gif)$/, loaders: ["url", "image"] },
{ test: /\.json$/, loader: 'json' },
{ test: /^(?!.*\.min\.css$).*\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader?sourceMap") },
{ test: /\.scss$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap'] },
å { test: /\.html$/, loader: "html" },
{ test: /\.ts$/, loader: 'ts', exclude: [/test/, /node_modules/] },
{ test: /vendor\/.*\.(css|js)/, loader: 'file-loader?name=[path][name].[ext]', exclude: [/node_modules/] },
{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader?limit=10000&minetype=application/font-woff" },
{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" }
],
noParse: [
/\.min\.js/,
/vendor[\/\\].*?\.(js|css)$/
]
},
tslint: {
emitErrors: false,
failOnHint: false
}
}
}
var config = makeConfig(argv)
console.log(require('util').inspect(config, { depth: 10 }))
module.exports = config;
My tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noEmitHelpers": false,
"sourceMap": true
},
"filesGlob": [
"./app/**/*.ts",
"!./node_modules/**/*.ts"
],
"compileOnSave": false,
"buildOnSave": false
}
Can anyone suggest what might be happening? I don't seem to be able to produce any logs from either the webpack dev server or the npm build.
After hours of reverse-engineering ts-loader I finally found out what was causing this "freeze" (as it may seem) in my case:
I am building a web scraper and had amassed around 40Gb of cached data in a hashed directory structure between the previous, successful deployment and the now failing/freezing deployment.
Turned out, since I'd forgotten to include the root cache directory in the "exclude" option in my tsconfig.json, ts-loader was going through all sub-folders in the cache directory. So, it wasn't actually hanging, it was just looking through millions of files.
When I added the cache directory to the excluded files option, everything went back to normal.
Hope this helps you with your issue. In case you want to look into what's going on with typescript, I'd recommend to experiment with some console.logs in the visitDirectory-function in typescript.js. This was what finally helped me resolve this problem.
Cheers
Sam

Webpack and TypeScript: Cannot resolve module 'child_process' in node.d.ts

I tried to get webpack, typescript and react.js working together via awesome-typescript-loader, but I constantly get errors.
I am using awesome typescript loader at Version 0.3.0-rc.2 and webpack 1.8.9
This is my webpack.config.js:
module.exports = {
entry: './ui/index.ts',
output: {
path: __dirname + '/build-ui',
filename: 'app.js',
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.ts']
}
};
When I run the webpack dev server and my index.ts looks like this:
alert('hello');
It states the following error:
ERROR in ./ui/index.ts
/Users/..../typings/node/node.d.ts:29:12
Subsequent variable declarations must have the same type. Variable 'require' must be of type 'WebpackRequire', but here has type '{ (id: string): any; resolve(id: string): string; cache: any; extensions: any; main: any; }'.
Same when I put in the reference path.
When I try to import the React.js via import React = require('react'); it states:
ERROR in ./ui/index.ts
Module build failed: Cannot resolve module 'child_process' in /..../typings/node
Required in /..../typings/node/node.d.ts
I copied the node.d.ts file from the loader repo, still no luck.
Has anybody been able to get this combination work smoothly? Or should I just use a different web packager?
I'd really would like to get it to work with webpack.
All you're missing is a key target: 'node'.
This makes sure that the environment you are targeting is Node.js and not the browser, and will therefore ignore native dependencies.
Final Config:
module.exports = {
entry: './ui/index.ts',
target: 'node',
output: {
path: __dirname + '/build-ui',
filename: 'app.js',
publicPath: 'http://localhost:8090/assets'
},
module: {
loaders: [
{
test: /\.jsx$/,
loader: 'jsx-loader?insertPragma=React.DOM&harmony'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.scss$/,
loader: "style-loader!css-loader!sass-loader"
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader?limit=8192'
},
{
test: /\.ts$/,
loader: 'awesome-typescript-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx', '.ts']
}
};
You could consider using a different webpack TypeScript loader. I know a few had issues with node stuff. There are also a couple starter kits that may help out.
Disclaimer: I'm the maintainer of ts-loader.
Try creating a tsconfig.json file.
For example, as you are using awesome-typescript-loader this should work:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noEmitHelpers": true
},
"exclude": [
"node_modules"
],
"awesomeTypescriptLoaderOptions": {
"forkChecker": true
},
"compileOnSave": false,
"buildOnSave": false,
"atom": { "rewriteTsconfig": false }
}

Resources