Skip to content

Commit

Permalink
[js/common] allow import onnxruntime-common as ESM and CJS
Browse files Browse the repository at this point in the history
  • Loading branch information
fs-eire committed May 2, 2023
1 parent 7f293d0 commit b9ec25d
Show file tree
Hide file tree
Showing 19 changed files with 208 additions and 112 deletions.
1 change: 1 addition & 0 deletions js/common/.npmignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/.vscode/

build.js
webpack.config.js
typedoc.json
tsconfig.json
Expand Down
27 changes: 27 additions & 0 deletions js/common/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

'use strict';

import { writeFileSync } from "node:fs";
import { execSync } from "node:child_process";
import {resolve, dirname} from 'node:path';
import {readFileSync} from 'node:fs';
import {fileURLToPath} from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));

// build the following folders:
// - dist/cjs
// - dist/esm
execSync('npm run build:cjs', {shell: true, stdio: 'inherit', cwd: __dirname});
execSync('npm run build:esm', {shell: true, stdio: 'inherit', cwd: __dirname});

// generate package.json files under each of the dist folders for commonJS and ESModule
// this trick allows typescript to import this package as different module type
// see also: https://evertpot.com/universal-commonjs-esm-typescript-packages/
writeFileSync(resolve(__dirname, './dist/cjs', 'package.json'), '{"type": "commonjs"}');
writeFileSync(resolve(__dirname, './dist/esm', 'package.json'), '{"type": "module"}');

// launch webpack to generate bundles
execSync('npm run build:bundles', {shell: true, stdio: 'inherit', cwd: __dirname});
2 changes: 1 addition & 1 deletion js/common/lib/backend-impl.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Backend} from './backend';
import {Backend} from './backend.js';

interface BackendInfo {
backend: Backend;
Expand Down
6 changes: 3 additions & 3 deletions js/common/lib/backend.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {InferenceSession} from './inference-session';
import {OnnxValue} from './onnx-value';
import {InferenceSession} from './inference-session.js';
import {OnnxValue} from './onnx-value.js';

/**
* @internal
Expand Down Expand Up @@ -46,4 +46,4 @@ export interface Backend {
Promise<SessionHandler>;
}

export {registerBackend} from './backend-impl';
export {registerBackend} from './backend-impl.js';
2 changes: 1 addition & 1 deletion js/common/lib/env-impl.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Env} from './env';
import {Env} from './env.js';

type LogLevelType = Env['logLevel'];
export class EnvImpl implements Env {
Expand Down
2 changes: 1 addition & 1 deletion js/common/lib/env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {EnvImpl} from './env-impl';
import {EnvImpl} from './env-impl.js';

export declare namespace Env {
export type WasmPrefixOrFilePaths = string|{
Expand Down
10 changes: 5 additions & 5 deletions js/common/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
* @packageDocumentation
*/

export * from './backend';
export * from './env';
export * from './inference-session';
export * from './tensor';
export * from './onnx-value';
export * from './backend.js';
export * from './env.js';
export * from './inference-session.js';
export * from './tensor.js';
export * from './onnx-value.js';
10 changes: 5 additions & 5 deletions js/common/lib/inference-session-impl.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {SessionHandler} from './backend';
import {resolveBackend} from './backend-impl';
import {InferenceSession as InferenceSessionInterface} from './inference-session';
import {OnnxValue} from './onnx-value';
import {Tensor} from './tensor';
import {resolveBackend} from './backend-impl.js';
import {SessionHandler} from './backend.js';
import {InferenceSession as InferenceSessionInterface} from './inference-session.js';
import {OnnxValue} from './onnx-value.js';
import {Tensor} from './tensor.js';

type SessionOptions = InferenceSessionInterface.SessionOptions;
type RunOptions = InferenceSessionInterface.RunOptions;
Expand Down
4 changes: 2 additions & 2 deletions js/common/lib/inference-session.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {InferenceSession as InferenceSessionImpl} from './inference-session-impl';
import {OnnxValue} from './onnx-value';
import {InferenceSession as InferenceSessionImpl} from './inference-session-impl.js';
import {OnnxValue} from './onnx-value.js';

/* eslint-disable @typescript-eslint/no-redeclare */

Expand Down
2 changes: 1 addition & 1 deletion js/common/lib/onnx-value.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Tensor} from './tensor';
import {Tensor} from './tensor.js';

type NonTensorType = never;

Expand Down
2 changes: 1 addition & 1 deletion js/common/lib/tensor-impl.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Tensor as TensorInterface, TensorFromImageOptions, TensorToImageDataOptions} from './tensor';
import {Tensor as TensorInterface, TensorFromImageOptions, TensorToImageDataOptions} from './tensor.js';

type TensorType = TensorInterface.Type;
type TensorDataType = TensorInterface.DataType;
Expand Down
2 changes: 1 addition & 1 deletion js/common/lib/tensor-utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Tensor, TensorToImageDataOptions, TypedTensor} from './tensor';
import {Tensor, TensorToImageDataOptions, TypedTensor} from './tensor.js';

