Exporting Global Styles with Font Assets from a TypeScript->CommonJS module - node.js

I have a TypeScript React project organized as follows:
tsconfig.json
package.json
yarn.lock
lerna.json
node_modules/
packages/
ui-library/
package.json
tsconfig.json
typings.d.ts
src/
fonts/
myfont.ttf
components/
GlobalStyle.tsx
lib/ <-- `tsc` builds to here
web-app/
package.json
src/
components/
The web-app imports the ui-library as a commonjs module in its package.json. This is managed through Yarn Workspaces, hence node_modules being at the root instead of each folder. At one point, the web-app imports GlobalStyle from the ui-lib, which is where the issue occurs.
Error: Cannot find module '../fonts/myfont.ttf'
Require stack:
- /Users/me/sources/myproject/packages/ui-library/lib/styles/GlobalStyle.js...
Here is the original import statement from ui-library/src/GlobalStyle.tsx that causes the issue:
import myFont from "../fonts/myfont.ttf";
const GlobalStyle = () => (
<style global jsx>{`
#font-face {
font-family: "My font family";
src: url(${myFont}) format("truetype");
}
...</style>);
The issue is the require statement in the emitted GlobalStyle.js code, built when I run tsc in the ui-lib folder:
const MYFONT_ttf_1 = __importDefault(require("./myfont.ttf"));
I googled this issue online, and I found you had to add typings for compiling .ttf and other abnormal imports. So I created a typings.d.ts file with this declaration:
declare module "*.ttf" {
const value: string;
export default value;
}
And I included it on ui-library/tsconfig.json as follows:
{
"extends": "../../tsconfig.json",
"exclude": ["lib"],
"include": ["src"],
"files": ["./typings.d.ts"],
"compilerOptions": {
"baseUrl": "src",
"outDir": "lib",
"declaration": true,
"declarationMap": true,
"noEmit": false
}
}
The tsconfig above extends the root tsconfig:
{
"files": ["./typings.d.ts"],
"compilerOptions": {
"module": "commonjs",
"target": "es2019",
"lib": ["dom", "es2019"],
"strict": true,
"jsx": "react",
"moduleResolution": "node",
"isolatedModules": true,
"esModuleInterop": true,
"noUnusedLocals": false,
"forceConsistentCasingInFileNames": true,
"strictNullChecks": true,
"sourceMap": true,
"noEmit": true,
"declaration": false
},
"exclude": ["node_modules"]
}
We are using TypeScript 3.8. Let me know if there is any additional info to provide. My hunch is that I am either using the wrong module/target, or fundamentally misunderstanding some aspect of this.
More Details
I should note the reason we are using CommonJS modules is because ts-node can only work with that. We pull in ts-node when we are doing our gatsby build, following the gist here in gatsby-config.js:
require("ts-node").register();
// Use a TypeScript version of gatsby-config.js.
module.exports = require("./gatsby-config.ts");
Maybe it's an impossible problem to solve, to get fonts imported through ts-node which is a server side environment? Confused on what the right approach is to export a module with fonts. Willing to get rid of ts-node, and leave the Gatsby config files as js.. but mostly just want to be able to import my fonts.

I solved this by just copying the fonts as part of build steps. Basically, fonts have their own pipeline. There may be better ways, but this works well enough.

Related

Is there any way to not compile folders, that comes from path:{...}

I want tsc to compile my project as:
built/
- package.json
- app.js
- etc.
not:
built/
- test/lambda/first/src/
- app.js
- package.json
my tsconfig looks like this currently:
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES2017",
"noImplicitAny": true,
"preserveConstEnums": true,
"declaration":true,
"baseUrl": "./",
"outDir": "./built",
"sourceMap": true,
"paths": {
"#utils/*": ["../../../common/layers/test2/*"]
},
"esModuleInterop": true
},
"include": ["./**/*"],
"exclude": ["node_modules"]
}
And what i want to do is tell tsc to dont compile the folder "common" inside my built folder and also dont make a file structure like this? Is it possible with only tsconfig settings? I know how to do it with linux commands, but the point would be that tsc should handle it.
(I only want to use paths for developing, i dont actually want them in my built folder because it will access those files in the cloud)

module resolution from 'dist' folder

I'm working on a nodeJs/Typescript app and I would like to be able to launch it from the dist/ folder.
The structure of each src and dist folders is something like that :
server/
|---dist/
| |---server/
| |---src/
| |---index.js
| |---utils/
| |---connection.js
|---src/
| |---index.ts
| |---utils/
| |---connection.ts
|
|---package.json
|---tsconfig.json
This dist folder is the generated code, with this path being configured using outDir inside of my tsconfig.json file.
I have also configured the main property in my package.json to be dist/server/src/index.js and the type property to be module
In this project, I am using Typescript 4.0.5
I have specified paths property in my tsconfig.json to be "utils/*" : ["src/utils/*"], the baseUrl property to be './' and the property moduleResolution strategy to be node
Now this is my issue. I would like to be able to import my modules the same way i do in my source code, but this time directly from the dist folder, like this :
import createConnection from 'utils/connexion';
However, when i hover the import declaration in VScode, it does not seems to resolve the module and i get an error Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'utils' imported from /home/maxime/Dev/JeuxDuPlacard/packages/server/dist/server/src/index.js
When i do the same operation from my Typescript files, it works as expected.
The paths of the files in the dist folder is the same in the Server folder. If the problem comes form the module resolution, Is there a way to persist the paths aliases in the dist folder (without installing a third party library) ?
{
"compilerOptions": {
"esModuleInterop": true,
"target": "es2020",
"moduleResolution": "node",
"sourceMap": true,
"baseUrl": "./",
"outDir": "dist",
"strict": true,
"lib": ["ES2017", "ES2020"],
"types": [
"node"
],
"allowSyntheticDefaultImports": true,
"noImplicitAny": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"incremental": true,
"skipLibCheck": true,
"strictPropertyInitialization": false,
"paths": {
"utils/*": ["src/utils/*"]
}
}
}
Thanks
That's right, because you CAN'T import files from outside your workdir. What you could do, is you could link a local module and access it as you would any other npm package.
npm link (in package dir)
npm link [<#scope>/]<pkg>[#<version>]
alias: npm ln
https://docs.npmjs.com/cli/v6/commands/npm-link

How to add shortcuts to modules in Nodejs Typescript

So we have a ReactTs project and we implemented shortcuts to things like our utils folder, So instead of calling the relative path everytime we use it in a module we just call #utils. We did this by adding path in our tsconfig.json.
This feature looks so handy and clean we decided to do the same on our Nodejs Typescript application. But when we compile the project and run the compliled js project it returns an error that seems #utils is not found. is there a way over this? How can we tell to compile the #utils to the declared relative path?
tsconfig file:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "./build",
"strict": true,
"baseUrl": "./",
"paths": {
"#interface": [
"interface/index.ts"
],
"#utils":[
"src/utils/index.ts"
]
},
"types": [
"node_modules/#types"
],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Project directory:
So to solve this I implemented this npm: https://www.npmjs.com/package/module-alias.

importing class in Node js with typescript

I would import class in nodejs and use it in app.ts
var nano = require("nano");
import { EnvConfig } from './envConfig.service';
let config = new EnvConfig();
const dbCredentials: any = config.appEnv.getServiceCreds('dataservices');
export const nanodb = nano({
url: dbCredentials.url,
});
export const nanodbCockpitLight = nanodb.use('data');
console.log(dbCredentials);
When I try to compile I get this error.
import { EnvConfig } from './envConfig.service';
^
SyntaxError: Unexpected token {
I have created the tsconfig file :
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
//"baseUrl": "src" // Attention !! nécessite l'utilisation d'un loader de module node pour fonctionner sur node
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
I get this warning
No inputs were found in config file 'c:/Users/EHHD05911.COMMUN/Documents/cockpitLight/DB mananger/tsconfig.json'. Specified 'include' paths were '["src//"]' and 'exclude' paths were '["node_modules","/.spec.ts"]'
You cannot run node app.ts file directly that won't work
You need transpiler like babel js or typescript compiler tsc so first transpile to js file and then run node app.js
You're using .js extension, you need .ts extension, e.g.: app.ts instead of app.js.
Make sure you have typescript either in npm global or in dev dependencies.
I suspect whatever you're importing has typescript syntax (strong typing and such), and so running node directly won't work. You need to run tsc first, which will transpile everything to javascript in a dist folder, and then run node dist/app.js.
This is a bit cumbersome though, which is why there is ts-node. It's exactly what it sounds like, a node REPL for typescript. You should be able to run ts-node src/app.ts.
import { something } is a typescript syntax, it won't work in a .js file. That is a separate language. Try using require instead.
Use babel js which is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
package.json
"dependencies": {
"#babel/polyfill": "^7.0.0",
}
"babel": {
"presets": [
"#babel/preset-env"
]
},
"scripts": {
"start": "server.js --exec babel-node",
}
https://babeljs.io/docs
This will enable/resolve your import statements.

Error importing node modules in TypeScript

I had a problem this morning that was driving me crazy. I'll explain the issue and then I'll provide my answer below (so that others who come across this can get to a solution sooner).
It is very easy to duplicate the issue by just issuing these commands:
tsd query react --action install
mkdir src
echo "import React = require('react');" > src/foo.ts
I also included the following tsconfig.json file in src:
{
"version": "1.6.2",
"compilerOptions": {
"outDir": "./tsdir",
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"isolatedModules": false,
"jsx": "react",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true
},
"files": [
"foo.ts"
]
}
If I try to compile this by simply running the tsc (version 1.6.2) command inside src, I get:
foo.ts(1,24): error TS2307: Cannot find module 'react'.
What I find baffling here is that I've installed the react bindings with tsd but when I run tsc, I get this error. It looks like I've done everything right, so why the error?
So what I eventually figured out was that I need to explicitly include the typings file in my list of "files", i.e.,
{
"version": "1.6.2",
"compilerOptions": {
...
},
"files": [
"foo.ts",
"../typings/react/react.d.ts"
]
}
In other words, I had to include the typings files explicitly in the "files". I don't really know why. I thought tsc was smart enough to look for them itself.
If there is a better solution that doesn't involve having to list all the .d.ts files explicitly in "files", I'm all ears. But I just wanted to point out that this is at least a workaround.

Resources