Giter Club home page Giter Club logo

ifdef-loader's Introduction

ifdef-loader

Webpack loader that allows JavaScript or TypeScript conditional compilation (#if ... #elif ... #else ... #endif) directly from Webpack.

Conditional compilation directives are written inside /// triple slash comment so that they don't effect normal JavaScript or TypeScript parsing.

Example:

/// #if DEBUG
console.log("there's a bug!");
/// #endif

The DEBUG or any other variable can be specified when configuring the Webpack loader (see below).

The directive #if accepts any valid JavaScript expression:

/// #if PRODUCTION && version.charAt(0)=='X'
console.log("Ho!");
/// #endif

If the expression is true the block of code between #if and #endif is included, otherwise is excluded by commenting it out.

Additionally, #elif and #else clauses can be added to an #if clause:

/// #if env == 'PRODUCTION'
console.log('Production!');
/// #elif env == 'DEBUG'
console.log('Debug!');
/// #else
console.log('Something else!');
/// #endif

The #if clauses can also be nested:

/// #if PRODUCTION
      /// #if OS=="android"
      android_code();
      /// #elif OS=="ios"
      ios_code();
      /// #endif
/// #endif

Installation

In webpack build directory:

npm install ifdef-loader --save-dev

Configuration

Example of use with TypeScript files, enabling the DEBUG and version variables:

In webpack.config.json put ifdef-loader after ts-loader so that files are processed before going into TypeScript compiler:

// define preprocessor variables
const opts = {
   DEBUG: true,
   version: 3,
   "ifdef-verbose": true,                 // add this for verbose output
   "ifdef-triple-slash": false,           // add this to use double slash comment instead of default triple slash
   "ifdef-fill-with-blanks": true         // add this to remove code with blank spaces instead of "//" comments
   "ifdef-uncomment-prefix": "// #code "  // add this to uncomment code starting with "// #code "
};

/* ... */ { 
   test: /\.tsx?$/, 
   exclude: /node_modules/, 
   use: [
      { loader: "ts-loader" }, 
      { loader: "ifdef-loader", options: opts } 
   ]
}

// alternatively, options can be passed via query string:
const q = require('querystring').encode(opts);
/* ... */ { 
   test: /\.tsx?$/, 
   exclude: /node_modules/, 
   loaders: [ "ts-loader", `ifdef-loader?${q}` ] 
}

in example.ts:

/// #if DEBUG
     /* code to be included if DEBUG is defined */
///   #if version <2
        /* code to be included if DEBUG is defined and version < 2*/
///   #endif
/// #endif

Code in comments

Often times writing #if ... #else ... #endif results in code that is not syntactically valid or does not pass the LINT check. A possible workaround is to hide such code in comments and let ifdef-loader uncomment it if it's part of the block that has to be included in the output.

Example:

The following code is invalid because the linter sees a double declaration of the a variable.

// #if DEBUG
let a=1;
// #else
let a=2;
// #endif

Using code in comments:

// #if DEBUG
let a=1;
// #else
// #code let a=2;
// #endif

The code is now under comment so it's ignored by the linter; but it's uncommented by ifdef-loader if the else branch has to be included in the output (that is when DEBUG==false).

The // #code string prefix can be changed and has to be explictly specified in the options object:

const opts = {
   // ...
   "ifdef-uncomment-prefix": "// #code ",
   // ...
};

License

MIT

Contributions

Contributions in the form of issues or pull requests are welcome.

Changes

  • v2.3.0 added option uncomment-prefix to write code in comments allowing it to pass through linters and syntax checking

  • v2.2.0 added option fill-with-blanks for removing code with blank spaces instead of // comments

  • v2.1.0 added support for #elif clause.

  • v2.0.0 BREAKING CHANGE: options are now passed using the standard Webpack API (loader-utils). See below for the upgrade.

  • v1.0.0 changed to triple slash comment syntax. Double slash syntax deprecated and available by turning off the ifdef-triple-slash option.

  • v1.0.3 fixed bug occurring with short lines. Improved handling of line termination (CRLF vs LF) in order to preserve source maps.

  • v1.1.0 added support for #else clauses.

Upgrading from v1 to v2

In v2 options are passed differently than v1, so you need to update your webpack.config.js. Just do the following simple changes:

/* from */ const q = require('querystring').encode({json: JSON.stringify(opts)});
/* to   */ const q = require('querystring').encode(opts);
/* you can keep the  ... `ifdef-loader?${q}` ... syntax    */
/* but it's better to pass options directly (see the docs) */

ifdef-loader's People

Contributors

chrisjpatty avatar florentferry avatar gwigwam avatar ian-craig avatar nippur72 avatar sgratzl avatar stephenlautier avatar tiejunhu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ifdef-loader's Issues

Error if "options" is not defined in webpack config

I am relying on Webpack to replace a var used with the #ifdef statements so don't need to actually pass values through the options. Kind of an edge case, but noticed if options is not provided, get this vague error upon running webpack:

use: [
    { loader: 'babel-loader' },
    { loader: 'ifdef-loader' }, // errors if `options` is not provided
],

TypeError: Cannot read property 'json' of null

Passing empty object fixes it and everything seemingly works as expected:

use: [
    { loader: 'babel-loader' },
    { loader: 'ifdef-loader', options: {} }, // all good
],

Thanks. Very useful plugin!

[Feature Request] Add support for #elif

Add support for an #elif operator (similar to C's #elif preprocessor)

Currently one might write:

/// #if Version == 1
console.log('v1');
/// #endif
/// #if Version == 2
console.log('v2');
/// #endif
/* This cannot be replaced with #else because it would also trigger if Version == 1: */
/// #if Version != 1 && Version != 2
console.log('other version');
/// #endif

Or:

/// #if Version == 1
console.log('v1');
/// #else
///   #if Version == 2
console.log('v2');
///   #else
console.log('other version');
///   #endif
/// #endif

This would become:

/// #if Version == 1
console.log('v1');
/// #elif Version == 2
console.log('v2');
/// #else 
console.log('other version');
/// #endif

It's a bit shorter, and in my opinion much more readable.

Change would be non-breaking.

If you are interested in this feature and are still maintaining this package and repo please let me know. I can probably implement this feature and create a pull request within the coming 1 or 2 weeks.

Html preprocecor

Hi,

Is-it possible to preprocessing html files?

Exemple:

<!--#if dev-->
<div>DEVELOPMENT VERSION</div>
<!--#endif-->

Thanks for your job :)

