Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Browserify to transform dependencies?

I'm working on two Node packages at once, let's call them Library and Consumer. Library is responsible for rendering a bunch of stuff in the browser. All Consumer does is import Library from 'library' and call Library(someConfigHere) -- it's basically just a test to make sure Library is doing what I expect in the browser.

I've npm linked Library into Consumer and am trying to run Browserify on Consumer, but I get this error: ParseError: 'import' and 'export' may appear only with 'sourceType: module'. Library does indeed contain an ES6 export statement, so I'm guessing that Browserify is only running against Consumer and not Library.

So my question is: is there any way to force Browserify to transform dependencies as well?

This is my package.json:

{
  "name": "consumer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "budo index.js --port $PORT",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-preset-es2015": "^6.13.2",
    "babel-preset-react": "^6.11.1",
    "babelify": "^7.3.0",
    "browserify-shim": "^3.8.12"
  },
  "browserify": {
    "transform": [
      "babelify"
    ]
  },
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  }
}

This is Consumer's index.js:

import Library from 'library'  // <= this is what isn't getting babelified

console.log(Library);

This is Library's index.js:

export default (config) => {
    console.log('Testing testing')
}
like image 285
serverpunk Avatar asked Dec 12 '16 19:12

serverpunk


1 Answers

Browserify transforms can be configured to be global, which means they will be applied to files within node_modules, too.

The configuration is per-transform. With babelify, you'd configure it like this:

browserify().transform("babelify", {
  global: true
})

Or, if you are using the command line, like this:

browserify ... -t [ babelify --global ] ...

Or, to configure it in the package.json, it should be something like this (note the added square brackets):

"browserify": {
  "transform": [
    ["babelify", { "global": true }]
  ]
}

Babelify also implements an ignore option, so it would be possible to configure it to transform only the files within node_modules that you want it to. There is more information here.

Another solution would be to include a similar browserify/babelify configuration in your library module's package.json. When processing dependencies, Browserify will check said dependency's pacakge.json files for transforms and will apply any that are configured.

like image 139
cartant Avatar answered Sep 20 '22 06:09

cartant