Qiulang
Qiulang

Reputation: 12395

Publish a node module written in ES6 without providing the transpiled ES5 version b/c it is targeted for the latest browser

My team will publish a node module written in ES6, targeted for the latest browsers. All the ES6 features we use, like async/await, import/export are supported by our target browsers. So I believe providing the transpiled ES5 version does not make sense (Our targeted audiences assure us they will only use the latest Chrome).

But I found without the transpiled ES5 version when they use our module, they got SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' even though their gulpfile already set

return browserify({ ... })
  .transform(babelify.configure({
    presets: ["es2015"]
  }))
  ...

If they just include our module source codes in their own codes they can import my module without any error. That makes me believe there should be some setting in my module so I can just provide ES6 version only.

BTW, I have read How to publish a module written in ES6 to NPM? and SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' - Wait what?

They were not my question and the answers there didn't fix the SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' my clients got.

Upvotes: 1

Views: 673

Answers (1)

Qiulang
Qiulang

Reputation: 12395

I spent a whole day solving it so I would like to share my experience.

First of all, it is browserify's parser that complained SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' so what I need to do is to let the client's browserify transform my module and the solution turned to be quite simple!

Why aren't files in node_modules being transformed?

A possible solution is to add:

{ "browserify": { "transform": ["babelify"] } } to the root of all your modules package.json that you want to be transformed.

So adding "browserify": { "transform": [ "babelify" ] } to my module's package.json and the the problem is solved!

It is easy to verify that, e.g. in my module's .babelrc I particularly set "modules":false (b/c defaults to "commonjs")

{ "presets": [[
  "env",
  {
    "modules":false,
    "debug": true
  }
]]}

Then I got SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' again!

PS,

I got more than one comments/answers said <script type="module". Of course I knew script has type="module" but that is the wrong answer!

Because we are talking using node module in browser environment, type="module" can't solve the problem of import module from node_modules

Upvotes: 1

Related Questions