Add #define

I'm trying to figure out how to build a "full" and "lite" version from the same codebase with one webpack config file.

If #define was supported, I could have two entry files, app.js and app-lite.js, with the latter starting #define LITE 1. This would then be used with #if etc. to slim down the build.

Has anyone gotten ifdef-loader to work with Angular 13?

Title says it all. I'm trying to upgrade from Angular 10 to 13. Using the patch provided in another thread I had ifdef-loader working but it looks like the whole webpack setup has changed drastically in Angular 13 so the patch no longer works.

I've tried to use "ifdef-loader": "^2.3.0" with "@angular-builders/custom-webpack": "^13.0.0" using https://medium.com/angular-in-depth/customizing-angular-cli-build-an-alternative-to-ng-eject-v2-c655768b48cc as a guide.

My custom config is:

// ifdef-loader config

const opts = {
   APP: false,
   WEB: true,
   DEBUG: true,
   version: 3,
   "ifdef-verbose": true,                 // add this for verbose output
   "ifdef-triple-slash": true,           // add this to use double slash comment instead of default triple slash
   "ifdef-fill-with-blanks": true         // add this to remove code with blank spaces instead of "//" comments
   "ifdef-uncomment-prefix": "// #code "  // add this to uncomment code starting with "// #code "
};

module.exports = {
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: [
          { loader: 'ts-loader' },
          { loader: 'ifdef-loader", options: opts }
        ]
      }
    ]
  },
....

My .ts files are not getting processed by ifdef-loader. 

Any hints or pointers at what I should look at next would be greatly appreciated.

[Feature Request] place condition into /**/

Hi there,

There is a case when using TSX. Unfortunately triple slash wont work (or I am missing something).

Usage example:

class Test extends Component {
    render () {
        return (
            <div>
{/* #if __SERVER__ */}
		<ChannelsList />
{/* #endif */}
            </div>	
        );
    }
}

Performance improvement: skip files

While testing my (slow) webpack build process I noticed that ifdef-loader was taking a long time. Just had a quick look over the source code and think there are a lot of improvements that could be done.

First one, and easiest one, would be to skip files that don't contain the // #if string, before doing all the line splitting and going through all the lines.

