How to generate single ES5 bundle file from ES6 project using browserify - javascript

I am trying to use react-vis library in my project. In their readme file, they have asked to import library by adding following lines in non-node environment:
If you're working in a non-node environment, you can also directly include the bundle and compiled style using basic html tags.
<link rel="stylesheet" href="https://unpkg.com/react-vis/dist/style.css">
<script type="text/javascript" src="https://unpkg.com/react-vis/dist/dist.min.js"></script>
The global reactVis object will now be available for you to play around.
When I did that, I got following error:
Uncaught TypeError: Cannot call a class as a function
at _classCallCheck (dist.min.js:formatted:23789:27)
at LabelSeries (dist.min.js:formatted:23823:21)
at Constructor.render (<anonymous>:1866:23)
at Constructor.<anonymous> (react.js:6029:34)
at Constructor._renderValidatedComponent (react.js:11403:21)
at Constructor.<anonymous> (react.js:5582:14)
at Constructor.mountComponent (react.js:11403:21)
at Constructor.mountChildren (react.js:10913:42)
at Constructor._createContentMarkup (react.js:6812:32)
at Constructor.<anonymous> (react.js:6734:14)
After a lot of digging, I realised issue was that the react-vis library follows ES6, while my project is in ES5. So, I thought to transpile react-vis library to ES5. After digging a bit in the react-vis repo, I found that it uses browserify.
So to compile ES6 porject to single ES5 bundle file using browserify itself, I added --presets [ #babel/preset-env ] on this line itself as suggested here:
"build:browser": "browserify src/index.js -t [ babelify --presets [ #babel/preset-env ] ] --standalone reactVis | uglifyjs > dist/dist.min.js",
I also tried adding #babel/preset-react:
"build:browser": "browserify src/index.js -t [ babelify --presets [ #babel/preset-env #babel/preset-react] --rootMode upward ] --standalone reactVis | uglifyjs > dist/dist.min.js",
But in both cases I ended up getting same error: Cannot call a class as a function.
What I am missing?

Related

How to generate single ES5 bundle file from ES6 project using webpack?

I am trying to use react-vis library in my project. In their readme file, they have asked to import library by adding following lines in non-node environment:
If you're working in a non-node environment, you can also directly include the bundle and compiled style using basic html tags.
<link rel="stylesheet" href="https://unpkg.com/react-vis/dist/style.css">
<script type="text/javascript" src="https://unpkg.com/react-vis/dist/dist.min.js"></script>
The global reactVis object will now be available for you to play around.
When I did that, I got following error:
Uncaught TypeError: Cannot call a class as a function
at _classCallCheck (dist.min.js:formatted:23789:27)
at LabelSeries (dist.min.js:formatted:23823:21)
at Constructor.render (<anonymous>:1866:23)
at Constructor.<anonymous> (react.js:6029:34)
at Constructor._renderValidatedComponent (react.js:11403:21)
at Constructor.<anonymous> (react.js:5582:14)
at Constructor.mountComponent (react.js:11403:21)
at Constructor.mountChildren (react.js:10913:42)
at Constructor._createContentMarkup (react.js:6812:32)
at Constructor.<anonymous> (react.js:6734:14)
After a lot of digging, I realised the issue was that the react-vis library follows ES6, while my project is in ES5. So, I thought to transpile react-vis library to ES5. I used babel as explained in this post to transpile ES6 to ES5 (with slight changes). But, it generated multiple files. I needed single bundle file.
So, I followed steps explained here to generate single ES5 bundle file. I used same webpack.config.js as specified in these steps. And my scripts in package.json look something like this:
"build:babel": "babel src -d build"
"build:app": "npm run build:babel",
"build:bundle": "webpack --mode production",
"build3": "npm run build:app && npm run build:bundle"
It was successful, but when I used generated bundle file, I got error ReferenceError: reactVis. When I checked the generated bundle file, it did not contain reactVis variable. So, now I have two doubts:
Q1. how can I tell webpack to preserve reactVis variable?
Q2. how can I make webpack to add it to global scope (or how can I access this variable in my project once I linked the generated bundle)?

Use Babelify with Browserify Globally / Global in WebStorm

Background:
I have several vanilla JS projects with files up to 25 000 lines / single file in which I would like to use ES6 capabilities + require so I can make the code more readable. OS X guy by the way
Possible solution:
I could make up a package.json and use a webpack for each project, but I would prefer if I do not do that.
What I have done so far:
Install browserify globally
sudo npm install -g browserify
setup a watcher in PhpStorm
global browserify path
/usr/local/lib/node_modules/browserify/bin/cmd.js
arguments
$FilePath$
-o
$FileDir$/$FileNameWithoutAllExtensions$.js
all works fine, and if I have a require in my code
var foo = require('./inc/_dependency-functionality');
✅ it will bundle just right and the required external files will get bundle inside a single file
BUT, ideally, I would like to have it so that I can use ES6 import / export functions, which may say I need babelify
doing this
sudo npm install -g browserify
and using
$FilePath$
-o
$FileDir$/$FileNameWithoutAllExtensions$.js
-t [ /usr/local/lib/node_modules/babelify --presets [/usr/local/lib/node_modules/#babel/preset-env ] ]
❌ will not actually babelify the script
I'm kind of stuck
Ok, I managed to do it
$FilePath$
-o
$FileDir$/$FileNameWithoutAllExtensions$.js
-t [ /usr/local/lib/node_modules/babelify/index.js --presets [/usr/local/lib/node_modules/#babel/preset-env ] ]
Babelify should be appended by /index.js
and then you can actually lose the presets, if you have .babelrc in the home of your user library ( babel searches for .babelrc recursively on top )
$FilePath$
-o
$FileDir$/$FileNameWithoutAllExtensions$.js
-t [ /usr/local/lib/node_modules/babelify/index.js ]
Also, make sure your files are named file.source.js not file.babel as I had them, as the transpiling will not start for unknown files

SyntaxError: Cannot use import statement outside a module

I've got an ApolloServer project that's giving me trouble, so I thought I might update it and ran into issues when using the latest Babel. My "index.js" is:
require('dotenv').config()
import {startServer} from './server'
startServer()
And when I run it I get the error
SyntaxError: Cannot use import statement outside a module
First I tried doing things to convince TPTB* that this was a module (with no success). So I changed the "import" to a "require" and this worked.
But now I have about two dozen "imports" in other files giving me the same error.
*I'm sure the root of my problem is that I'm not even sure what's complaining about the issue. I sort of assumed it was Babel 7 (since I'm coming from Babel 6 and I had to change the presets) but I'm not 100% sure.
Most of what I've found for solutions don't seem to apply to straight Node. Like this one here:
ES6 module Import giving "Uncaught SyntaxError: Unexpected identifier"
Says it was resolved by adding "type=module" but this would typically go in the HTML, of which I have none. I've also tried using my project's old presets:
"presets": ["es2015", "stage-2"],
"plugins": []
But that gets me another error: "Error: Plugin/Preset files are not allowed to export objects, only functions."
Here are the dependencies I started with:
"dependencies": {
"#babel/polyfill": "^7.6.0",
"apollo-link-error": "^1.1.12",
"apollo-link-http": "^1.5.16",
"apollo-server": "^2.9.6",
"babel-preset-es2015": "^6.24.1",
Verify that you have the latest version of Node.js installed (or, at least 13.2.0+). Then do one of the following, as described in the documentation:
Option 1
In the nearest parent package.json file, add the top-level "type" field with a value of "module". This will ensure that all .js and .mjs files are interpreted as ES modules. You can interpret individual files as CommonJS by using the .cjs extension.
// package.json
{
"type": "module"
}
Option 2
Explicitly name files with the .mjs extension. All other files, such as .js will be interpreted as CommonJS, which is the default if type is not defined in package.json.
If anyone is running into this issue with TypeScript, the key to solving it for me was changing
"target": "esnext",
"module": "esnext",
to
"target": "esnext",
"module": "commonjs",
In my tsconfig.json. I was under the impression "esnext" was the "best", but that was just a mistake.
For those who were as confused as I was when reading the answers, in your package.json file, add
"type": "module"
in the upper level as show below:
{
"name": "my-app",
"version": "0.0.0",
"type": "module",
"scripts": { ...
},
...
}
According to the official documentation:
import statements are permitted only in ES modules. For similar functionality in CommonJS, see import().
To make Node.js treat your file as an ES module, you need to (Enabling):
add "type": "module" to package.json
add "--experimental-modules" flag to the Node.js call
I ran into the same issue and it's even worse: I needed both "import" and "require"
Some newer ES6 modules works only with import.
Some CommonJS works with require.
Here is what worked for me:
Turn your js file into .mjs as suggested in other answers
"require" is not defined with the ES6 module, so you can define it this way:
import { createRequire } from 'module'
const require = createRequire(import.meta.url);
Now 'require' can be used in the usual way.
Use import for ES6 modules and require for CommonJS.
Some useful links: Node.js's own documentation. difference between import and require. Mozilla has some nice documentation about import
I had the same issue and the following has fixed it (using Node.js 12.13.1):
Change .js files extension to .mjs
Add --experimental-modules flag upon running your app.
Optional: add "type": "module" in your package.json
More information: https://nodejs.org/api/esm.html
First we'll install #babel/cli, #babel/core and #babel/preset-env:
npm install --save-dev #babel/cli #babel/core #babel/preset-env
Then we'll create a .babelrc file for configuring Babel:
touch .babelrc
This will host any options we might want to configure Babel with:
{
"presets": ["#babel/preset-env"]
}
With recent changes to Babel, you will need to transpile your ES6 before Node.js can run it.
So, we'll add our first script, build, in file package.json.
"scripts": {
"build": "babel index.js -d dist"
}
Then we'll add our start script in file package.json.
"scripts": {
"build": "babel index.js -d dist", // replace index.js with your filename
"start": "npm run build && node dist/index.js"
}
Now let's start our server.
npm start
I Tried with all the methods, but nothing worked.
I got one reference from GitHub.
To use TypeScript imports with Node.js, I installed the below packages.
1. npm i typescript --save-dev
2. npm i ts-node --save-dev
Won't require type: module in package.json
For example,
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
Step 1
yarn add esm
or
npm i esm --save
Step 2
package.json
"scripts": {
"start": "node -r esm src/index.js",
}
Step 3
nodemon --exec npm start
Node v14.16.0
For those who've tried .mjs and got:
Aviator#AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.mjs
file:///mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.mjs:3
import fetch from "node-fetch";
^^^^^
SyntaxError: Unexpected identifier
and who've tried import fetch from "node-fetch";
and who've tried const fetch = require('node-fetch');
Aviator#AW:/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex$ node just_js.js
(node:4899) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/mnt/c/Users/Adrian/Desktop/Programming/nodejs_ex/just_js.js:3
import fetch from "node-fetch";
^^^^^^
SyntaxError: Cannot use import statement outside a module
and who've tried "type": "module" to package.json, yet continue seeing the error,
{
"name": "test",
"version": "1.0.0",
"description": "to get fetch working",
"main": "just_js.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "MIT"
}
I was able to switch to axios without a problem.
import axios from 'axios'; <-- put at top of file.
Example:
axios.get('https://www.w3schools.com/xml/note.xml').then(resp => {
console.log(resp.data);
});
I found the 2020 update to the answer in this link helpful to answering this question as well as telling you WHY it does this:
Using Node.js require vs. ES6 import/export
Here's an excerpt:
"Update 2020
Since Node v12, support for ES modules is enabled by default, but it's still experimental at the time of writing this. Files including node modules must either end in .mjs or the nearest package.json file must contain "type": "module". The Node documentation has a ton more information, also about interop between CommonJS and ES modules."
I'm new to Node.js, and I got the same issue for the AWS Lambda function (using Node.js) while fixing it.
I found some of the differences between CommonJS and ES6 JavaScript:
ES6:
Add "type":"module" in the package.json file
Use "import" to use from lib.
Example: import jwt_decode from jwt-decode
Lambda handler method code should be define like this
"exports.handler = async (event) => { }"
CommonJS:
Don't add "type":"module" in the package.json file
Use "require" to use from lib.
Example: const jwt_decode = require("jwt-decode");
The lambda handler method code should be defines like this:
"export const handler = async (event) => { }"
In my case. I think the problem is in the standard node executable. node target.ts
I replaced it with nodemon and surprisingly it worked!
The way using the standard executable (runner):
node target.ts
The way using the nodemon executable (runner):
nodemon target.ts
Do not forget to install nodemon with npm install nodemon ;P
Note: this works amazing for development. But, for runtime, you may execute node with the compiled js file!
To use import, do one of the following.
Rename the .js file to .mjs
In package.json file, add {type:module}
If you are using ES6 JavaScript imports:
install cross-env
in package.json change "test": "jest" to "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
more in package.json, add these:
...,
"jest": {
"transform": {}
},
"type": "module"
Explanation:
cross-env allows to change environment variables without changing the npm command. Next, in file package.json you change your npm command to enable experimental ES6 support for Jest, and configure Jest to do it.
This error also comes when you run the command
node filename.ts
and not
node filename.js
Simply put, with the node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node.
If you want to use BABEL, I have a simple solution for that!
Remember this is for nodejs example: like an expressJS server!
If you are going to use react or another framework, look in the babel documentation!
First, install (do not install unnecessary things that will only trash your project!)
npm install --save-dev #babel/core #babel/node
Just 2 WAO
then config your babel file in your repo!
file name:
babel.config.json
{
"presets": ["#babel/preset-env"]
}
if you don't want to use the babel file, use:
Run in your console, and script.js is your entry point!
npx babel-node --presets #babel/preset-env -- script.js
the full information is here; https://babeljs.io/docs/en/babel-node
I had this error in my NX workspace after upgrading manually. The following change in each jest.config.js fixed it:
transform: {
'^.+\\.(ts|js|html)$': 'jest-preset-angular',
},
to
transform: {
'^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
},
I had this issue when I was running migration
Its es5 vs es6 issue
Here is how I solved it
I run
npm install #babel/register
and add
require("#babel/register")
at the top of my .sequelizerc file my
and go ahead to run my sequelize migrate.
This is applicable to other things apart from sequelize
babel does the transpiling
Just add --presets '#babel/preset-env'.
For example,
babel-node --trace-deprecation --presets '#babel/preset-env' ./yourscript.js
Or
in babel.config.js
module.exports = {
presets: ['#babel/preset-env'],
};
To make your import work and avoid other issues, like modules not working in Node.js, just note that:
With ES6 modules you can not yet import directories. Your import should look like this:
import fs from './../node_modules/file-system/file-system.js'
For people coming to this thread due to this error in Netlify functions even after adding "type": "module" in package.json file, update your netlify.toml to use 'esbuild'. Since esbuild supports ES6, it would work.
[functions]
node_bundler = "esbuild"
Reference:
https://docs.netlify.com/functions/build-with-javascript/#automated-dependency-bundling
The documentation is confusing. I use Node.js to perform some local task in my computer.
Let's suppose my old script was test.js. Within it, if I want to use
import something from "./mylocalECMAmodule";
it will throw an error like this:
(node:16012) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
SyntaxError: Cannot use import statement outside a module
...
This is not a module error, but a Node.js error. Forbid loading anything outside a 'module'.
To fix this, just rename your old script test.js into test.mjs.
That's all.
My solution was to include babel-node path while running nodemon as follows:
nodemon node_modules/.bin/babel-node index.js
You can add in your package.json script as:
debug: nodemon node_modules/.bin/babel-node index.js
NOTE: My entry file is index.js. Replace it with your entry file (many have app.js/server.js).
I had the same problem when I started to use Babel... But later, I
had a solution... I haven't had the problem any more so far...
Currently, Node.js v12.14.1, "#babel/node": "^7.8.4", I use babel-node and nodemon to execute (Node.js is fine as well..)
package.json: "start": "nodemon --exec babel-node server.js "debug": "babel-node debug server.js"!! Note: server.js is my entry
file, and you can use yours.
launch.json. When you debug, you also need to configure your launch.json file "runtimeExecutable":
"${workspaceRoot}/node_modules/.bin/babel-node"!! Note: plus
runtimeExecutable into the configuration.
Of course, with babel-node, you also normally need and edit another file, such as the babel.config.js/.babelrc file
In case you're running nodemon for the Node.js version 12, use this command.
server.js is the "main" inside package.json file, replace it with the relevant file inside your package.json file:
nodemon --experimental-modules server.js
I recently had the issue. The fix which worked for me was to add this to file babel.config.json in the plugins section:
["#babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true,
"loose": true,
"lazy": true
}],
I had some imported module with // and the error "cannot use import outside a module".
If you are using node, you should refer to this document. Just setup babel in your node app it will work and It worked for me.
npm install --save-dev #babel/cli #babel/core #babel/preset-env
When I used sequelize migrations with npx sequelize db:migrate, I got this error, so my solution for this was adding the line require('#babel/register'); into the .sequelizerc file as the following image shows:
Be aware you must install Babel and Babel register.
Wrong MIME-Type for JavaScript Module Files
The common source of the problem is the MIME-type for "Module" type JavaScript files is not recognized as a "module" type by the server, the client, or the ECMAScript engine that process or deliver these files.
The problem is the developers of Module JavaScript files incorrectly associated Modules with a new ".mjs" (.js) extension, but then assigned it a MIME-type server type of "text/javascript". This means both .js and .mjs types are the same. In fact the new type for .js JavaScript files has also changed to "application/javascript", further confusing the issue. So Module JavaScript files are not being recognized by any of these systems, regardless of Node.js or Babel file processing systems in development.
The main problem is this new "module" subtype of JavaScript is yet known to most servers or clients (modern HTML5 browsers). In other words, they have no way to know what a Module file type truly is apart from a JavaScript type!
So, you get the response you posted, where the JavaScript engine is saying it needs to know if the file is a Module type of JavaScript file.
The only solution, for server or client, is to change your server or browser to deliver a new Mime-type that trigger ES6 support of Module files, which have an .mjs extension. Right now, the only way to do that is to either create a HTTP content-type on the server of "module" for any file with a .mjs extension and change your file extension on module JavaScript files to ".mjs", or have an HTML script tag with type="module" added to any external <script> element you use that downloads your external .js JavaScript module file.
Once you fool the browser or JavaScript engines into accepting the new Module file type, they will start doing their scripting circus tricks in the JS engines or Node.js systems you use.

vue cli build with target lib: "require is not defined" when component is imported

I'm trying to export a Vue component as a package, and using vue cli to build the dist. I intend to publish it on npm, but I'm currently using a symbolic link for testing purpose. However even with a simple hello-world project I can't make a valid package.
I created a project:
vue create hello-world
Then I modified the package.json:
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue",
"lint": "vue-cli-service lint"
},
"main": "./dist/vue-hello-world.common.js",
Then I call
npm run build
and it compiles without error.
Then I make an import in a vue component in another project (I used a symbolic link in node_modules):
import HelloWorld from "hello-world";
On page render I get the following error:
[Vue warn]: Failed to resolve async component: function MediaViewerPdf() {
return Promise.all(/*! import() */[__webpack_require__.e(62), __webpack_require__.e(46)]).then(__webpack_require__.bind(null, /*! ./viewers/MediaViewerPdf.vue */ "./vuejs/components/mediaViewer/viewers/MediaViewerPdf.vue"));
}
Reason: ReferenceError: require is not defined
Any idea what's happening?
Remarks:
using vue inspect, I checked that in webpack config that:
target: "web"
I already set resolve.symlinks at false on the importing project.
EDIT: I have confirmed that it doesn't come from the symbolic link, I have exactly the same error with package directly on node_modules.
Repo with whole code: https://github.com/louis-sanna/vue-hello-world
So I asked the question on the vue-cli repo and I got the solution! https://github.com/vuejs/vue-cli/issues/4245
Turns out NODE_ENV was already set at development in my shell, so it was the mode used to make the build.
Just need to set the mode explicitly and it works:
vue-cli-service build --target lib --name vue-hello-world ./src/components/HelloWorld.vue --mode production
You may need to add it to vue.config.js:
config
.mode("production")
This happens due to the fact that Vue CLI Webpack setup by default does not import commonjs modules, as described in your "main" field in package.json. So the problem is with the project that attempts import, not with the project that exports the component.
There are two ways to attempt to solve this problem.
From the importing project side
You can remedy this by installing babel plugins for the project that imports your components and setting babel.config.js
module.exports = {
presets: [
'#vue/app'
],
plugins: [
'#babel/plugin-transform-modules-commonjs', // leave to import .common.js files
'#babel/plugin-transform-modules-umd' // leave to import .umd.js files
]
}
But doing this alone will not be sufficient: you also will need to import CSS that is generated with the library by adding this in your entry file
import 'hello-world/dist/vue-hello-world.css';
Note that I have only tested this using yarn link, but I have confidence that this will work with an imported separate npm module just fine.
From the library side
The intent (I suppose) of the original question - how do I bundle a library so my users don't have to do this little dance each time they want to use it?
Option 1: don't bundle it - provide .vue files and sources. Just include everything in 'src' directory of your module, write a readme with explanation and be done with it. Let the importing project figure the compilation and bundling out.
Option 2: use rollup with Vue plugin to roll components into bundle. There is an example on how to do that. In that example you can see that your project will be able to import .esm build
https://github.com/vuejs/rollup-plugin-vue/tree/master/cookbook/library
Not sure how you are creating the symbolic link, but you should use npm link for that. If you are still having problems (like I did myself) I would suggest you try npm-link-better:
npm install -g npm-link-better
cd vue-hello-world
npm link
cd ../hello-world
nlc -w vue-hello-world
For building component libraries, I suggest you have a look at vue-cli-plugin-component. This plugin already sets up the vue-cli project pretty well.

Do I need require js when I use babel?

Im experimenting with ES6, and Im using gulp to build and babel to transpile to ES5. The output is not being run in node, just linked to from a .htm file with a tag. Im thinking I need to add
<script src='require.js'></script>
or something like that.
Im trying to import / export.
////////////////scripts.js
import {Circle} from 'shapes';
c = new Circle(4);
console.log(c.area());
/////////////////shapes.js
export class Circle {
circle(radius) {
this.radius = radius;
}
area() {
return this.radius * this.radius * Math.PI;
}
}
Error is
Uncaught ReferenceError: require is not defined
Refers to this (after .pipe(babel()) in gulp)
var _shapes = require('shapes');
Do I need require js when I use babel?
You might need some module loader, but it is not necessary RequireJS. You have several options. The following will help you to get started.
rollup.js with rollup-plugin-babel
Rollup is a next-generation JavaScript module bundler. It understands ES2015 modules natively, and will produce a bundle that doesn't need any module loader to operate. Unused exports will be trimmed from the output, it's called tree-shaking.
Now I personally recommend using rollupjs, as it produces the clearest output, and is easy to setup, however, it gives a different aspect to the answer. All the other approaches do the following:
Compile the ES6 code with babel, use the module format of your choice
Concatenate the compiled modules alongside with a module loader OR use a bundler that will traverse the dependencies for you.
With rollupjs things doesn't really work this way. Here, rollup is the first step, instead of babel. It only understands ES6 modules by default. You must give an entry module of which the dependencies will be traversed and concatenated. As ES6 allows multiple named exports in a module, rollupjs is smart enough to strip unused exports, thus shrinking bundle size. Unfortunately rollupjs-s parser doesn't understand >ES6 syntax, so ES7 modules have to be compiled before rollup parses them, but the compilation should not affect the ES6 imports. It is done by using the rollup-plugin-babel plugin with the babel-preset-es2015-rollup preset (this preset is the same as the es2015 one, except the module transformer and the external-helpers plugin). So rollup will do the following with your modules if correctly set up:
Reads your ES6-7 module from the filesystem
The babel plugin compiles it to ES6 in memory
rollup parses the ES6 code for imports and exports (using acorn parser, compiled into rollup)
it traverses the whole graph, and creates a single bundle (which still might have external dependencies, and the entry's exports might be exported, in a format of your choice)
Example nodejs build:
// setup by `npm i rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`
// build.js:
require("rollup").rollup({
entry: "./src/main.js",
plugins: [
require("rollup-plugin-babel")({
"presets": [["es2015", { "modules": false }]],
"plugins": ["external-helpers"]
})
]
}).then(bundle => {
var result = bundle.generate({
// output format - 'amd', 'cjs', 'es6', 'iife', 'umd'
format: 'iife'
});
require("fs").writeFileSync("./dist/bundle.js", result.code);
// sourceMaps are supported too!
}).then(null, err => console.error(err));
Example grunt build with grunt-rollup
// setup by `npm i grunt grunt-rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`
// gruntfile.js
module.exports = function(grunt) {
grunt.loadNpmTasks("grunt-rollup");
grunt.initConfig({
"rollup": {
"options": {
"format": "iife",
"plugins": [
require("rollup-plugin-babel")({
"presets": [["es2015", { "modules": false }]],
"plugins": ["external-helpers"]
})
]
},
"dist": {
"files": {
"./dist/bundle.js": ["./src/main.js"]
}
}
}
});
}
Example gulp build with gulp-rollup
// setup by `npm i gulp gulp-rollup rollup-plugin-babel babel-preset-es2015 babel-plugin-external-helpers --save-dev`
// gulpfile.js
var gulp = require('gulp'),
rollup = require('gulp-rollup');
gulp.task('bundle', function() {
gulp.src('./src/**/*.js')
// transform the files here.
.pipe(rollup({
// any option supported by Rollup can be set here.
"format": "iife",
"plugins": [
require("rollup-plugin-babel")({
"presets": [["es2015", { "modules": false }]],
"plugins": ["external-helpers"]
})
],
entry: './src/main.js'
}))
.pipe(gulp.dest('./dist'));
});
Babelify + Browserify
Babel has a neat package called babelify. It's usage is simple and straightforward:
$ npm install --save-dev babelify babel-preset-es2015 babel-preset-react
$ npm install -g browserify
$ browserify src/script.js -o bundle.js \
-t [ babelify --presets [ es2015 react ] ]
or you can use it from node.js:
$ npm install --save-dev browserify babelify babel-preset-es2015 babel-preset-react
...
var fs = require("fs");
var browserify = require("browserify");
browserify(["./src/script.js"])
.transform("babelify", {presets: ["es2015", "react"]})
.bundle()
.pipe(fs.createWriteStream("bundle.js"));
This will transpile and concatenate your code at once. Browserify's .bundle will include a nice little CommonJS loader, and will organize your transpiled modules into functions. You can even have relative imports.
Example:
// project structure
.
+-- src/
| +-- library/
| | \-- ModuleA.js
| +-- config.js
| \-- script.js
+-- dist/
\-- build.js
...
// build.js
var fs = require("fs");
var browserify = require("browserify");
browserify(["./src/script.js"])
.transform("babelify", {presets: ["es2015", "react"]})
.bundle()
.pipe(fs.createWriteStream("dist/bundle.js"));
// config.js
export default "Some config";
// ModuleA.js
import config from '../config';
export default "Some nice export: " + config;
// script.js
import ModuleA from './library/ModuleA';
console.log(ModuleA);
To compile just run node build.js in your project root.
Babel + WebPack
Compile all your code using babel. I recommend you to use the amd module transformer (called babel-plugin-transform-es2015-modules-amd in babel 6). After that bundle your compiled sources with WebPack.
WebPack 2 is out! It understands native ES6 modules, and will perform (or rather simulate) tree shaking using babili-s builtin dead code elimination. For now (September 2016) I would still suggest to use rollup with babel, although my opinion might change with the first release of WebPack 2. Feel free to discuss your opinions in the comments.
Custom compilation pipeline
Sometimes you want to have more control over the compilation process. You can implement your own pipeline like this:
First, you have to configure babel to use amd modules. By default babel transpiles to CommonJS modules, which is a little complicated to handle in the browser, although browserify manages to handle them in a nice way.
Babel 5: use { modules: 'amdStrict', ... } option
Babel 6: use the es2015-modules-amd plugin
Don't forget to turn on the moduleIds: true option.
Check the transpiled code for generated modul names, there are often mismatches between defined and required modules. See sourceRoot and moduleRoot.
Finally, you have to have some kind of module loader, but it isn't necessairy requirejs. There is almondjs, a tiny require shim that works well. You can even implement your own:
var __modules = new Map();
function define(name, deps, factory) {
__modules.set(name, { n: name, d: deps, e: null, f: factory });
}
function require(name) {
const module = __modules.get(name);
if (!module.e) {
module.e = {};
module.f.apply(null, module.d.map(req));
}
return module.e;
function req(name) {
return name === 'exports' ? module.e : require(name);
}
}
At the end, you can just concatenate the loader shim and the compiled modules together, and running an uglify on that.
Babel's boilerplate code is duplicated in every module
By default, most of the above methods compile each module with babel individually, and then concatenate them together. That's what babelify does too. But if you look at the compiled code, you see that babel inserts lots of boilerplate at the beginning of each file, most of them are duplicated across all files.
To prevent this you can use the babel-plugin-transform-runtime plugin.
barebones webpack 2
1) If this is your root directory:
index.html
<html>
...
<script src="./bundle.js"></script>
...
</html>
scripts.js
import { Circle } from './shapes.js';
...
shapes.js
export class Circle {
...
}
2) have node installed node
3) run the following command in your terminal:
$ npm install -g webpack
5) in your root directory run the following:
$ webpack scripts.js bundle.js
You should now have a file called bundle.js in your root directory which will be the file your index.html will consume. This is a minimalistic bundling feature from webpack. You can learn more here
require does not exist in the browser, so this error is expected. You need to use something like require.js or Browserify.

Categories

Resources