Do I need require js when I use babel? - javascript

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.

Related

How to use ES modules within gulpfile.js? [duplicate]

Question: How can I write my gulp file in ES6 so I can use import instead of require and use => syntax over function()?
I can use io.js or node any version.
gulpfile.js:
import gulp from "./node_modules/gulp/index.js";
gulp.task('hello-world', =>{
console.log('hello world');
});
Errors:
import gulp from "./node_modules/gulp/index.js";
^^^^^^
SyntaxError: Unexpected reserved word
gulp.task('hello-world', =>{
^^
SyntaxError: Unexpected token =>
Inside the node_modules/gulp/bin/gulp.js i've changed the first line to #!/usr/bin/env node --harmony as asked in this stack
Yes, you can by using babel.
Make sure you've got the latest version of the gulp-cli.
npm install -g gulp-cli
Install babel as a dependency of the project.
npm install --save-dev babel
Rename gulpfile.js to gulpfile.babel.js
Your gulpfile might look something like this:
import gulp from 'gulp';
gulp.task('default', () => {
// do something
});
Update for Babel 6.0+
As correctly pointed out by Eric Bronniman, there are a few extra steps involved in getting this to work with the latest version of babel. Here are those instructions:
Again, make sure you've got the latest version of gulp-cli
npm install -g gulp-cli
Then install gulp, babel core, and the es2015 presets
npm install --save-dev gulp babel-core babel-preset-es2015
Then, either add the following to a .babelrc file or to your package.json
"babel": {
"presets": [
"es2015"
]
}
Your gulpfile.js should be named gulpfile.babel.js
Note you can now use many/most ES6 features in Node.js v4.0.0 without babel. However apparently 'import' is still not supported. See: https://nodejs.org/en/docs/es6/
Edit: Most of the popular ES6 features (including destructuring and spread) are supported by default in NodeJS 5.0 (see above link.) The only major missing feature appears to be ES6 modules as far as I can tell.
If you have the latest versions of gulp & node, you can simply create a gulpfile as gulpfile.mjs instead of gulpfile.js and it should work without needing to use Babel or any other transpiler.
.mjs is a special format used by node which allows usage of ES Modules.
References :-
https://nodejs.org/api/esm.html#esm_enabling
https://nodejs.org/api/packages.html#packages_determining_module_system
Example :-
// Filename: gulpfile.mjs
import gulp from 'gulp';
export default task;
function task()
{
return (
gulp.src(`./src/js/**/*.js`)
.pipe(gulp.dest(`./dist/Static/js`)
);
}
I use babel-node and native gulp.
Install babel and gulp as devDependencies.
Write gulpfile.js with ES6 syntax.
Use command ./node_modules/.bin/babel-node ./node_modules/.bin/gulp to run gulp
In package.json scripts section, you can skip the first ./node_modules/.bin/ part - as babel-node ./node_modules/.bin/gulp.
The advantage of this appoach is, one day when the node.js support all ES6 features one day, all you need to opt-out babel runtime is to replace babel-node with node. That is all.
If you're using the most modern version of Gulp and the Gulp CLI, you can just do Gulpfile.babel.js and it will understand and transpile your ES6 gulpfile with BabelJS by default.
It is also important to have the BabelJS transpiler installed under devDependencies as is Gulp:
npm install --save-dev babel
Also note that to require gulp in this context, you do not have to import the index.js, you can just:
import gulp from 'gulp';
Basically, what you need to install using npm is gulp, gulp-babel and babel-resent-env, add "env" to your .babelrc presets array, and use a gulpfile.babel.js file.
npm install gulp-babel --save-dev
Some of the answers mentioned babel-core, babel-preset-es2015, etc. The Babel official setup guide with Gulp is to use gulp-babel only, while gulp-babel has dependencies modules including babel-core so you don't need to install it separately.
About preset, you need to use a preset to make Babel actually do something, which is called Preset Env that automatically determines the Babel plugins you need based on your supported environments.
npm install babel-preset-env --save-dev
and in .babelrc file
{
"presets": ["env"]
}
/*
* Steps
* 1. Rename your gulpfile.js to gulpfile.babel.js
* 2. Add babel to your package.json (npm install -D babel)
* 3. Start writing ES6 in your gulpfile!
*/
import gulp from 'gulp'; // ES6 imports!
import sass from 'gulp-sass';
const sassOpts = { outputStyle: 'compressed', errLogToConsole: true }; // "let" and "const"!!
gulp.task('sass', () = > { // Arrow functions!!
gulp.src('./**/*.scss')
.pipe(sass(sassOpts))
.pipe(gulp.dest('./'));
});
gulp.task('default', ['sass'], () => { // Arrow functions!!
gulp.watch('./src/sass/**/*.scss', ['sass'])
.on('change', (e) => { // Arrow functions!!
console.log(`File ${e.path} was ${e.type}, running Sass task...`); // Template strings and interpolation!!
});
});
Steps I followed for developing the code for gulpfile in es6:
npm install gulp && sudo npm install gulp -g.
Please make sure that you you are using the updated version of Gulp.
The current version at the time of writing this answer was 3.9.1. To check which version of gulp is installed, type gulp -v
npm install babel-core babel-preset-es2015-without-strict --save-dev
Type touch .babelrc in the terminal
In the .babelrc file, add this code
{
"presets": ["es2015-without-strict"]
}
Created the gulp config file with the name gulpfile.babel.js
Voila!!! You can now write the config code for gulp in ES6.
Source: Using ES6 with Gulp - Mark Goodyear
I have just had the same problem and
solved as following:
Windows 10
node version: 14.15.4
npm version: 6.14.10
gulp version: 4.0.2
using yarn v1
Renamed gulpfile.js as gulpfile.babel.js
Added these packages as devdependency:
"#babel/cli": "^7.12.10",
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/register": "^7.12.10",
"gulp-babel": "^8.0.0",
Added babel.config.json
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": "10",
"edge": "17",
"firefox": "60",
"chrome": "70",
"safari": "11.1"
}
}
]
]
}
Finally I deleted yarn.lock file and node_modules folder and installed all packages.
yarn install
This is how my gulpfile.babel.js file looks like:
import { src, dest, parallel, series, watch } from 'gulp';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import concat from 'gulp-concat';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import sass from 'gulp-sass';
import { init, write } from 'gulp-sourcemaps';
import uglify from 'gulp-uglify';
import babel from "gulp-babel";
//....
const _default = series(
parallel(scssTask, jsTask),
cacheBustTask,
watchTask
);
export { _default as default };
Note:
yarn gulp command runs properly but I still have that warning:
Requiring external module #babel/register

