SystemJS Builder + Babel issue - javascript

I'm trying out SystemJS and getting an issue when trying to use the builder alongside babel.
It's a simple ES2015 project, so won't bore you with the details of that, but my bundle setup looks like the below.
config.js:
System.config({
transpiler: 'babel',
paths: {
'babel': './node_modules/babel-core/lib/api/browser.js'
}
});
builder.js:
var path = require("path");
var Builder = require('systemjs-builder');
var builder = new Builder('.', 'config.js');
builder
.buildStatic('./src/app.js', './dist/index.js')
.then(function() {
console.log('Build complete');
})
.catch(function(err) {
console.log('Build error');
console.log(err);
});
I'm getting the following error: ReferenceError: require is not defined on the browser.js file from babel. Prior to adding the babel path, I was getting an error that SystemJS was trying to locate babel.js relative to my source directory.
I'm obviously missing something simple here, but the docs aren't exactly straight forward, and seem to be a bit outdated with regards to babel. Do I need to run babel on the files prior to bundling with SystemJS so that require is available or something?

Not positive on this because I use jspm so I didn't have to set this up manually, but it looks like the correct main file for babel-core is ./node_modules/babel-core/browser.js which has "format global"; instead of "format cjs"; which would explain your error.

Related

Webpack 5 Receiving a Polyfill Error?!?! My JavaScript React project is receiving a polyfill error while trying to compile my webpack.config.js file

