Babili minifies but does not transpile - javascript

I am stuck with babili.
I need to transpile, then minify the javascript that is written in ES6. So I installed the package using:
npm install babili --save-dev
and made .babelrc file containing a preset:
{"presets": ["es2015"]}
Now I tried the following command
./node_modules/.bin/babili public/js/rt.socket.js --out-file public/test.min.js
It does give a minified but doesn't transpile. What could be the reason for this?
`

Babili does not use .babelrc. Per the README:
Note that, because the babili command uses the default preset with no-babelrc, you cannot set any non-default options in the preset's plugins with this command. To do this, you can use the babel command with the options set in a .babelrc. See the preset docs for more information on how to do this.
The solution is to instead use Babel with the babel-preset-babili preset, as described in the Babel preset section of the README (which assumes that you've already installed Babel):
Install
npm install babel-preset-babili --save-dev
Usage
You'll most likely want to use it only in the production environment.
Check out the env
docs for more help.
Options specific to a certain environment are merged into and overwrite non-env specific options.
.babelrc:
{
"presets": ["es2015"],
"env": {
"production": {
"presets": ["babili"]
}
}
}
Then you'll need to set the env variable which could be something like
BABEL_ENV=production npm run build

Related

Why is ESLint complaining about a syntax error when I can run my code fine in Node? "Parsing error: Unexpected token =" [duplicate]

ESLint is throwing a Parsing error: Unexpected token = error when I try to lint my Es6 classes. What configuration parameter am I missing to enable fat arrow class methods in eslint?
Sample class:
class App extends React.Component{
...
handleClick = (evt) => {
...
}
}
.eslint
{
"ecmaFeatures": {
"jsx": true,
"modules":true,
"arrowFunctions":true,
"classes":true,
"spread":true,
},
"env": {
"browser": true,
"node": true,
"es6": true
},
"rules": {
"strict": 0,
"no-underscore-dangle": 0,
"quotes": [
2,
"single"
],
}
}
If you want to use experimental features (such as arrows as class methods) you need to use babel-eslint as a parser. Default parser (Espree) doesn't support experimental features.
First install babel-eslint:
npm i -D babel-eslint
Then add the following to your .eslintrc.json file:
"parser": "babel-eslint"
First install these plugins:
npm i -D babel-eslint eslint-plugin-babel
Then add these settings to your ESLint config file:
{
"plugins": [ "babel" ],
"parser": "babel-eslint",
"rules": {
"no-invalid-this": 0,
"babel/no-invalid-this": 1,
}
}
This way you can use fat arrow class methods plus you will not get any no-invalid-this errors from ESLint.
From what I read in the error message Parsing error: Unexpected token = it looks like more a parser error than linter one.
Assuming you are using Babel as your JavaScript compiler/transpiler and babel-eslint as your ESLint parser, chances are that it is Babel complaining about the syntax, not ESLint.
The issue is not about the arrow functions but something more experimental (ES7??) that I think it is called property initializer or class instance field (or both :) ).
If you want to use this new syntax/feature you need to enable preset-stage-1 in Babel. This preset includes the syntax-class-properties plugin that allows that syntax.
Summing up:
Install babel preset:
npm install babel-preset-stage-1
Add this preset to the list of your presets (I suppose you are already using es2015 and react presets), either in your .babelrc or in your babel-loader query field if you are using webpack.
"presets": ["es2015", "stage-1", "react"]
I came across the same problem today
and #dreyescat 's answer works for me.
By default, babel uses 3 presets: es2015, react, stage-2
Screenshot with "Parsing error: Unexpected token ="
Then if you also select the stage-1preset, the error is gone
Screenshot with no error
You can test it on the bebeljs.io site yourself
2021 Update: Be sure you're using #babel/eslint-parser and not the deprecated babel-eslint
Remove the old package if necessary: yarn remove babel-eslint or npm uninstall babel-eslint
yarn add --dev #babel/eslint-parser or npm install --save-dev #babel/eslint-parser
In .eslintrc add "parser": "#babel/eslint-parser"
Optionally, this answer suggests including "requireConfigFile": false in .eslintrc to prevent eslint from searching for unnecessary config files:
{
...
"parserOptions": {
...
"requireConfigFile": false,
}
}
If this still doesn't work, try checking whether your system is using a globally installed eslint (and removing it).
My other problem was eslint was using a globally installed version instead of my local version, and the global eslint can't access my locally installed babel-eslint parser. Further, since my globally installed eslint was installed on a different version of node, removing it was non-trivial.
Checking if your system is using global versus local eslint.
Install babel-eslint following #spencer.sm's answer for your local eslint.
From the terminal, check if you get different output from running eslint . and npx eslint .. If you get different output it's likely that it's your global eslint running that can't access babel-eslint.
Uninstalling the global eslint
For most people, the following commands should uninstall eslint with npm (uninstall global package with npm) and yarn (uninstall global package with yarn):
# npm
npm uninstall -g eslint
npm uninstall eslint
# yarn
yarn global remove eslint
Next, run npx eslint . to see if things work. If it doesn't, which it didn't for me, you need to take an extra step to remove the globally installed eslint.
From this answer, I learned that I had installed eslint on a system version of Node instead of my current version of Node (I use nvm). Follow these simple steps to remove the global eslint and you should be good to go!
Your sample isn't valid ES6, so there's no way to configure eslint to allow it

Babel-CLI set config value correctly

I am trying to add a build command that uses babel CLI to transpile my ES6. I am having difficult pointing it correctly to babelrc.
The file structure is roughly as follows:
root
src
index.js
...
.babelrc
.package.json
In my package.json, I originally tried the following:
"scripts": {
"build": "babel --out-dir dist src",
...
},
But this gave an error because of the array destructuring notation I have used in my code. I think this is because it is not picking up my .babelrc file. Using
babel --presets=#babel/preset-env --out-dir dist src
instead fixes this problem. But I would rather I didn't have to specify plugins etc. here and rely on the .babelrc file instead.
From reading this issue, I get the impression babel looks for a config file in src rather than root . Looking at the documentation it seems there is an option for specifying a config file, but I can't quite get it to work correctly. My attempt:
babel --config-file .babelrc --out-dir dist src
You can use ./node_modules/.bin/babel in place of babel.
Worked for me this week.
Check point 3 in the overview from babel-cli
https://babeljs.io/docs/en/usage
And running this command to compile all your code from the src directory to lib:
./node_modules/.bin/babel src --out-dir lib
You can use the npm package runner that comes with npm#5.2.0 to shorten that command by replacing ./node_modules/.bin/babel with npx babel
For Babel version 7.x, it looks for project-wide configuration in the file with name like this - babel.config.{json|js|cjs|mjs}. Check the documentation here.
In my end,
npx babel src/ -d lib/
Babel should already pick up the .babelrc file automatically. If you want to add that preset, you should specify
{
// ... more .babelrc up here
"presets": ["#babel/preset-env"]
// ... more .babelrc down here
}
in your .babelrc file.
But babel will automatically search for the closest .babelrc file in the directory starting at the entry file and working its way upwards (specified here at the bottom).

Where should I insert '#babel/polyfill' into?: main.js or each modules [duplicate]

I just started to use Babel to compile my ES6 javascript code into ES5. When I start to use Promises it looks like it's not working. The Babel website states support for promises via polyfills.
Without any luck, I tried to add:
require("babel/polyfill");
or
import * as p from "babel/polyfill";
With that I'll get the following error on my app bootstrapping:
Cannot find module 'babel/polyfill'
I searched for the module but it seems I'm missing some fundamental thing here. I also tried to add the old and good bluebird NPM but it looks like it's not working.
How to use the polyfills from Babel?
This changed a bit in babel v6.
From the docs:
The polyfill will emulate a full ES6 environment. This polyfill is automatically loaded when using babel-node.
Installation:
$ npm install babel-polyfill
Usage in Node / Browserify / Webpack:
To include the polyfill you need to require it at the top of the entry point to your application.
require("babel-polyfill");
Usage in Browser:
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.
NOTE: Do not require this via browserify etc, use babel-polyfill.
The Babel docs describe this pretty concisely:
Babel includes a polyfill that includes a custom regenerator runtime
and core.js.
This will emulate a full ES6 environment. This polyfill is
automatically loaded when using babel-node and babel/register.
Make sure you require it at the entry-point to your application, before anything else is called. If you're using a tool like webpack, that becomes pretty simple (you can tell webpack to include it in the bundle).
If you're using a tool like gulp-babel or babel-loader, you need to also install the babel package itself to use the polyfill.
Also note that for modules that affect the global scope (polyfills and the like), you can use a terse import to avoid having unused variables in your module:
import 'babel/polyfill';
For Babel version 7, if your are using #babel/preset-env, to include polyfill all you have to do is add a flag 'useBuiltIns' with the value of 'usage' in your babel configuration. There is no need to require or import polyfill at the entry point of your App.
With this flag specified, babel#7 will optimize and only include the polyfills you needs.
To use this flag, after installation:
npm install --save-dev #babel/core #babel/cli #babel/preset-env
npm install --save #babel/polyfill
Simply add the flag:
useBuiltIns: "usage"
to your babel configuration file called "babel.config.js" (also new to Babel#7), under the "#babel/env" section:
// file: babel.config.js
module.exports = () => {
const presets = [
[
"#babel/env",
{
targets: { /* your targeted browser */ },
useBuiltIns: "usage" // <-----------------*** add this
}
]
];
return { presets };
};
Reference:
usage#polyfill
babel-polyfill#usage-in-node-browserify-webpack
babel-preset-env#usebuiltins
Update Aug 2019:
With the release of Babel 7.4.0 (March 19, 2019) #babel/polyfill is deprecated. Instead of installing #babe/polyfill, you will install core-js:
npm install --save core-js#3
A new entry corejs is added to your babel.config.js
// file: babel.config.js
module.exports = () => {
const presets = [
[
"#babel/env",
{
targets: { /* your targeted browser */ },
useBuiltIns: "usage",
corejs: 3 // <----- specify version of corejs used
}
]
];
return { presets };
};
see example: https://github.com/ApolloTang/stackoverflow-eg--babel-v7.4.0-polyfill-w-core-v3
Reference:
7.4.0 Released: core-js 3, static private methods and partial
application
core-js#3, babel and a look into the future
If your package.json looks something like the following:
...
"devDependencies": {
"babel": "^6.5.2",
"babel-eslint": "^6.0.4",
"babel-polyfill": "^6.8.0",
"babel-preset-es2015": "^6.6.0",
"babelify": "^7.3.0",
...
And you get the Cannot find module 'babel/polyfill' error message, then you probably just need to change your import statement FROM:
import "babel/polyfill";
TO:
import "babel-polyfill";
And make sure it comes before any other import statement (not necessarily at the entry point of your application).
Reference: https://babeljs.io/docs/usage/polyfill/
First off, the obvious answer that no one has provided, you need to install Babel into your application:
npm install babel --save
(or babel-core if you instead want to require('babel-core/polyfill')).
Aside from that, I have a grunt task to transpile my es6 and jsx as a build step (i.e. I don't want to use babel/register, which is why I am trying to use babel/polyfill directly in the first place), so I'd like to put more emphasis on this part of #ssube's answer:
Make sure you require it at the entry-point to your application,
before anything else is called
I ran into some weird issue where I was trying to require babel/polyfill from some shared environment startup file and I got the error the user referenced - I think it might have had something to do with how babel orders imports versus requires but I'm unable to reproduce now. Anyway, moving import 'babel/polyfill' as the first line in both my client and server startup scripts fixed the problem.
Note that if you instead want to use require('babel/polyfill') I would make sure all your other module loader statements are also requires and not use imports - avoid mixing the two. In other words, if you have any import statements in your startup script, make import babel/polyfill the first line in your script rather than require('babel/polyfill').
babel-polyfill allows you to use the full set of ES6 features beyond
syntax changes. This includes features such as new built-in objects
like Promises and WeakMap, as well as new static methods like
Array.from or Object.assign.
Without babel-polyfill, babel only allows you to use features like
arrow functions, destructuring, default arguments, and other
syntax-specific features introduced in ES6.
https://www.quora.com/What-does-babel-polyfill-do
https://hackernoon.com/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423
Like Babel says in the docs, for Babel > 7.4.0 the module #babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in #babel/polyfill.
So this worked for me:
npm install --save core-js#3.6.5
npm install regenerator-runtime
then add to the very top of your initial js file:
import 'core-js/stable';
import 'regenerator-runtime/runtime';

How can I run gulp with a typescript file

Have a gulp project that uses a gulp.js file but my project is in typescript so I'd rather have a gulp file in typescript. It would be possible to break the process into two steps where I:
1. Manually transpile the typescript gulp file into js, then
2. Call gulp <some-task-name>
But that doesn't seem optimal. Is there any better way of doing
this?
From Gulp docs for transpilation:
Transpilation
You can write a gulpfile using a language that requires transpilation, like TypeScript or Babel, by changing the extension on your gulpfile.js to indicate the language and install the matching transpiler module.
For TypeScript, rename to gulpfile.ts and install the ts-node module.
For Babel, rename to gulpfile.babel.js and install the #babel/register module.
So the simpler way to add TypeScript support in Gulp:
Install ts-node, typescript, and #types/gulp:
$ npm i -D ts-node typescript #types/gulp
If you have a tsconfig.json file set ts-node.compilerOptions.module to "commonjs"
{
// these options are overrides used only by ts-node
"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
}
}
(You don't need a tsconfig.json file, this is just for if you have one in your project already)
Create gulpfile.ts with the following demo code:
import gulp from 'gulp'; // or import * as gulp from 'gulp'
gulp.task('default', () => console.log('default'));
(or rename your existing Gulpfile.js to gulpfile.ts)
Start the build:
$ npx gulp
The output should look similar to this:
$ gulp
[21:55:03] Requiring external module ts-node/register
[21:55:03] Using gulpfile ~/src/tmp/typescript-tmp/gulpfile.ts
[21:55:03] Starting 'default'...
default
[21:55:03] Finished 'default' after 122 μs
In case anyone else runs into this, #tony19's answer above will only work for some projects ;-)
import * as gulp from 'gulp'; won't always work (it depends on your tsconfig.json settings- specifically allowSyntheticDefaultImports), the "safer" thing to use is import gulp from 'gulp'; which should work regardless of the allowSyntheticDefaultImports value.
Set up a gulp.js file in the root of your project with nothing but the following line.
eval(require('typescript').transpile(require('fs').readFileSync("./gulp.ts").toString()));
Then create another actual gulp file written in typescript in a file gulp.ts. What will happen is that the gulp.js file will be loaded but will bootstrap the process by compiling your `gulp.ts' file and passing the transpiled results instead.
This allows us to not have to precompile the gulp.ts file before using it. Instead you can just type gulp test and it will be executed from your tyepscript file without any extra calls.
Make sure to run the following first:
npm install typescript --save-dev
npm install fs --save-dev

