choojs / nanohtml

:dragon: HTML template strings for the Browser with support for Server Side Rendering in Node.
MIT License
686 stars 49 forks source link

Browserify transform does not work for code transpiled from Typescript #152

Closed hugueschabot closed 5 years ago

hugueschabot commented 5 years ago

The code produced by Typescript transpiler with esModuleInterop is not processed correctly by nanohtml browserify transform. esModuleInterop is required when migrating from Javascript to Typescript.

How to reproduce

Create a Typescript file, test.ts

import html from 'nanohtml'

module.exports = function (data) {
  const className = 'test'

  return html`<div class="${className}">
      <h1>${data}</h1>
      <div is="my-div"></div>
    </div>`
}

Create the tsconfig.json file.

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2015",
    "esModuleInterop": true
  }
}

Browserify the test.ts with tsifyand nanohtml.

browserify --plugin tsify --transform nanohtml test.ts

In the result, the nanohtml require is removed, as expected but the string template is not processed.

...

const nanohtml_1 = __importDefault({});
module.exports = function (data) {
    const className = 'test';
    return nanohtml_1.default `<div class="${className}">
      <h1>${data}</h1>
      <div is="my-div"></div>
    </div>`;
};

...

The expected result would look like this.

...

const nanohtml_1 = __importDefault({});
module.exports = function (data) {
    const className = 'test';
    return (function () {
      var ac = require('/home/hugues/projects/nanohtml-typescript-test/node_modules/nanohtml/lib/append-child.js')
      var nanohtml2 = document.createElement("div")
nanohtml2.setAttribute("class", arguments[1])
var nanohtml0 = document.createElement("h1")
ac(nanohtml0, [arguments[0]])
var nanohtml1 = document.createElement("div", { is: "my-div" })
ac(nanohtml2, ["\n      ",nanohtml0,"\n      ",nanohtml1,"\n    "])
      return nanohtml2
    }(data,className));
};

...
fgblomqvist commented 2 years ago

This seems to be broken again (or maybe the fix didn't cover all cases). I know this project isn't active anymore but posting this for anyone else that's wondering what's up. The behavior I'm seeing is essentially the exact same as the one described here. The only workaround seems to be to just keep using require when importing nanohtml rather than using the ESM import syntax.