javascript - How to compile npm package from src (source) for both lib (module) and dist (browser)? -
i'm writing small class object in javascript wish able use both node applications standalone browser javascript file.
i think i've found solution, i'm not sure if that's how it's supposed be.
let me try explain how directory looks.
ok, i've got main file inside directory called src/index.js. file consists of simple es6 class, export es6 export (following airbnb use import/export).
export default person class { constructor() { // code here... } getexamplemethod() { // code here... } }
okay. code not run in browser because browsers not support "export default" , it's es6 should transpile es5 using babel.
but using babel --presets=es2015 not cut out "export default" browsers still throw error. solved using package called "replace" search , replaces string before transpiling using babel.
in package.json looks this:
"build:dist": "babel src -d dist --no-babelrc && replace 'export default ' '' dist/index.js && babel dist -d dist --presets=es2015",
so first moving file, removing "export default " line, , transpiling it... , works!
for lib directory this:
"build:lib": "babel src -d lib --plugins=add-module-exports,transform-es2015-modules-commonjs",
so move file , transpile it, adding "module exports" , "commonjs" module.
this works... not feel way it? i've tried using browserify, webpack etc, when doing that, not seem able initiate new object class? gives me error message saying "new person()" not defined or similar this.
how suppose write source code in plain es6 style, transpiling both used in browser , node usage, while being able have api looks this: "var person = new person();"?
really, question maybe more aimed be: how turn src/index.js both browser , node compatible files?
thanks lot!
Comments
Post a Comment