export function parse(source: string, defs: object, verbose?: boolean, tripleSlash?: boolean): string {
if(tripleSlash === undefined) tripleSlash = true;
useTripleSlash = tripleSlash;
const lines = source.split('\n');
var ifBlocks = find_if_blocks(lines);
for(let ifBlock of ifBlocks) {
apply_if(lines, ifBlock, defs, verbose);
}
return lines.join('\n');
}

Could just add this before the splitting (line 42):

// Skip files that don't have ifdefs
if(!source.includes('// #if')) return source;

Webpack & Angular 7

Hello, first I wanted to thank you for this great module by the way, very useful :)

As I'm kind of a noob regarding webpack (I usually use ng-cli), I was wondering if it would be possible to have an example to make it work with Angular 7 ?

I installed the @angular-builders/custom-webpack package and can successfully have a custom webpack config. With the verbose activated, I can see the ifdef being detected but unfortunately the built app still contains the conditional blocks.

Here is my webpack config and my app :

custom-webpack-config.js:

var path = require('path');
var env = require("./src/environments/environment.json");


const opts = {
  env,
  DEBUG: true,
  "ifdef-verbose": true,       // add this for verbose output
};

console.log('Custom webpack config loaded');

module.exports = {
  entry: {
      main: './src/main.ts'
  },
  output: {
      path: path.resolve(__dirname, '../app/templates')
  },
  plugins: [],
  module: {
    rules: [{
      test: /\.tsx?$/,
      exclude: /node_modules/,
      use: [
        { loader: 'ts-loader' },
        { loader: 'ifdef-loader', options: opts }
      ],
    }]
  }
};

src/main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

/// #if DEBUG
console.log('Debug activated!');
/// #endif

I'm wondering if the output is not being overwritten by another part of the webpack. Could someone help me please ?

Thanks for your time !

[Feature Request] Provide a way to write optional code hide in comment

Background

Sometime, mix all conditional code together may not allowed by linters.
Need a way to write optional code, able to avoid linting errors.

Actual

/// #if ! __DEBUG__
const foo = "bar" // Cannot redeclare block-scoped variable 'foo'
/// #else
var foo = "bar" // Cannot redeclare block-scoped variable 'foo'
const __hotUpdate = ()=>{
  foo="bar2" // Cannot assign to 'foo' because it is a constant
}
/// #endif

Expected

/// #if ! __DEBUG__
const foo = "bar"
/// #else
/// var foo = "bar"
/// const __hotUpdate = ()=>{
///   foo="bar2"
/// }
/// #endif

Maybe?

  1. // code
  2. /// code
  3. /* code */

Cannot use defines that have dashes

You cannot use defines that use dashes (similar to ifdef-verbose) because this doesn't evaluate as proper JavaScript:

/// #if my-custom-define

The Haxe language compiler converts -D my-custom-define to #if my_custom_define when evaluating source files, perhaps this would be a reasonable solution?

Related issue:

openfl/openfl#1911

Improve documentation to include onlyCompileBundledFiles option

The ts-loader config should include the onlyCompileBundledFiles: true option. Otherwise, files that are required to be pre-processed to be valid and are currently not imported might produce ghost errors. Adding this option will exclude these files from the build.

      {
        test: /\.ts$/,
        exclude: /node_modules/,
        use: [
          { loader: 'ts-loader', options: { onlyCompileBundledFiles: true } },
          { loader: 'ifdef-loader', options: { "ifdef-verbose": true, WEB: false, NODE: true } },
        ],
      },

It took me an hour to figure this out.

Excellent library, loving it!

use loader-utils to get options

HI,

Nice idea.

You are forcing the users to use a query string to provide options to the loader.

Webpack loader configuration comes with support for setting options either by

  • Options object
  • query string

Webpack has a best practice and tooling for that, so you don't care how the user provided the options, you just get them:

Instead of querystring install loader-utils, then:

const loaderUtils = require('loader-utils');

function loader() {
  const options = loaderUtils.getOptions(this);
}

Now you have the options ready for you.

This is also future proof, using that util will ensure that if webpack changes the way options are defined it will still work for you.

ESLint bad indentation

The idea to use // #code as a "placeholder" to make eslint works is very appreciated but substituting // #code with spaces lead eslint to complain about the fact that expected indentation was 0 but found 9.

I think we just should replace with "" to maintain the real intended indentation

lines[t] = " ".repeat(r.groups.before.length) + r.groups.line;

Loader not works for imported scripts

I have two files

