A webpack loader that converts JSDoc types from namepaths with module identifiers to types for Closure Compiler.
This is useful for type checking and building a set of ES modules with Closure Compiler, e.g. through the webpack-closure-compiler plugin.
$ npm install --save-dev webpack-jsdoc-closure-loader
Add the loader to the modules
section of your webpack configuration:
module: {
rules: [{
test: /\.js$/,
loaders: ['webpack-jsdoc-closure-loader'],
exclude: /node_modules/
}]
},
Each file needs a @module
JSDoc annotation with the path and name at the top of the file. If you have a file src/foo/bar.js
and src
is the package root, use the following annotation:
/** @module foo/bar */
Define the type using a JSDoc module identifiers, e.g.
/** @type {module:foo/bar.mytype} */
const foo = {
bar: 'baz'
};
The type used above is defined in src/foo/bar.js
like this:
/** @typedef {{bar: string}} */
export let mytype;
or
/** @typedef {{bar: string}} mytype */
Since typedefs are just shorthands for complex types in Closure Compiler, they can be inlined wherever they are used. In the above example, the result that the compiler sees will be
/** @type {{bar: string}} */
const foo = {
bar: 'baz'
};
When bundling your application, webpack will import types from other files. Let's say you have a file foo/Bar.js
with the following:
/** @module foo/Bar */
/**
* @constructor
* @param {string} name Name.
*/
const Bar = function(name) {
this.name = name;
};
export default Person;
Then you can use this in another module with
/**
* @param {module:foo/Bar} bar Bar.
*/
function foo(bar) {}
The bundler will get something like
const foo$Bar = require('./foo/Bar');
/**
* @param {foo$Bar} bar Bar.
*/
function foo(bar) {}
With this, the type definition is made available to the module that uses the type.
Closure Compiler does not recognize imported enums, so these are repeated locally. If module types
specifies
/** @enum {number} */
export const Foo = {
BAR: 1,
BAZ: 2
};
and another module uses
/** @type {module:types.Foo} */
const foo;
the bundler will get something like
/** @enum {number} */ let _types_Foo = { BAR: 1, BAZ: 2 };
_types_Foo = require('./types').Foo;
/** @type {_types_Foo} */
const foo;
Repeating the enum locally and in addition requiring it helps the copiler understand the enum in cases where it is also imported locally by the source.