Webpack 5 and ESM

I think I've read every thread on SO and every related page on the internet on this, everything has some variation of a problem
I want:
To use webpack to bundle my web app up
To use ES Modules within my source js and have them transpiled down for wider browser support
To use ES Modules within my webpack configuration
Node 14 allegedly supports ESM, so lets use that
Setup 1
I have "type": "module" in my package.json
then my webpack.config.js looks something like:
import { somethingUseful } from './src/js/useful-things.js';
export default (env, argv) => {
return {
// webpack config here
};
}
running > webpack (webpack-cli) I get:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: D:\git\Useroo\webpack.config.js
require() of ES modules is not supported.
require() of webpack.config.js from C:\nvm\v14.14.0\node_modules\webpack-cli\lib\groups\resolveConfig.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename webpack.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from package.json.
OK, so lets do what the error message says
Setup 2a
If I remove "type": "module" from my package.json I get
webpack.config.js
import { somethingUseful } from './src/js/useful-things.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
right.... So lets try the other suggested alternative:
Setup 2b
module.exports = async (env, argv) => {
var somethingUseful = await import('./src/js/useful-things.js');
return {
// webpack config here
};
}
I get a segfault.
/c/Program Files/nodejs/webpack: line 14: 14272 Segmentation fault "$basedir/node" "$basedir/node_modules/webpack/bin/webpack.js" "$#"
webpack-cli now supports ES Modules. All that is required is
adding "type": "module" to your package.json
or
name your webpack config with the mjs extension: webpack.config.mjs
At the time of writing, webpack-cli just doesn't support ES6 modules, so you basically have to re-implement it yourself.
It's not that hard really, just annoying. You need something like this (simplified for brevity): Just RTFM here https://webpack.js.org/api/node/
import webpack from 'webpack';
import webpackConfig from './webpack.config.js';
var config = await webpackConfig(mode);
var compiler = webpack(config);
compiler.watch()
Webpack does not have native support for ESM config files, as the other answer states, but it does support automatically transpiling them. If your config file is named webpack(.whatever).babel.js, and you have babel properly installed, your config file will be quietly downleveled before use.
As far as I know, the only way to configure Babel in this case is to use a top level .babelrc in your project directory. Mine simply contains {"presets": ["#babel/preset-env"]}. It does mean that if I want to use Babel in the build, I have to configure it through e.g. plugin options, but it works for me.
ETA: user #bendwarn says in a deleted comment that as of Webpack CLI 4.5.0 you can name your config file webpack.config.mjs or just call it webpack.config.js if your package is type: "module" and it should work natively. I haven't tried it (and frankly that second one sounds like a terrible idea).