I am taking a course on Udemy (it is Brad Schiff's React for the Rest of Us course here) that is based on React and I am receiving an error related to webpack which is keeping it from compiling.
I am getting the following error as I am trying to compile my webpack file from a Udemy course I am taking... here is a picture of the error I am receiving on my terminal:
please view it here
Here is the text of the error but please view the link for more details as a screenshot nonetheless:
Module not found: Error: Can't resolve 'path' in '/Users/seanmodd/Development/2021/BradSchiff/Frontend/node_modules/webpack/lib/util'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
# ./node_modules/webpack/lib/CleanPlugin.js 12:17-37
# ./node_modules/webpack/lib/index.js 115:9-33
# ./node_modules/dotenv-webpack/dist/index.js 12:15-33
# ./node_modules/dotenv-webpack/browser.js 1:13-38
# ./app/components/HomeGuest.js 5:15-40
# ./app/Main.js 8:0-47 38:96-105
Run npm install node-polyfill-webpack-plugin in your terminal`
go to your webpack.config.js and paste this:
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin')
module.exports = {
// Other rules like entry, output, devserver....,
plugins: [
new NodePolyfillPlugin()
]}
this should fix it, they removed automatic polyfills in webpack 5 that's why downgrading web3 version will fix it too
They have removed automatic polyfills in webpack 5. We have to include them ourselves.
More info here
By looking at the error stack, we see that ./app/components/HomeGuest.js line 15 requires the path module.
If you really need the path module on the client side, you have to add this in the webpack config file:
module.exports = {
// ... your config
resolve: {
fallback: {
path: require.resolve("path-browserify")
}
}
}
And also, install the path-browserify module (npm install path-browserify).
However, you may not need this module on the client side, and then the fix is to edit the HomeGuest.js file line 15 in such a way that the path module is not required.

webpack config for haml

So I've just started using webpack for my projects. I am using webpack to try and compile my haml templates to jsx to react elements. To do this I am using the haml-jsx and babel-loader loaders.
so, the problem I'm having right now arises when webpack goes to load the .haml template. I keep getting this error "module parse failed: unexpected token. you may need an appropriate loader to handle this file type". idk what is preventing the haml-jsx loader from working right, but as I said I'm new to webpack so idk if it's my webpack config file or something outside of that. That's why I'm coming to you folks!
the following is my webpack config file:
const path = require('path');
module.exports = {
entry:path.resolve(__dirname,"index.js"),
module:{
rules:[
{
test:/\.haml$/,
use:[
{
loader:"babel-loader",
options:{
presets: ['#babel/preset-env'],
plugins: [require('#babel/plugin-syntax-jsx')]
}
},
{
loader:"haml-jsx-loader"
}
]
},
]
},
output: {
filename:"bundle.js",
path: path.resolve(__dirname,"/distro")
},
};
also my directory structure looks like this
webpack
-sass(dir)
-distro(dir)
-haml(dir)
-tamplate.haml
-node_modules
-webpack.config.js
-babel.config.js
-index.js
-package.json
any suggestions at all would help! thanks!
The issue does not have anything to do with haml itself. The loaders are fine, except of the fact, that one of them can not parse - and therefore load - the given file.
Having a look at your babel-loader config, the fact that you're using React is the key to your issue. #babel/plugin-syntax-jsx is not what you're looking for. You should be using #babel/plugin-transform-react-jsx.
To be honest, the documentation for all the babel plugins is pretty bad actually.

Installing Modernizr with Yarn on Rails

I am trying to install Modernizr with Yarn in Rails. I do 'yarn add Modernizr' and it gets added to the .node-modules directory. However, I can't figure out how to reference it properly from Rails.
I have added //= require modernizr/src/Modernizr to application.js. But I'm not sure that's the right reference because I get the following error:
Uncaught ReferenceError: define is not defined
Do I need to somehow build the Modernizr library. Does yarn not do that? I'm somewhat new to this and struggling to understand the relationship between webpacker, yarn, and rails and how to properly build and add libraries to rails with yarn. The tutorials all make it seem as though it's as simple as 'yarn add xxx' but I seem to be missing something. Thank you.
What you're looking for is the webpacker gem, which ships by default with Rails 5.1+ but can be used with Rails 4.2+. Get that set up, then follow these steps to get a custom Modernizr build running in your Rails app:
Loader
Install the loader for modernizr:
$ yarn install webpack-modernizr-loader
Modernizr Configuration
Download your desired modernizr config from the modernizr site. Visit a link like this:
https://modernizr.com/download?-appearance-backgroundblendmode-backgroundcliptext-backgroundsize-bgpositionxy-borderradius-boxshadow-boxsizing-canvas-canvastext-cssgradients-csspointerevents-fontface-generatedcontent-inputtypes-lastchild-mediaqueries-multiplebgs-opacity-svg-touchevents-setclasses-dontmin-cssclassprefix:mod_
Then configure your build, click "Build" in the upper right-hand corner, and download "Command Line Config".
Then convert it from JSON to a module and save it as config/webpack/.modernizrrc.js (note the leading period in the filename), like so:
"use strict";
module.exports = {
minify: false,
options: [
"setClasses"
],
"feature-detects": [
"test/canvas",
"test/canvastext",
"test/inputtypes",
"test/svg",
"test/touchevents",
"test/css/appearance",
"test/css/backgroundblendmode",
"test/css/backgroundcliptext",
"test/css/backgroundposition-xy",
"test/css/backgroundsize",
"test/css/borderradius",
"test/css/boxshadow",
"test/css/boxsizing",
"test/css/fontface",
"test/css/generatedcontent",
"test/css/gradients",
"test/css/lastchild",
"test/css/mediaqueries",
"test/css/multiplebgs",
"test/css/opacity",
"test/css/pointerevents"
]
};
Custom Configuration
Next, create a custom webpack config file as config/webpack/custom.js:
const path = require("path");
module.exports = {
module: {
rules: [
{
loader: "webpack-modernizr-loader",
test: /\.modernizrrc\.js$/
}
]
},
resolve: {
alias: {
modernizr$: path.resolve(__dirname, "./.modernizrrc.js")
}
}
};
Expose Configuration
Make your config/webpack/environment.js look like this:
const { environment } = require("#rails/webpacker");
const customConfig = require('./custom');
environment.config.merge(customConfig);
module.exports = environment;
Import Modernizr
Add the following line to app/javascript/packs/application.js:
import modernizr from 'modernizr';
Load Your Pack
Add this to your layout:
<%= javascript_pack_tag "application", defer: true %>
Voila
Load up your site in a browser, inspect, and confirm that (a) modernizr CSS classes have been added to the DOM, and (b) you aren't seeing any webpack compilation errors in the console.
Further Reading
I came upon this question when I was looking to set up modernizr using webpacker in a Rails 5 app, saw the question was unanswered, and figured it out myself. If you want to know how all of this works, I suggest reading the docs for webpacker and webpack-modernizr-loader.

NPM module throws an error when being imported

I have been trying to get the following module to work on a react/webpack application:
https://github.com/ripjar/material-datetime-picker
Whenever I import the module my server wont start and it crashes with the syntax error: Uncaught SyntaxError: Unexpected token import.
It seems that throughout the modules code it is using es6 to import/export but each one of those lines breaks the module when I try to install and export it into my own file.
I have tried looking through the source code for the module as well as the standalone version but cant get either to work - however - I know that the module works inside a standalone HTML file as their demo still works when I download it locally.
Could this have to do with incompatibility with webpack? I have been working with their code along with a senior developer and we cant seem to get the module to load at all.
Apparently you're trying to import es6 module while not using es6 compiler like Babel
If you intend to use it with CommonJS you should consider adding it using require:
var MaterialDateTimePicker = require('material-datetime-picker');
I believe you are using this module/js for front-end(browser). I will suggest using babelify in your build environment. You can check documentation in given links.
webpack-for-browserify-users
babeljs.io-installation
babel/babelify
Babel transformation--
var fs = require("fs"); var browserify = require("browserify");
var babelify = require("babelify");
browserify({ debug: true })
.transform(babelify)
.require("./script.js", { entry: true })
.bundle()
.on("error", function (err) {
console.log("Error: " + err.message);
}).pipe(fs.createWriteStream("bundle.js"));

Trouble using babel transpiler with WebPack

I'm trying to use this package in my application.
It appears to be written in ES6 so I need a transpiler like babel. I've started a new project and tried the following:
Create new index .html / .js file for testing.
npm install audio-effects
npm install gulp gulp-babel babel-preset-es2015
Create .babelrc
After trying to run this from the dist folder with python -m SimpleHTTPServer, I got an error: index.js:3 Uncaught ReferenceError: require is not defined.
After some digging, this is because require can't be used client-side. So next I looked into using WebPack to allow me to use require.
I went into my dist folder (where my transpiled javascript is) and ran:
webpack ./index.js index.js
But now I'm getting the error index.js:78 Uncaught SyntaxError: Unexpected token import.
Can anybody see what I'm missing (apart from a NPM-ES6-Gulp-WebPack tutorial)? I seem to be stuck in a loop of WebPack-ing and transpiling.
index.html
<!DOCTYPE html>
<html>
<body>
<h4>Welcome</h4>
<button onclick="startAudio()">Start Audio</button>
<script src="js/index.js"></script>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>
index.js (pre-babel / WebPack - ification)
import {HasAudioContext} from 'audio-effects';
function startAudio() {
console.log("Start Audio...");
let audioContext = null;
if (HasAudioContext) {
console.log("Has Audio CTX");
audioContext = new AudioContext();
}
else {
console.log("No Audio CTX");
}
}
gulpfile.js
var gulp = require("gulp");
var babel = require("gulp-babel");
gulp.task("default", function () {
return gulp.src("src/app.js")
.pipe(babel())
.pipe(gulp.dest("dist"));
});
I've made some changes to the library (I'm the original author of the package). When installing the package with npm, you will now get the transpiled ES5 code instead of the ES6 source. You'll still need webpack, browserify, ... to load the module though.
This might fix the the Uncaught SyntaxError: Unexpected token import error, so please update your audio-effects library to the latest version.
The wrong imports as mentioned in the answer by Jorawar Singh should be resolved as well.
I'm still working on the library so if you run into any problems, feel free to create an issue or pull request on github.
I personally use the package with webpack. this is my webpack.config.babel.js file (remove comments).
Note: I'm using react, if you don't set the react parameter to false.
import config from 'madewithlove-webpack-config';
export default config({
react: true,
sourcePath: 'src', // Source directory
outputPath: 'builds', // Transpiled coded directory
});
This imports a basic webpack config from https://github.com/madewithlove/webpack-config/
Since I'm writing code in ES6, I'm transpiling it with babel, my .babelrc file looks like this:
{
"presets": ["es2015", "stage-0"],
}
With all this setup, you can just run webpack with webpack-dev-server --inline --hot.
You don't have to use the madewitlove webpack config but it takes care of some standard setup like compiling scss etc.
I hope this gives you an insight in how to use the audio-effects package or any other ES6 package.
Well what i understand there was some issues with this library it was written es6 and when you do import and want to complie into es5 with webpack then webpack will also bummbel all the require modules for you. Here's my webpack.config look likes
var webpack = require('webpack');
var config = {
entry: './index.js',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
module: {
loaders: [ {
test: /\.js$/,
loader: 'babel-loader',
query: {
presets: ['es2015']
}
}]
}
};
module.exports = config;
running by webpack will compile the library and your index.js file to bundle.js
there was some other issues i think in order to get this library you need to do some small changes in library.
from
'./Helpers/HasAudioContext'; //this doesn't exist and
//webpack will give you compile error
to
'./helpers/hasAudioContext';
I had one issue whitch i couldn't resolve is i couldn't run the startAudio function but through the index.js i could (weard let me know if you find why)
in your index.js
document.getElementById("btn").addEventListener("click", startAudio);
there are still some issues witch i want to resolve and also there are some issues with the library witch need to be resolved

Categories