1


i would like to know how to add Namespace declaration to my js bundle.

I have typescript class in myclass.ts

export class MyClass{
...
}

I use this class in others files

export {MyClass} from "myclass"
...
let a:MyClass = new MyClass();

I compile it into vs code and use grunt to automate concat of different files and minimify with terser.

Everything is fine except i would like to have a namespace before my class when use it in js

<script src="mylib.min.js"></script>
...
var a = new MYLIB.MyClass();

Where in the process do i introduce the "MYLIB" namespace ? I want to continue to work on the export/import pattern so i do not want to include the namespace nor module name inside TS file.

Is there a grunt plugin to doing so ? I do not find any clear informations, nor samples, on the topic.

2 Answers2

0

Your code mixes javascript and typescript. You are building a minified javascript file from typescript then writing further javascript (var a = new MYLIB.MyClass();). That is puzzling to me as normally you would be writing all your code in one or the other. That said, javascript does not have any concept of namespacing, so new MYLIB.MyClass() is not valid. On the other hand, namespaces do exist in typescript, so if you're using the class in the context of typescript, you can use that syntax: https://www.typescriptlang.org/docs/handbook/namespaces.html

Please also see this answer for information on how you can kind of partially fake namespaces in pure javascript. Basically a "namespace" in javascript is just an object like any other, which is why new namespace.myClass() doesn't work; you can't put a class definition on an object.

see sharper
  • 11,505
  • 8
  • 46
  • 65
  • Thank's for the answer, use case is because i still own several html/js to maintain. I perfectly understand the way we have js object at root, to fake namespace. My question was how to automate the creation of this root during build process with grunt. Again many thank's. – Guillaume Pelletier Mar 31 '20 at 11:04
0

Did not found any easy solution with Grunt only, then i move to webpack and use

output: {
    library: 'MYLIB',
    libraryTarget: 'var',
    filename: '[name].' + config.version + '.js' ,
    path: path.resolve(__dirname, 'dist'),
}

I understand that webpack and grunt are not intended to be used in the same way, but somehow we can use both. i will also have a look on webpack/gulp couple. thanks all reader and @see shaper to took time to answer. Stay safe at home.