Replace 'require' on Typescript bundle

2019-05-29 13:14发布

问题:

I have a main TypeScript file with an import to another file like so:

import './app.run';

I use tsproject to compile my ts files into a single bundle and then use System JS in my html page like so:

System.import('app/app.module');

But in my bundle, all the file imports are replaced with commonjs require statements, like so:

require('./app.run');

While there is no longer a app.run file present, because everything is bundled. How do I properly bundle ts without external file imports?

回答1:

In the very latest version of TypeScript (which is 1.5 at the time of writing) you would use the ES6 style of module imports:

import * as Alias from "./app.run";

And compile with the SystemJS module kind.

tsc --module systemjs app.ts

This should be the easiest route to what you want. The SystemJS support is brand new to 1.5.

Notes on internal / external modules...

There has been a lot of confusion about internal and external modules, but my (strong) advise on the subject is that you shouldn't mix internal and external modules.

The idea behind internal modules was to simulate a common pattern were using when writing JavaScript to hide information rather than drop it on the global scope. Doug Crockford spread the word on this one. Essentially, if you have this JavaScript:

var name = 'Nicky';
function sayHello() {
    return 'Hello ' + name;
}

You could take name and sayHello out of the global scope and reduce your footprint to a single variable:

var myNamespace = (function() {
    var name = 'Nicky';
    return {
        sayHello: function () {
            return 'Hello ' + name;
        }
    };
}());

This is admirable, because there is a chance another library will define name or sayHello and whichever loaded last would win.

With external modules, the file is the module. This actually goes one better than the namespace example above, because nothing ends up on the global scope. When you load a module, you give it a local name and there is no pollution. For this reason, you don't need to organise your external modules into internal modules or namespaces. In fact, attempting to do so makes your code worse, not better.

The TypeScript team are renaming internal modules to "namespaces" - see the note under "Simplifying modules" in the TypeScript 1.5 release notes. While this will resolve the confusion between what is meant by "internal" or "external", I don't think it will entirely solve the confusion about combining the two patterns.

Considering your reputation Steve, I am convinced

Nobody has a reputation that means their word should be unimpeachable - so use your own experience to make the final decision. In this case, you should feel in your bones that the combination of internal and external modules is creating uncomfortable code without adding any benefit; but I could be wrong.