Typescript transpile es6 .js dependency to es5

I have a hypothetical Typescript file in my project (simplified example).
Utils.ts:
import * as HelperFromNodeModules from 'helper-from-node-modules';
class Utils {
static foo() {
return HelperFromNodeModules.parse(...);
}
}
Importing helper-from-node-modules consists of a Javascript file.
helper-from-node-modules.js:
const dep = require('foo');
function parse(...) {
return bar.map((e) => {...});
}
And from #types/helper-from-node-modules index.d.ts:
export function parse(...);
The tsconfig.json among other things contains the following:
{
...
"target": "es5",
"lib": ["es2015.collection","es6", "dom"],
"sourceMap": true,
"allowJs": true,
...
}
So my problem is the Typescript compiler's output file is a giant concatenation of my compiled source code plus all of the decencies. Since helper-from-node-modules was always a .js file, the compiler seems to just append its contents to the output file. So, despite "target": "es5" the output file still contains es6 artifacts like const and (e) => {...}, resulting in errors with things later that expect strictly es5 javascript.
Is there is a way to tell the Typescript compiler/transpiler to output es5 on the javascript dependencies as well?
Context if you care:
I made the horrible mistake of using react-create-app-typescript and react-scripts-ts as the boilerplate for my React app. The webpack stack built in is very opinionated on where source code should come from and that the compiled source must be es5. The minifier/uglifier packaged will crash if attempting to minify any es6 artifacts. I know I can run npm run-script eject and modify the various config scripts but I am trying to avoid that mess. I would love to just get the source to compile to es6 and not mess with their webpack stack.
Unfortunately, there isn't a way to do convert dependencies from ES6 to ES5. That option in tsconfig.json only affects how TypeScript code is transpiled. What you should do is use an ES5 version of your helper-from-node-modules. For example, Angular is distributed with several packages, for ES5 (umd), ES5, ES6 ... Then, in the package.json of the library there are options to tell the packager (usually webpack) what version to use, depending on the target use for TypeScript.
If the library you're using does not support that, the only option you have is to transpile it to ES5 yourself, maybe using babel, or use an alternative.
Is is strange, however, for a library to be only distributed as ES6.
The only thing that comes to my mind is hooking into the compilation process and transforming your dependencies before they get processed by TypeScript. This requires TypeScript transformers.
A transformer is a function to which the AST of your program is exposed. A basic example:
import * as ts from 'typescript';
export default (program: ts.Program) => {
return (ctx: ts.TransformationContext) => {
return (sourceFile: ts.SourceFile) => {
function visitor(node: ts.Node): ts.Node {
/**
* If that's the kind of node you were looking for,
* do something with it and return it. Otherwise:
*/
return ts.visitEachChild(node, visitor, ctx);
}
return ts.visitEachChild(sourceFile, visitor, ctx);
};
};
}
If you are using Webpack, you could plug it into your build pipeline in your Webpack configuration file.
webpack.config.js
const transformer = require('./your-custom-transformer');
module.exports = {
/* ... */
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader', // (or 'awesome-typescript-loader')
options: {
getCustomTransformers: program => ({
before: [
transformer(program)
]
})
}
}
]
}
};
Came across this question because I needed to import some files into both Next.js and my CLI. (A common source file in two different builds.) Next.js has certain automated configuration, so I was trying to support all the things it supports so I didn't have many situations where Next.js worked and my CLI failed.
So the below solution is the Babel part. (I combined with https://github.com/vercel/next.js/tree/canary/examples/custom-server-typescript for the tsconfig part.)
Solution to transpile ES6 imports to ES5: (outside of nextjs)
from https://www.dotnetcurry.com/javascript/1293/transpile-es6-modules-es5-using-babel
npm install --save-dev #babel/cli #babel/preset-env
Create .babelrc:
{
presets: ["#babel/preset-env"]
}
add to your build script (i.e. you probably already have package.json script for npm run build to work)
for JSX to work (if you have any .tsx files or JSX syntax in .js files)
npm install --save-dev #babel/preset-react
and in .babelrc
{
"presets": [
"#babel/preset-env",
[
"#babel/preset-react",
{
"runtime": "automatic"
}
]
]
}
for Next.js _app had to add https://github.com/uiwjs/babel-plugin-transform-remove-imports to remove CSS imports

React webpack / browserify "unexpected token"

I have this npm module that I created and every time I try to include it to see if it works I get this error:
Unexpected token <
You may need an appropriate loader to handle this file type.
I've used react-starterkit and included it in main.js like so
var ReactDOM = require('react-dom');
var ColorPicker = require('color-picker-react');
ReactDOM.render(<ColorPicker />, document.getElementById('app'));
then when i run gulp which runs webpack I get the error. Here's the webpack.config.js
module.exports.getConfig = function(type) {
var isDev = type === 'development';
var config = {
entry: './app/scripts/main.js',
output: {
path: __dirname,
filename: 'main.js'
},
debug : isDev,
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}]
}
};
if(isDev){
config.devtool = 'eval';
}
return config;
}
I've tried everything I could think of and still can't get it to work. I'm not using ES6 anywhere and I've tried many different react starter kits but I just can't get it to work. Please help!!!
P.S. I am able to get the project to run when I clone it locally and build out app.js with browserify like so: browserify -t [ babelify --presets [ react ] ] app.js -o bundle.js
To solve the problem you need to remove the line exclude: /node_modules/ if you are not the author of the npm module (But you should go with another module).
The component color-picker-react doesn't seem to have a release build or script that compile the jsx. So you need to do it by your own and compile the jsx file on the fly using wepack.
Instead of just removing the exclude: /node_modules/
You can exclude all /node_modules/ except the /node_modules/color-picker-react folder by using a regex pattern :
//will exclude all modules except `color-picker-react`
exclude: /node_modules\/(?!color-picker-react).*\//,
EDIT Basics for creating a npm module:
A correct setup for a npm module is to add a prepublish script to
ensure compilation happens automatically before uploading to NPM.
Thus when you push your module to npm the users doesn't need to compile the module they can just require it.
Taking an example of a node_module:
https://github.com/securingsincity/react-ace/blob/master/package.json
The package.json file is saying which file is the entry point when you required the module
"main": "lib/ace.js",
You can see in the github repository that the lib folder doesn't exist because added to the .gitignore but the line
"prepublish": "npm run clean && npm run build"
is run before uploading to NPM so on the npm repository the lib/ folder exist and you can see it when you do npm install --save react-ace the lib folder appears in the node_modules/react-ace/ folder
A great link that explains how to build npm modules in es6 for example http://javascriptplayground.com/blog/2015/10/authoring-modules-in-es6/
EDIT explain what needs to be done on react-color-picker module :
Sorry i didn't see that you was the author of the module so you should go with the solution below.
The react-color-picker for example doesn't have a prepublish script and the main file is index.js which is
var ColorPicker = require('./colorpicker.js'); // require a file with jsx will throw an error if not precompiled
module.exports = ColorPicker;
So a syntax error is thrown.
To be able to use the npm module in your other applications :
Create a webpack config for the npm module to handle the conversion of your react component written using jsx (you can take some of the webpack configs of this module https://github.com/securingsincity/react-ace set libraryTarget: 'umd' you module will be more easy to consume from various module systems (global, AMD, CommonJS).)
add a prepublish script that output a precompiled version of the color picker (lib/pickedprecompiled.js)
change the main to "main": "lib/pickedprecompiled.js",

"ReferenceError: Can't find variable: require" (using babel.js output) [duplicate]

When this code (generated from babel) runs I get an error exports is undefined
Object.defineProperty(exports, '__esModule', {
any ideas?
You are most likely not executing the code in an environment that supports CommonJS modules. You could use a bundler, such as Browserify or webpack
to bundle your modules into something that can be run in different environments.
Or you could choose a different module transformer.
With webpack
Run npm install -g webpack; npm install -D babel-loader. Then with this webpack configuration:
// webpack.config.js
module.exports = {
entry: "./path/to/entry/module.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}
]
}
};
running the webpack command will convert all *.js files reachable via the entry file with babel and bundle them together into bundle.js.
I read an article about how ES6 import and export are only supposed to work in browser with "statically analyzable files" and Babel removed import and export support in the browser because of this. Something to do with async or possibly security?
If you want to skip the server-side bundling for dev purposes, you can put
window.MyModule = MyModule at the bottom, then import
var MyModule = window.MyModule at the top of your next file

Categories

Resources