dependency.js

export default function test() {
    // #if BROWSER=='chrome'
    console.log('chrome');
   // #endif
}

index.js

import test from './dependency.js';

// #if BROWSER=='chrome'
console.log('chrome');
// #endif
test();

loader sees conditional directive and processes her in index.js but conditional directive in 'dependency.js' stays not processed

how can I handle this case?

Throwing an error when a variable is not defined

These are my options:

const opts = {
  "ifdef-verbose": true,
  "ifdef-triple-slash": true
};

In some .js file I have:

/// #if STATS
console.log('stats defined');
/// #else
console.log('stats not defined');
/// #endif

And when I try running my project:

Module build failed: Error: ifdef-loader error: error evaluation #if condition(STATS): ReferenceError: STATS is not defined

Obviously I didn't defined STATS in the loader options. But, why throw an error if STATS is not defined? For me makes no sense to throw an error in this case, I would expect that the '#if STATS' part is removed and the '# else' part is kept.

Is this the desired behaviour, or am I missing something?

Define environment variables by default

I think it'd make sense to define everything in process.env by default, so instead of

/// #if env == 'PRODUCTION'
/// #if PRODUCTION

one can do a more standard

/// #if NODE_ENV === 'production'
/// #if process.env.NODE_ENV === 'production'

Variables defined in options should overwrite bare variables like NODE_ENV but process.env should always reflect the actual environment.

I imagine this would allow to integrate the loader with default options in most cases.

Deprecation warning when used with webpack 5.0.0

When using ifdef-loader with webpack 5.0.0 the following deprecation warning is shown:

/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web $ node --trace-deprecation node_modules/webpack/bin/webpack.js
(node:9695) [DEP_WEBPACK_MODULE_ERRORS] DeprecationWarning: Module.errors was removed (use getErrors instead)
    at Object.reportTranspileErrors (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/ts-loader/dist/instances.js:263:24)
    at successLoader (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/ts-loader/dist/index.js:28:17)
    at Object.loader (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/ts-loader/dist/index.js:24:5)
    at LOADER_EXECUTION (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:132:14)
    at runSyncOrAsync (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:133:4)
    at iterateNormalLoaders (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:251:2)
    at iterateNormalLoaders (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:240:10)
    at /Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:255:3
    at Object.context.callback (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/loader-runner/lib/LoaderRunner.js:124:13)
    at Object.module.exports (/Users/doberkofler/MyDev/ljs_app/trunk/desktop/ttr/web/node_modules/ifdef-loader/ifdef-loader.js:34:14)

babel-loader complains about syntax errors in code that should be removed

I have a .js file with an entry that looks like this:

{
  text: 'link text',
  /// #if CONDITION
  url: 'url/if/true'
  /// #else 
  url: 'url/if/false
  /// #endif
}

I have tried setting up my webpack.config.js rules in a couple of different ways, neither of which is currently working:

webpackConfig.rules version 1

[
  { test: /\.(js|jsx)$/,
    use: [ 'babel-loader' ],
    exclude: /node_modules/ },
  ...
  { test: /\.(js|jsx)$/,
    use: [{ loader: 'ifdef-loader', options: { CONDITION: false } } ],
    exclude: /node_modules/ }
];

webpackConfig.rules version 2

[
  { test: /\.(js|jsx)$/,
    use: [ 'babel-loader',  { loader: 'ifdef-loader', options: { CONDITION: false } } ],
    exclude: /node_modules/ },
  ...
];

What happens is the babel-loader complains about a missing comma on the url: 'url/if/true' line, when that line (or the other one, depending on the condition) should not even be getting to the babel-loader, if my understanding of loaders is correct.

exact errors look like this:
ERROR in SyntaxError: path\to\folder \file.js: Unexpected token, expected "," (linenumber)

I can see that the ifdef-loader appears to be getting applied correctly if I turn on verbose, but the babel-loader still fails after that.

ifdef-loader not reflecting in main.js

hi @nippur72
i installed ifdef-loader 2.3.0 to understand this package, but i see that its not really removing code in main.js , my changes below. logs during build clearly sharing message, but not reflecting main.js. can you please let me know what has went wrong here.

///// custom-webpack.config.js ///////

