My goal is to develop a javascript script using typescript, and finally import that script as a third party script in any website project (I tested with Nextjs so far).
My typescript project
Inventory
Here is my tsconfig.json
file:
{
"compilerOptions": {
"target": "ES2022",
"module": "UMD",
"moduleResolution": "Node",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
My package.json
file:
{
"name": "my-project-name",
"version": "0.0.1",
"description": "...",
"main": "index.js",
"scripts": {
"dev": "tsnd --respawn src/index.ts",
"build": "tsc -p tsconfig.json"
},
"repository": {
"type": "git",
"url": "..."
},
"keywords": [
"..."
],
"author": "...",
"license": "ISC",
"bugs": {
"url": "..."
},
"homepage": "...",
"devDependencies": {
"@types/node": "^20.12.8",
"typescript": "^5.4.5"
},
"dependencies": {
"ts-node-dev": "^2.0.0"
}
}
I have a src/utils/Helpers.ts
file:
export const Log = (what: any) => {
console.log(what)
}
And finally a src/index.ts
file:
import { Log } from './utils/Helpers'
Log('Hello :) from Log')
console.log('Hello :) from console.log')
Compiling
Running the npm run dev
command shows both expected console.log
:
> tsnd --respawn src/index.ts
[INFO] 15:02:17 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.9.2, typescript ver. 5.4.5)
Hello :) from Log
Hello :) from console.log
Running the npm run build
command generates a dist
folder containing my .js
files.
Running the node dist
command shows both expected console.log
, same result as npm run dev
.
Finally, I put the whole thing on github and hosted it on netlify.
Third party script
I created a new Nextjs project and tried to import my script from netlify as a third party script:
In layout
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<script src="https://my-project-name.netlify.app/dist/index.js"></script>
<body className={inter.variable}>{children}</body>
</html>
)
}
With next component
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<Script src="https://my-project-name.netlify.app/dist/index.js" />
<body className={inter.variable}>{children}</body>
</html>
)
}
In page component
'use client'
import Script from 'next/script'
export default function Home() {
return (
<Script
src="https://my-project-name.netlify.app/dist/index.js"
onLoad={() => {
console.log('Script has loaded')
}}
/>
)
}
Result
Neither script console.log is displayed, except the one saying ‘Script has loaded’, which makes me think that the script has been loaded, but for some reason, is not executed.
Plus, the call to index.js
hosted on netlify is visible in the network tab in developer tools.
Can anyone help me on that one please ?