As someone new to the world of JS library development, I have embarked on a journey to achieve the following goals:
- Creating a library with TypeScript
- Generating a bundle using webpack5
- Publishing the library to npm
- Utilizing the library in other projects by installing the npm package
The process went smoothly until step 4, where I faced an issue upon trying to reference functions from functions.ts
. Strangely enough, importing the library into script.js
executed the code specified in index.ts
, allowing me to see the log output. What additional steps should I take within index.ts
to successfully reference functions and classes from other files like functions.ts
? Keep in mind that this library will primarily be used in front-end JS files. Thank you for your assistance!
Project folder structure:
root
|-dist
| |-library.js
|
|-scr
| |-functions.ts
| |-index.ts
|
|-node_modules
I aim to use index.ts
as a centralized file containing references to all functions and classes without any logic.
functions.ts
export function add(x: number, y: number): number {
return x + y;
}
export function multiply(x: number, y: number): number {
return x * y;
}
export function subtract(x:number, y:number): number {
return x - y;
}
index.ts
import * as func from './functions'
var f1 = func.add(2, 5);
console.log('f1 - ' + f1);
var f2 = func.subtract(6, 2);
console.log('f2 - ' + f2);
var f3 = func.multiply(10, 2);
console.log('f3 - ' + f3);
export { func }
tsconfig.json
{
"compilerOptions": {
"target": "es6",
"lib": ["es6", "dom"],
"outDir": "src",
"sourceMap": true,
"strict": true,
"module": "ES2015",
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
devtool: 'eval-source-map',
mode: 'development',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: path.resolve(__dirname, 'node_modules'),
include: [path.resolve(__dirname, 'src')]
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'library.js',
path: path.resolve(__dirname, 'dist'),
library: 'library',
libraryTarget: 'umd',
umdNamedDefine: true
},
};
New project - script.js
import * as lib from './node_modules/library/dist/library.js'
var a = lib.library.add(2, 9); // -- error, library is not found.
console.log(a);