const opts = {
myVal: 1,
"ifdef-verbose": true, // add this for verbose output
"ifdef-triple-slash": true, // add this to use double slash comment instead of default triple slash
"ifdef-fill-with-blanks": true, // add this to remove code with blank spaces instead of "//" comments
"ifdef-uncomment-prefix": "// #code " // add this to uncomment code starting with "// #code "
};
module.exports = {
module: {
rules: [
{
test: /.ts?$/,
exclude: /node_modules/,
use: [
{ loader: "ts-loader" },
{ loader: "ifdef-loader", options: opts }
]
},
]
}

////// app.component.ts ///////

export class AppComponent {
/// #if myVal==2
title: string = 'preprocessorexmple 1';
/// #endif
/// #if myVal!=2
title1: string = 'preprocessorexmple ';
/// #endif
constructor() {
}
}

// verbose
ng build
⠦ Generating browser application bundles (phase: building)...#if block lines [9-11]: Condition 'myVal==2' is FALSE. Excluding everything (src\app\app.component.ts)
#if block lines [12-14]: Condition 'myVal!=2' is TRUE. Including lines [12-14] (src\app\app.component.ts)

///// main.js generated file //////
} }
class AppComponent {
/// #endif
constructor() {
/// #if myVal==2
this.title = 'preprocessorexmple 1';
/// #endif
/// #if myVal!=2
this.title1 = 'preprocessorexmple ';
}
}

Regular expression not working well in some cases

Hi,

Pretty cool loader, but I ran into a problem. When I set the --host property of the webpack-dev-server, the ifdef-loader doesn't work anymore. The dude at webpack-dev-server didn't really seem to be open to the conversation so I don't really know why.

Here are the details: webpack/webpack-dev-server#2623

You can find a complete repro here: https://github.com/TanukiSharp/webpack-dev-server-host-ifdef-loader

Would you accept a PR to get rid off the regular expressions ? Or at least to make their use optional with a traditional parsing fallback method ?

@ngtools/webpack

Hi,

Instead of ts-loader, I have use ngtools/webpack which compile and perform AoT. does ifdef-loader work with ngtools/webpack?
cheers,
Khoa

Failing to process files after update from 2.0.3 to 2.1.0

Our CI started failing today after this update. Depending on the build, some files are not having the ifdef comments processed.

Example build logs:

...

[01:14:09][Step 4/7] ERROR in ./src/mvc/model/PlatformModel.js
[01:14:09][Step 4/7] Module build failed: Duplicate declaration "ledgerPromise"
[01:14:09][Step 4/7] 
[01:14:09][Step 4/7]   1010 |     });
[01:14:09][Step 4/7]   1011 |     /// #else
[01:14:09][Step 4/7] > 1012 |     const ledgerPromise = ledger.runPurchaseFunction(config.purchaseFunction, purchaseCopy);
[01:14:09][Step 4/7]        |           ^
[01:14:09][Step 4/7]   1013 |     /// #endif
[01:14:09][Step 4/7]   1014 | 
[01:14:09][Step 4/7]   1015 |     return ledgerPromise.then(
[01:14:09][Step 4/7] 
[01:14:09][Step 4/7] BabelLoaderError: Duplicate declaration "ledgerPromise"
[01:14:09][Step 4/7] 
[01:14:09][Step 4/7]   1010 |     });
[01:14:09][Step 4/7]   1011 |     /// #else
[01:14:09][Step 4/7] > 1012 |     const ledgerPromise = ledger.runPurchaseFunction(config.purchaseFunction, purchaseCopy);
[01:14:09][Step 4/7]        |           ^
[01:14:09][Step 4/7]   1013 |     /// #endif
[01:14:09][Step 4/7]   1014 | 
[01:14:09][Step 4/7]   1015 |     return ledgerPromise.then(
[01:14:09][Step 4/7] 
[01:14:09][Step 4/7]     at transpile (/Users/teamcityAgent2/workspace/buildAgent/work/e12c3c134554c23d/frontend/node_modules/babel-loader/lib/index.js:65:13)
[01:14:09][Step 4/7]     at /Users/teamcityAgent2/workspace/buildAgent/work/e12c3c134554c23d/frontend/node_modules/babel-loader/lib/fs-cache.js:118:18
[01:14:09][Step 4/7]     at ReadFileContext.<anonymous> (/Users/teamcityAgent2/workspace/buildAgent/work/e12c3c134554c23d/frontend/node_modules/babel-loader/lib/fs-cache.js:31:21)
[01:14:09][Step 4/7]     at ReadFileContext.callback (/Users/teamcityAgent2/workspace/buildAgent/work/e12c3c134554c23d/frontend/node_modules/graceful-fs/graceful-fs.js:90:16)
[01:14:09][Step 4/7]     at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:420:13)
[01:14:09][Step 4/7]  @ ./src/Application.js 129:21-59

...

simple if statement does not behave as expected

If I set a variable to true in the config, a simple evaluation does not appear to work.
e.g. in options:

{
  DEBUG: true
}

in code:

let mode = 'production';
/// #if DEBUG
mode = 'debug';
/// #endif
console.log(mode);

In this scenario, mode is 'production', not 'debug' as expected. I had to use:

/// #if DEBUG === true

to get this to work as expected. (Triple equals is probably not necessary). The documentation suggests that DEBUG just needs to be a truthy value for this to work as expected, without an explicit evaluation.

How to config for .ts file?

There are config webpack example for .tsx file in the Readme, and it worked for .tsx file in my project, but it's not work for .ts file when I add #if comment in .ts file.
The code below is my webpack config, it used awesome-typescript-loader for .tsx file, and added resolve for .ts, .tsx file:

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        include: path.resolve(__dirname, 'src'),
        use: [
          {
            loader: 'awesome-typescript-loader',
            options: {
                  useBabel: true,
                  useCache: true,
                },
          },
          { loader: 'ifdef-loader', options: opts },
        ],
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.ts', '.tsx'],
    modules: [path.resolve(__dirname, 'node_modules/'), 'node_modules'],
  },

Anyone know how to make it work for .ts file?

Use ifdef-loader with ESLint

Hi! Thank you for the tool!

Is there a way to use ifdef-loader with ESLint?

I try to conditionally import two files, but ESLint says that the syntax is broken:

// #if USE_FLASH
import embedpano from 'lib/krpano_flash/swfkrpano';
// #else
import embedpano from 'lib/krpano/krpano';
// #endif

ESLint output:

10:8  error  Parsing error: Identifier 'embedpano' has already been declared

/////// leftovers in HTML code when mixed with JSX

I have the following in the code:

      <Head>
/// #if PRODUCTION
        <script
          async
          src="https://www.googletagmanager.com/gtag/js?id=UA-3500050-6"
        />
/// #endif
      </Head>

ifdef works properly, but what happens in addition is that section of the HTML markup contains multiple
///////////////// ///////////////////////////// //////////////////

Once I remove the ifdef from JS messy characters in the head are also gone.

I wonder at which point this problem is happening

This is part of Next.js project. with SSR

Give a option to decide whether the loader is cacheable

Thanks for your ifdef-loader, it's exactly what I need.
But I have a problem when I want to compile my code more than one time.

I find out that is because the loader is cacheable.
So I wonder if it's possible to give a option to decide whether the loader is cacheable.

Looking forward to your apply.

How I use in webpack.config.js is like below

const createIfDefineLoader = (isH5) => ({
  test: /\.(js|vue(\?[^?]+)?)$/,
  use: [{
    loader: 'ifdef-loader',
    options: {
      'ifdef-triple-slash': false,
      'ifdef-fill-with-blanks': true,
      'ifdef-uncomment-prefix': '// #code ',
      'ifdef-verbose': true,
      DEBUG: process.env.NODE_ENV === 'development',
      APP: !isH5,
      H5: isH5
    }
  }]
})
const webConfig = {
  // ...
   module: {
      rules: [
         // ...
         createIfDefineLoader(true)
      ]
  }
}
const nativeConfig = {
  // ...
   module: {
      rules: [
         // ...
         createIfDefineLoader(false)
      ]
  }
}
module.exports = [webConfig, nativeConfig];

using with react-app-rewired

Hi,

I am trying out ifdef-loader with react-app-rewired.

Below are the contents of my config-overrides.js file
`

module.exports = function override(config, env) {
console.log('override!');

const opts = {
    PRODUCTION:false,
    DEBUG: true,
    "ifdef-verbose": true
 };
  
let loaders = config.module.rules[2].oneOf;

loaders.splice(loaders.length - 1, 0, {
    test: /\.js$/,
    use: [
        { loader: "echo-loader?msg=dump" },  
        { loader: "ifdef-loader", options: opts } 
     ]
});

return config;

};`

When I dump the files being processed by echo-loader I see my files are not getting processed

dump.txt

Any clues on how I can get it working with react-app-rewired ?

Cheers
Ajay

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.