What is actually happening when you import a npm package?

Sorry, another noob NPM question.

When compiling a npm project from TS to js I see, for instance, at the top of my converted js code:

“use strict”;
Object.defineProperty(exports, “__esModule”, { value: true });
const transformNode_1 = require("@babylonjs/core/Meshes/transformNode");
const math_1 = require("@babylonjs/core/Maths/math");
const Meshes_1 = require("@babylonjs/core/Meshes");
const Materials_1 = require("@babylonjs/core/Materials");
const Actions_1 = require("@babylonjs/core/Actions");
const Animations_1 = require("@babylonjs/core/Animations");
const nodeStage_1 = require("…/ts/nodeStage");

But I don’t see anywhere in my SRC folder those @babylon tree shaked packages as converted js files. They exist obviously in the node_modules folders as nodes, but that will be outside the scope of a live project. How do I get those packages to compile in? Sorry, if I am not making much sense. I just want those @babylon files to compile into my javascript output file so they can be used on a webserver.

1 Like

OK, so I think I am just not understanding NPM.
Where do I put all the npm package files on my webserver so they are included?

website
| index.html
–css
–src
---- (compiled javascript (from ts using ES6) are here, these have includes to import * from @babylon/blah but those @babylon files are not currently on my server)

How does one set this all up?

When I initially started down this path I thought I could just use Webpack to generate a single javascript file with everything I needed (engine functions w tree shaking for size, my own code). But not having much luck getting this to work. Locally, things are fine but when I move it from my webpack-dev-server to an online dev server to play more things don’t work as @babylon is missing as an include.

Yes, I already read over the NPM and ES6 documentation.

1 Like

I believe I had to add this to my webpack.config.js once to solve the same problem of BJS not getting compiled in (it didn’t resolve the .js files):

resolve: {
  extensions: ['.ts', '.js', '.json']
}

No luck

I reverted back again to default ES6 eamples, so things look like:

tsConfig.json:
{
“compilerOptions”: {
“module”: “esNext”,
“target”: “es5”,
“moduleResolution”: “node”,
“outDir”: “./src”,
“allowJs”: true,
“types”: [
“babylonjs”,
“babylonjs-gui”,
“babylonjs-loaders”,
“babylonjs-materials”,
“jquery”
]
}
}

webpack

module.exports = {
  resolve: {
      extensions: ['.ts', '.js', '.json']
  },
  module: {
      rules: [{
          test: /\.tsx?$/,
          loader: 'ts-loader'
      }]
  }
}

Though I have tried likely 60 different ways of doing it today.
@Gijs, did you actually get a single (or set) of js files from your ts files with all @babylon includes embeded as code instead of import links? or are @babylon files just housed on the server somewhere, if so how does that linking work?

1 Like

I’ve never used standalone ES6 modules, always one js file that includes babylon code. I don’t use a babylon.d.ts file, and I use output module “commonjs”:

tsconfig.json:

{
    "compilerOptions": {
        "target": "es2015",
        "module": "commonjs",
        "sourceMap": true,
        "allowJs": false,
        "experimentalDecorators": true,
        "rootDir": "./src/",
        "baseUrl": "./src/",
        "types": []
    }
}

webpack.config.js:

module.exports = {
  entry: {
    croncle: './src/main/index.ts'
  },
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true
        }
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.json']
  },
  output: {
    filename: '[name].js'
  },
  optimization: {
    minimize: false
  }
}

Maybe my @babylons are not in the right spot?

Are your node_modules sitting at top level of the workspace (mine are) or inside your src?

I just copied your settings and started getting hundreds of namespace errors, which makes sense I think… as I think your code is missing namespace type definitions.

1 Like

Maybe @sebavan can help?

You can have a look at github.com/babylonjs/Controls which does bundling with Webpack :slight_smile: it should help you with the setup.

1 Like

OK first, Babylon controls are going to be super beneficial!

I stole your config files, and slightly modified to point to my directories and… well nothing.

without having the namespace library declarations in types i get about 400 namespace errors that all look like
node_modules/babylonjs-inspector/babylon.inspector.module.d.ts:3373:47 - error TS2694: Namespace ‘BABYLON’ has no exported member ‘Observable’.

3373         onPropertyChangedObservable?: BABYLON.Observable<PropertyChangedEvent>;
                                               ~~~~~~~~~~

