Search code examples
google-chrome-extensionrequirejstypescriptamd

How can I import TypeScript AMD modules without making the dependent code a module


I have a Chrome extension content script that has 2 AMD dependencies. The script works fine when I load the dependencies using the requirejs "require" function.

I ported the script to TypeScript with the rest of my project, and am now using

import Dependency = require("Dependency");

which is all fine and dandy, the modules have been ported to TS and are working fine in other parts of the project.

My issue is that as soon as I add an import statement, the TS compiler wants to make my script into a module, and in the generated JS it imports the modules using requirejs "define". My chrome extension is not too thrilled about this, and when I run it I get a "mismatched anonymous define" error.

Is there any way to get the typescript compiler to use the require function to load my modules instead of making my script a module? I'm having difficulty finding anything about this.


Solution

  • The best way to handle this is to actually compile with the commonjs flag and use the fact that the TypeScript compiler doesn't actually emit require statements if the module import isn't used in a value position. This is similar to the "optional module loading" advanced scenario documented in the Modules in TypeScript page.

    Sample code:

    declare var require: any; // If needed
    import _a = require('Dependency');
    import _b = require('SomeOtherDependency');
    
    var a: typeof _a = require('Dependency');
    var b: typeof _b = require('SomeOtherDependency');
    
    // Use 'a' and 'b' in your code. Do not use _a or _b.
    a.doSomething();