How to publish a module written in ES6 to NPM?

I was about to publish a module to NPM, when I thought about rewriting it in ES6, to both future-proof it, and learn ES6. I've used Babel to transpile to ES5, and run tests. But I'm not sure how to proceed:
Do I transpile, and publish the resulting /out folder to NPM?
Do I include the result folder in my Github repo?
Or do I maintain 2 repos, one with the ES6 code + gulp script for Github, and one with the transpiled results + tests for NPM?
In short: what steps do I need to take to publish a module written in ES6 to NPM, while still allowing people to browse/fork the original code?
The pattern I have seen so far is to keep the es6 files in a src directory and build your stuff in npm's prepublish to the lib directory.
You will need an .npmignore file, similar to .gitignore but ignoring src instead of lib.
I like José's answer. I've noticed several modules follow that pattern already. Here's how you can easily implement it with Babel6. I install babel-cli locally so the build doesn't break if I ever change my global babel version.
.npmignore
/src/
.gitignore
/lib/
/node_modules/
Install Babel
npm install --save-dev babel-core babel-cli babel-preset-es2015
package.json
{
"main": "lib/index.js",
"scripts": {
"prepublish": "babel src --out-dir lib"
},
"babel": {
"presets": ["es2015"]
}
}
TL;DR - Don't, until ~October 2019. The Node.js Modules Team has asked:
Please do not publish any ES module packages intended for use by Node.js until [October 2019]
2019 May update
Since 2015 when this question was asked, JavaScript support for modules has matured significantly, and is hopefully going to be officially stable in October 2019. All other answers are now obsolete or overly complicated. Here is the current situation and best practice.
ES6 support
99% of ES6 (aka 2015) has been supported by Node since version 6. The current version of Node is 12. All evergreen browsers support the vast majority of ES6 features. ECMAScript is now at version 2019, and the versioning scheme now favors using years.
ES Modules (aka ECMAScript modules) in browsers
All evergreen browsers have been supporting import-ing ES6 modules since 2017. Dynamic imports are supported by Chrome (+ forks like Opera and Samsung Internet) and Safari. Firefox support is slated for the next version, 67.
You no longer need Webpack/rollup/Parcel etc. to load modules. They may be still useful for other purposes, but are not required to load your code. You can directly import URLs pointing to ES modules code.
ES modules in Node
ES modules (.mjs files with import/export) have been supported since Node v8.5.0 by calling node with the --experimental-modules flag. Node v12, released in April 2019, rewrote the experimental modules support. The most visible change is that the file extension needs to be specified by default when importing:
// lib.mjs
export const hello = 'Hello world!';
// index.mjs:
import { hello } from './lib.mjs';
console.log(hello);
Note the mandatory .mjs extensions throughout. Run as:
node --experimental-modules index.mjs
The Node 12 release is also when the Modules Team asked developers to not publish ES module packages intended for use by Node.js until a solution is found for using packages via both require('pkg') and import 'pkg'. You can still publish native ES modules intended for browsers.
Ecosystem support of native ES modules
As of May 2019, ecosystem support for ES Modules is immature. For example, test frameworks like Jest and Ava don't support --experimental-modules. You need to use a transpiler, and must then decide between using the named import (import { symbol }) syntax (which won't work with most npm packages yet), and the default import syntax (import Package from 'package'), which does work, but not when Babel parses it for packages authored in TypeScript (graphql-tools, node-influx, faast etc.) There is however a workaround that works both with --experimental-modules and if Babel transpiles your code so you can test it with Jest/Ava/Mocha etc:
import * as ApolloServerM from 'apollo-server'; const ApolloServer = ApolloServerM.default || ApolloServerM;
Arguably ugly, but this way you can write your own ES modules code with import/export and run it with node --experimental-modules, without transpilers. If you have dependencies that aren't ESM-ready yet, import them as above, and you'll be able to use test frameworks and other tooling via Babel.
Previous answer to the question - remember, don't do this until Node solves the require/import issue, hopefully around October 2019.
Publishing ES6 modules to npm, with backwards compatibility
To publish an ES module to npmjs.org so that it can be imported directly, without Babel or other transpilers, simply point the main field in your package.json to the .mjs file, but omit the extension:
{
"name": "mjs-example",
"main": "index"
}
That's the only change. By omitting the extension, Node will look first for an mjs file if run with --experimental-modules. Otherwise it will fall back to the .js file, so your existing transpilation process to support older Node versions will work as before — just make sure to point Babel to the .mjs file(s).
Here's the source for a native ES module with backwards compatibility for Node < 8.5.0 that I published to NPM. You can use it right now, without Babel or anything else.
Install the module:
npm install local-iso-dt
# or, yarn add local-iso-dt
Create a test file test.mjs:
import { localISOdt } from 'local-iso-dt/index.mjs';
console.log(localISOdt(), 'Starting job...');
Run node (v8.5.0+) with the --experimental-modules flag:
node --experimental-modules test.mjs
TypeScript
If you develop in TypeScript, you can generate ES6 code and use ES6 modules:
tsc index.js --target es6 --modules es2015
Then, you need to rename *.js output to .mjs, a known issue that will hopefully get fixed soon so tsc can output .mjs files directly.
#Jose is right. There's nothing wrong with publishing ES6/ES2015 to NPM but that may cause trouble, specially if the person using your package is using Webpack, for instance, because normally people ignore the node_modules folder while preprocessing with babel for performance reasons.
So, just use gulp, grunt or simply Node.js to build a lib folder that is ES5.
Here's my build-lib.js script, which I keep in ./tools/ (no gulpor grunt here):
var rimraf = require('rimraf-promise');
var colors = require('colors');
var exec = require('child-process-promise').exec;
console.log('building lib'.green);
rimraf('./lib')
.then(function (error) {
let babelCli = 'babel --optional es7.objectRestSpread ./src --out-dir ./lib';
return exec(babelCli).fail(function (error) {
console.log(colors.red(error))
});
}).then(() => console.log('lib built'.green));
Here's a last advice: You need to add a .npmignore to your project. If npm publish doesn't find this file, it will use .gitignore instead, which will cause you trouble because normally your .gitignore file will exclude ./lib and include ./src, which is exactly the opposite of what you want when you are publishing to NPM. The .npmignore file has basically the same syntax of .gitignore (AFAIK).
Following José and Marius's approach, (with update of Babel's latest version in 2019): Keep the latest JavaScript files in a src directory, and build with npm's prepublish script and output to the lib directory.
.npmignore
/src
.gitignore
/lib
/node_modules
Install Babel (version 7.5.5 in my case)
$ npm install #babel/core #babel/cli #babel/preset-env --save-dev
package.json
{
"name": "latest-js-to-npm",
"version": "1.0.0",
"description": "Keep the latest JavaScript files in a src directory and build with npm's prepublish script and output to the lib directory.",
"main": "lib/index.js",
"scripts": {
"prepublish": "babel src -d lib"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.5.5",
"#babel/core": "^7.5.5",
"#babel/preset-env": "^7.5.5"
},
"babel": {
"presets": [
"#babel/preset-env"
]
}
}
And I have src/index.js which uses the arrow function:
"use strict";
let NewOneWithParameters = (a, b) => {
console.log(a + b); // 30
};
NewOneWithParameters(10, 20);
Here is the repo on GitHub.
Now you can publish the package:
$ npm publish
...
> latest-js-to-npm#1.0.0 prepublish .
> babel src -d lib
Successfully compiled 1 file with Babel.
...
Before the package is published to npm, you will see that lib/index.js has been generated, which is transpiled to es5:
"use strict";
var NewOneWithParameters = function NewOneWithParameters(a, b) {
console.log(a + b); // 30
};
NewOneWithParameters(10, 20);
[Update for Rollup bundler]
As asked by #kyw, how would you integrate Rollup bundler?
First, install rollup and rollup-plugin-babel
npm install -D rollup rollup-plugin-babel
Second, create rollup.config.js in the project root directory
import babel from "rollup-plugin-babel";
export default {
input: "./src/index.js",
output: {
file: "./lib/index.js",
format: "cjs",
name: "bundle"
},
plugins: [
babel({
exclude: "node_modules/**"
})
]
};
Lastly, update prepublish in package.json
{
...
"scripts": {
"prepublish": "rollup -c"
},
...
}
Now you can run npm publish, and before the package is published to npm, you will see that lib/index.js has been generated, which is transpiled to es5:
'use strict';
var NewOneWithParameters = function NewOneWithParameters(a, b) {
console.log(a + b); // 30
};
NewOneWithParameters(10, 20);
Note: by the way, you no longer need #babel/cli if you are using the Rollup bundler. You can safely uninstall it:
npm uninstall #babel/cli
If you want to see this in action in a very simple small open source Node module then take a look at nth-day (which I started - also other contributors). Look in the package.json file and at the prepublish step which will lead you to where and how to do this. If you clone that module you can run it locally and use it as a template for yous.
Node.js 13.2.0+ supports ESM without the experimental flag and there're a few options to publish hybrid (ESM and CommonJS) NPM packages (depending on the level of backward compatibility needed): https://2ality.com/2019/10/hybrid-npm-packages.html
I recommend going the full backward compatibility way to make the usage of your package easier. This could look as follows:
The hybrid package has the following files:
mypkg/
package.json
esm/
entry.js
commonjs/
package.json
entry.js
mypkg/package.json
{
"type": "module",
"main": "./commonjs/entry.js",
"exports": {
"./esm": "./esm/entry.js"
},
"module": "./esm/entry.js",
···
}
mypkg/commonjs/package.json
{
"type": "commonjs"
}
Importing from CommonJS:
const {x} = require('mypkg');
Importing from ESM:
import {x} from 'mypkg/esm';
We did an investigation into ESM support in 05.2019 and found that a lot of libraries were lacking support (hence the recommendation for backward compatibility):
esm package's support doesn't align with Node's which causes issues
"Builtin require cannot sideload .mjs files." https://github.com/standard-things/esm#loading, https://github.com/standard-things/esm/issues/498#issuecomment-403496745
"The .mjs file extension should not be the thing developers reach for if they want interop or ease of use. It's available since it's in --experimental-modules but since it's not fully baked I can't commit to any enhancements to it." https://github.com/standard-things/esm/issues/498#issuecomment-403655466
mocha doesn't have native support for .mjs files
Update 2020-01-13: Mocha released experimental support in mocha#7.0.0-esm1
Many high-profile projects had issues with .mjs files:
create-react-app
react-apollo
graphql-js
inferno
The main key in package.json decides the entry point to the package once it's published. So you can put your Babel's output wherever you want and just have to mention the right path in main key.
"main": "./lib/index.js",
Here's a well written article on how to publish an npm package
https://codeburst.io/publish-your-own-npm-package-ff918698d450
Here's a sample repo you can use for reference
https://github.com/flexdinesh/npm-module-boilerplate
The two criteria of an NPM package is that it is usable with nothing more than a require( 'package' ) and does something software-ish.
If you fulfill those two requirements, you can do whatever you wish.
Even if the module is written in ES6, if the end user doesn't need to know that, I would transpile it for now to get maximum support.
However, if like koa, your module requires compatibility with users using ES6 features, then perhaps the two package solution would be a better idea.
Takeaway
Only publish as much code as you need to make require( 'your-package' ) work.
Unless the between ES5 & 6 matters to the user, only publish 1 package. Transpile it if you must.
A few extra notes for anyone, using own modules directly from github, not going through published modules:
The (widely used) "prepublish" hook is not doing anything for you.
Best thing one can do (if plans to rely on github repos, not published stuff):
unlist src from .npmignore (in other words: allow it). If you don't have an .npmignore, remember: A copy of .gitignore will be used instead in the installed location, as ls node_modules/yourProject will show you.
make sure, babel-cli is a depenency in your module, not just a devDepenceny since you are indeed building on the consuming machine aka at the App developers computer, who is using your module
do the build thing, in the install hook i.e.:
"install": "babel src -d lib -s"
(no added value in trying anything "preinstall", i.e. babel-cli might be missing)
Deppending on the anatomy of your module, this solution may not work, but if your module is contained inside a single file, and has no dependencies (does not make use of import), using the following pattern you can release your code as it is, and will be able to be imported with import (Browser ES6 Modules) and require (Node CommonJS Modules)
As a bonus, it will be suittable to be imported using a SCRIPT HTML Element.
main.js :
(function(){
'use strict';
const myModule = {
helloWorld : function(){ console.log('Hello World!' )}
};
// if running in NODE export module using NODEJS syntax
if(typeof module !== 'undefined') module.exports = myModule ;
// if running in Browser, set as a global variable.
else window.myModule = myModule ;
})()
my-module.js :
// import main.js (it will declare your Object in the global scope)
import './main.js';
// get a copy of your module object reference
let _myModule = window.myModule;
// delete the the reference from the global object
delete window.myModule;
// export it!
export {_myModule as myModule};
package.json :`
{
"name" : "my-module", // set module name
"main": "main.js", // set entry point
/* ...other package.json stuff here */
}
To use your module, you can now use the regular syntax ...
When imported in NODE ...
let myModule = require('my-module');
myModule.helloWorld();
// outputs 'Hello World!'
When imported in BROWSER ...
import {myModule} from './my-module.js';
myModule.helloWorld();
// outputs 'Hello World!'
Or even when included using an HTML Script Element...
<script src="./main.js"></script>
<script>
myModule.helloWorld();
// outputs 'Hello World!'
</script>

Categories