So 1) Why is your code not having namespace issues without including anything in “type” = [babylonjs, jquery, ext…]

If I do add that and and look at the compiled code, it is still showing

import { TransformNode } from "@babylonjs/core/Meshes/transformNode";

Although that is proper es6/esnext include the @babylon does not seem to point to anything as that is not a valid URL. If I upload to a dev server the browser (chrome, ff, edge) will freak and page wont load as it does not understand the @babylon and treats it like a syntax error. Even if it did understand those links, I am not seeing anywhere in my code where webpack is transpiling the node_modules from their original location into my project code as additional js files, or additions to my files.

Ideally I think I want to compile everything so - the bablyon tree shook files and my source into a single file (or at least a single location). That is how I feel it should work, though rarely how I feel something should work, relates to how it does work. So how, does it work on reality? Oddly, your structure for Control’s now is as identical as I can make mine look using a single entry point project but I am seemingly the only one having issues :unamused:

Could you share your project ?

It looks like you are using babylonjs/inspector instead of @babylonjs/inspector as described in the doc ? This would definitely generate weird typings errors.

Sorry, I have been bouncing in and out of the hospital :frowning:

I stripped out everything but structure, build files and includes
https://github.com/playwithtechnology/PWT-Structure

I tried both using the NPM and ES6 methods outlined on babylons sites, but did not have luck. I then tried ESNext as somewhere I was reading the required to include transition may have got borked.

Anyway, ideally I want to compile all of my tree shook code with all included dependency into a single javascript file.

I am indeed using the wrong inspector vs @inspector , thanks! However, the errors are not just from inspector but from everywhere I have an include

I resolve those namespace errors in my tsconfig by including the babylon namespace. When I do that everything in my src seems to compile if the files are in my src folder, but the babylon include links reference code in node_modules which don’t seem to ever compile, just remain as include links. Without them nothing works. I feel like moving the entire node_modules folder which is huge, and wont get me the single file I need is not correct.

I know behind the scenes I can get things to compile to a single file by using webpack-dev-server to preview compile things. Though that seems like a hack.

1 Like

Still struggling with this.

Do most people at this point not use typescript for production and are just sticking with native javascript?

I was debating reverting back, but that’s a lot of BABYLON.xxx to add in :frowning:

1 Like

I have not much experience with this topic yet but just want to give my 5 cents to it:

You may check out this boilerplate setup: GitHub - BeardScript/babylonjs-webpack-boilerplate: BabylonJS + Webpack minimal boilerplate for development and production, supporting es6 and/or typescript.
Just clone it with GIT…

I used this for the start, because webpack is not easy :wink: After an update of all npm modules I needed to change the webpack.config.js like this:

let webpack = require('webpack');
let HtmlWebpackPlugin = require('html-webpack-plugin');
let LiveReloadPlugin = require('webpack-livereload-plugin');
const path = require('path');

module.exports =  {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname,'dist'),
    filename: 'bundle.js'
  },
  resolve: {
    modules: [path.resolve(__dirname, '/src'), 'node_modules/'],
    descriptionFiles: ['package.json'],
    extensions : ['.js', '.ts', '.tsx']
  },
  module: {
    rules: [
      {
        use: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      },
      {
        use: 'ts-loader',
        test: /\.tsx?$/,
        exclude: /node_modules/
      },
      {
        use: ['style-loader', 'css-loader'],
        test: /\.css$/
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      inject: false, //prevents double firing the code
      template: 'index.html'
    }),
    new LiveReloadPlugin()
  ],
  externals: {
    oimo: 'OIMO', //or true
    cannon: 'CANNON', //or true
    earcut: 'EARCUT'
  }
};

/* const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
var CompressionWebpackPlugin = require('compression-webpack-plugin');

 if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map';
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),

    new UglifyJsPlugin({
      sourceMap: true
    }),

    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.(js|ts|vue|json|png|jpg|gif|svg)$/,
      threshold: 10240,
      minRatio: 0.8
    }),

    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ]); 
}  */

Needed to comment out the UglifyJsPlugin because it was not working anymore after the update and I don’t had the time yet to go deeper, but it works nice now!

Not excactly answeres your question, but maybe it can help :sweat_smile:

This is why aFalcon rolls-own-vanilla-module-systems. I’m a lightweight. Just sayin. :joy:

Respect for @sebavan because…

Module-Systems non-trivial. : )

:eagle: