パッケージの詳細

jscc

aMarCruz112.3kMIT1.1.1

Tiny and powerful preprocessor for conditional comments and replacement of compile-time variables in text files

html, parser, javascript, typescript

readme

jscc

jscc on npm License MIT Linux Build Codacy Coverage

Featuring some of the C preprocessor characteristics through special, configurable comments, jscc can be used in any type of files to build multiple versions of your software from the same code base.

With jscc, you have:

  • Conditional inclusion/exclusion of blocks, based on compile-time variables*
  • Compile-time variables with all the power of JavaScript expressions
  • Replacement of variables in the sources, by its value at compile-time
  • Sourcemap support, useful for JavaScript sources.
  • TypeScript v3 definitions

* This feature allows you the conditional declaration of ES6 imports (See the example).

jscc is derived on jspreproc, the tiny source file preprocessor in JavaScript, enhanced with sourcemap support but without the file importer nor the removal of comments (rollup with rollup-plugin-cleanup does it better).

jscc works in NodeJS 6 or later, with minimal dependencies and footprint. It was designed to operate on small to medium pieces of code (like most nowadays) and, since the whole process is done in memory, it is really fast.

jscc is not a minifier tool, but it does well what it does...

Install

Use the instructions of the plugin for your toolchain:

or install the jscc package from npm if you need direct access to its API:

npm i jscc -D

Direct Usage

const jscc = require('jscc');

const result = jscc(sourceCode, options);

// or in async mode:
jscc(sourceCode, options, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result.code);
    console.log(result.map);
  }
})

The result is a plain JS object with a property code, a string with the processed source, and a property map, with a raw sourcemap object, if required by the sourcemap option (its default is true).

If a callback is provided, jscc will operate asynchronously and call the callback with an error object, if any, or null in the first parameter and the result in the second.

Please see the Wiki to know the supported options.

Directives

jscc works with directives inserted in the text and prefixed with configurable character sequences, that defaults to '/*', '//' and '<!--'.

This directives allows you set or get compile-time variables, and exclude code blocks based in its value.

Here, I will refer to the names of the compile-time variables as varnames, to distinguish them from the JavaScript run-time variables.

To be valid, a <varname> must match the regular expression /^_[0-9A-Z][_0-9A-Z]*$/.

That is, it must start with an underscore, followed by a digit or uppercase letter, and then zero or more underscores, digits or uppercase letters. The character $ has a special use in jscc and is not allowed for varnames.

#set <varname> = <value>

Defines or redefines a varname.

The value can be a literal value, another varname, or an expression. If you don't specify a value, it is set to undefined.

#unset <varname>

Removes the definition of the given varname.

Both the definition or removal of a varname take immediate effect.

#if <expression>

Remove the block of code that follows this #if if expression is falsy.

You can nest multiple #if blocks.

#ifsef <varname>

Check the existence of a varname.

The returned value is true if the variable exists, even if its value is undefined. Apart from this, the behavior of #ifset is the same as #if, so references to the latter will imply both.

#ifnsef <varname>

This is the opposite to #ifset, it returns false if the varname does not exists.

#elif <expression>

The behavior of #elif is similar to the JS else if statement.

The expression will be evaluated if the previous #if or #elif was falsy.

You can have zero or more #elif directives following one #if.

#else

Includes the block that follows if the previous #if or #elif expressions were falsy.

#endif

Closes the current conditional block.

#error <expression>

Generates an exception at compile time with the result of the given character expression.

You can learn more about this in the Wiki.

Changes in This Version

  • Closes #8 : Removel of trailing jscc comment is breaking the expression.
  • Removed Codebeat tests.
  • More unity tests.

See details in the Changelog.

Known Issues

  • If you are using ESM imports with Typescript, you must enable esModuleInterop in your tsconfig.json or use import jscc = require("jscc").
  • jscc does not work in a browser, but it must work without issues on the back-end.

ES6 TL

Remember that jscc is language agnostic, the following block may or may not work as you think:

const template = `
//#if _DEBUG
console.log('debug mode is on.')
//#endif
`
fs.writeFile('code.js', template, 'utf8')

Directive searching knows nothing about ES6 TL, so the #if..#endif within the template will be evaluated at compile-time, just like any other (code.js is written without directives).

TODO

  • [X] Async mode (v1.0.0)
  • [ ] Explanatory error messages, with location of the error
  • [ ] Different prefixes for different file types
  • [ ] Express middleware
  • [ ] WebPack plugin
  • [ ] Better documentation
  • [ ] Syntax hilighter for some editores? Perhaps you want to contribute.

Support my Work

I'm a full-stack developer with more than 20 year of experience and I try to share most of my work for free and help others, but this takes a significant amount of time, effort and coffee so, if you like my work, please consider...

Of course, feedback, PRs, and stars are also welcome 🙃

Thanks for your support!

License

The MIT License.

© 2018, Alberto Martínez

Windows Build CodeClimate Vulnerabilities Last commit

更新履歴

Changes for jscc

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

[1.2.0] - 2018-12-28

Added

  • More tests.
  • markdownlint config.
  • perf-regexes as dependency, for the JS_STRINGS regex.
  • skip-regex as dependency to help solving #8

Changed

  • Revised .gitignore
  • Update dependencies and devDependencies.
  • Update Readme.
  • Replace node 10 with the 'node' in travis config.

Fixed

  • Regex in remap-vars being copied by reference.
  • 8 removal of trailing comment is breaking expressions.

  • tslint errors.

Removed

  • .npmignore, now using package.json 'files' property.
  • unused ESLint configuration.

[1.1.0] - 2018-11-22

Added

  • Option escapeQuotes to escape quotes in the output of strings (not wrapped by JSON output).
  • TSLint instead of ESLint, for compatibility with CI services.
  • Codacy quality and coverage services.

Changed

  • Convert export.default to module.exports in internal modules. Since it is a node.js library, it looks right and produces a cleaner code.
  • The output of chained properties stops with a primitive value, to avoid some compile-time errors.
  • Updated Readme, add "vulnerabilities" badge from snyk.io.
  • Regression of the replacement of NaN with null since the later alters the behavior of the Date ctor.
  • Simplify the parseChunk function, logic moved to the parseHelper class.

Removed

  • ESLint configuration.
  • Coverity badge, get the right results with this service is a nightmare.

Fixed

  • Minor issues with linters.

[1.0.0] - 2018-10-23

Major refactorization after two years, using TypeScript v3.

Added

  • Support for BOM mark in the source (it is preserved and does not affects the parsing).
  • Badges of the different services used to take care of the quality of the code.
  • Buy me a Coffee link.
  • Support for replacement with instances of Number.
  • Share .vscode setup for launch, settings, and tasks in CVS.
  • .npmignore files, for distribution with minimal stuff.
  • Sync test for async operation.
  • Async operation.
  • Add prefix for <! (alt html comment) to the predefined prefixes.
  • Support for replacement with more than one object property.

Changed

  • Revised Readme (WIP)
  • Make readonly the predefined variables _FILE and _VERSION.
  • Integrate Coverity (static analysis), CodeClimate (quality), Codebeat (quiality/analysis) and Codecov (coverage).
  • More strict ESLint rules.
  • Test modularizated and ready, 100% coverage.
  • Rewrite test in TypeScript
  • Package "expect", now part of jest, is replaced with expect.js.
  • Replacement in code accepts more than one object properties, Date and RegExp outputs strings, NaN outputs null.
  • Rewrite revars, evalExpr and remapVars, remove macro support, new logic for replacements.
  • Rewrite parseOptions, modularize some functions.
  • Internal modules now have named exports, main module (jscc) has default export
  • Configure ESLint to use the TypeScript parser.
  • First unoptimized conversion to Typescript.
  • Use .eslintrc.js instead .eslintrc.yaml, the JS format is easier to maintain.
  • Keep package manager locks as local.
  • Use "Keep a Changelog" recommendations for the changelog.
  • Update the LICENSE file to MIT (it was incorrect).
  • Update devDependencies and minimum node.js version to 6.

Removed

  • The undocumented option errorHandler was removed, which makes the logic more simpler and secure.
  • The "dist" folder holding the transpilled code is excluded from CVS (slim PRs, simpler CI config)
  • (Internal) Remove babel, as the plugin now runs on node.js v6 or later.

[0.3.5] - 2016-10-23

  • Add link to gulp plugin for jscc. Thanks to @gucong3000.
  • Add test witj workaround to #3: "not work with eslint rule: comma-spacing" using the prefixes option.
  • Updated devDependencies.

[0.3.4] - 2016-10-23

  • Added support for nested object and micro-like abilities (thanks to @bergi9).
  • Updated devDependencies.

[0.3.3] - 2016-10-23

  • Fixes issue with sourceMap generating incorrect output.

[0.3.2] - 2016-10-22

  • Fixes an issue with losing location in sourceMap after replacing memvars.
  • Now JSCC always returns an object, even if there were no changes.
  • Updated devDependencies.

[0.3.1] - 2016-10-14

  • Source map includes the source filename (needed by jscc-brunch).
  • Removed jscc own source maps from the distribution.
  • The CommonJS version is validated by Coverty Scan.

[0.3.0] - 2016-10-06

  • Initial Release published as v0.3.0 in npm over an old jscc tool from Taketoshi Aono.