interface Properties {
/**
Expand Down
4 changes: 2 additions & 2 deletions js/common/lib/tensor.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

import {Tensor as TensorImpl} from './tensor-impl';
import {TypedTensorUtils} from './tensor-utils';
import {Tensor as TensorImpl} from './tensor-impl.js';
import {TypedTensorUtils} from './tensor-utils.js';

/* eslint-disable @typescript-eslint/no-redeclare */

Expand Down
25 changes: 15 additions & 10 deletions js/common/package.json
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
{
"license": "MIT",
"unpkg": "dist/ort-common.min.js",
"type": "module",
"name": "onnxruntime-common",
"version": "1.15.0",
"repository": {
"url": "https://github.com/Microsoft/onnxruntime.git",
"type": "git"
},
"author": "fs-eire",
"module": "dist/lib/index.js",
"version": "1.15.0",
"jsdelivr": "dist/ort-common.min.js",
"scripts": {
"prepare": "tsc && webpack"
"build:cjs": "npx tsc --module commonjs --outDir ./dist/cjs",
"build:esm": "npx tsc",
"build:bundles": "webpack",
"build": "node ./build.js",
"prepare": "npm run build"
},
"devDependencies": {
"typedoc": "^0.23.22"
},
"main": "dist/cjs/index.js",
"exports": {
"require": "./dist/cjs/index.js",
"import": "./dist/esm/index.js"
},
"keywords": [
"ONNX",
"ONNXRuntime",
"ONNX Runtime"
],
"devDependencies": {
"typedoc": "^0.23.22"
},
"main": "dist/ort-common.node.js",
"types": "dist/lib/index.d.ts",
"description": "ONNXRuntime JavaScript API library"
}
4 changes: 3 additions & 1 deletion js/common/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "dist/lib",
"outDir": "./dist/esm",
"declaration": true,
"declarationMap": true,
"esModuleInterop": false,
"noUnusedParameters": true,
},
Expand Down
121 changes: 44 additions & 77 deletions js/common/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,98 +3,65 @@

'use strict';

const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require("terser-webpack-plugin");

function terserEcmaVersionFromWebpackTarget(target) {
switch (target) {
case 'es5':
return 5;
case 'es6':
case 'es2015':
return 2015;
case 'es2017':
return 2017;
default:
throw new RangeError(`not supported ECMA version: ${target}`);
}
}

function addCopyrightBannerPlugin(mode, target) {
const VERSION = require(path.join(__dirname, 'package.json')).version;
const COPYRIGHT_BANNER = `/*!
* ONNX Runtime Common v${VERSION}
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/`;

if (mode === 'production') {
return new TerserPlugin({
extractComments: false,
terserOptions: {
ecma: terserEcmaVersionFromWebpackTarget(target),
format: {
preamble: COPYRIGHT_BANNER,
comments: false,
},
compress: {
passes: 2
}
}
});
} else {
return new webpack.BannerPlugin({ banner: COPYRIGHT_BANNER, raw: true });
}
}
import webpack from 'webpack';
import {resolve} from 'node:path';
import {DEFAULT_ES_VERSION, addCopyrightBannerPlugin} from '../webpack.shared.mjs';

function buildConfig({
suffix = '',
format = 'umd',
target = 'es2017',
mode = 'production',
devtool = 'source-map'
suffix = '.js', // '.js', '.min.js', ...
format = 'umd', // 'umd', 'commonjs'
target = 'web', // 'web', 'node'
esVersion = DEFAULT_ES_VERSION, // 'es5', 'es6', ...
mode = 'production', // 'development', 'production'
devtool = 'source-map' // 'inline-source-map', 'source-map'
}) {
// output file name
const filename = `ort-common${suffix}`;

// variable name of the exported object.
// - set to 'ort' when building 'umd' format.
// - set to undefined when building other formats (commonjs/module)
const exportName = format === 'umd' ? 'ort' : undefined;

return {
target: [format === 'commonjs' ? 'node' : 'web', target],
entry: path.resolve(__dirname, 'lib/index.ts'),
target: [target, esVersion],
entry: resolve('./lib/index.ts'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: `ort-common${suffix}.js`,
library: {
name: format === 'commonjs' ? undefined : 'ort',
type: format
}
path: resolve('./dist'),
filename,
library: {name: exportName, type: format},
},
resolve: {
extensions: ['.ts', '.js'],
extensionAlias: {'.js': ['.ts', '.js']},
},
resolve: { extensions: ['.ts', '.js'] },
plugins: [
new webpack.WatchIgnorePlugin({ paths: [/\.js$/, /\.d\.ts$/] }),
addCopyrightBannerPlugin(mode, target),
new webpack.WatchIgnorePlugin({paths: [/\.js$/, /\.d\.ts$/]}),
addCopyrightBannerPlugin(mode, 'common', esVersion),
],
module: {
rules: [{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
compilerOptions: { target }
}
}
]
test: /\.ts$/,
use: [{
loader: 'ts-loader',
options: {compilerOptions: {target: esVersion}},
}]
}]
},
mode: mode,
devtool: devtool,
mode,
devtool,
};
}

module.exports = (env, argv) => {
export default (env, argv) => {
return [
buildConfig({ suffix: '.es5.min', target: 'es5' }),
buildConfig({ suffix: '.es6.min', target: 'es6' }),
buildConfig({ suffix: '.min' }),
buildConfig({ mode: 'development', devtool: 'inline-source-map' }),
buildConfig({ format: 'commonjs', suffix: '.node' }),
buildConfig({suffix: '.es5.min.js', target: 'web', esVersion: 'es5'}),
buildConfig({suffix: '.min.js'}),
buildConfig({mode: 'development', devtool: 'inline-source-map'}),
buildConfig({
suffix: '.node.cjs',
target: 'node',
format: 'commonjs',
}),
];
};
1 change: 0 additions & 1 deletion js/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"compilerOptions": {
"module": "ES2015",
"moduleResolution": "node16",
"declaration": true,
"esModuleInterop": true,
"target": "ES2020",
"lib": ["ES2020", "ESNext.BigInt", "dom"],
Expand Down
1 change: 1 addition & 0 deletions js/web/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"compilerOptions": {
"module": "CommonJS",
"downlevelIteration": true,
"declaration": true,
"declarationDir": "./types",
"typeRoots": ["./node_modules/@webgpu/types", "./node_modules/@types"]
},
Expand Down
Loading

0 comments on commit b9ec25d

Please sign in to comment.