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
Related
In a folder, I have the following JavaScript file main.js:
const o = require("./other.js");
console.log(o.f());
and the following JavaScript file other.js:
function f() { return 1.23; }
exports.f = f;
I need to have an equivalent file with no dependencies on other files, like the following JavaScript file bundle.js:
function f() { return 1.23; }
console.log(f());
How can I do that?
I tried to use the Rollup Nodejs extension, with this command:
rollup main.js -o bundle.js -f cjs
Though, the require statement remained in the bundle.js file, and if I remove the other.js, it is not working anymore.
You're correct - what you're looking for is a bundler. Rollup, however, will require specific configuration to work with your use-case; it doesn't support CommonJS imports (require) by default and will, as you've seen, leave them as-is.
If you'd like to use Rollup, you can resolve this by creating a configuration file that will look something like this:
import commonjs from '#rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [commonjs()]
};
and passing it to rollup --config bla.js.
You could also use a different bundler, such as esbuild; running npx esbuild main.js --bundle --outfile=out.js will do exactly what you're looking for. There are various advantages and disadvantages to using both - esbuild is extremely fast but is considered less mature than other bundlers.
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.
in react using webpack every js files is bundle into a single bundle.js , for my normal html , css, js application for example , i am having 6 libraries. for an example consider
i am using jquery and bootstrap min versions. so if i reference two files the request will be two. so how can i make it into a single file. So there will be a single request.
like when i checked the file size is about in kb's and the request is processed within less that 1 or 2 seconds , like the chrome dev tools shows the time for to load also it parrallely loads the two files.
But how can i bundle the two librarys using webpack and get a single file that i can refer in my application.
i am a beginner to webpack
You need to import them in your entry point file and Webpack will handle the bundling. As you have worked with React, I assume you have basic command line skills.
You can read the Getting Started guide which bundles Lodash like how you are trying to bundle jQuery and Bootstrap.
First of install, ensure that you are installing jQuery, Bootstrap, and any other libraries using npm (or yarn, if you prefer):
# Install Webpack as a dev dependency
npm install webpack webpack-cli --save-dev
# Install dependencies (I've added Popper.js as Bootstrap requires it)
npm install jquery bootstrap popper.js
Create a folder called src and a file inside there called index.js. This is your entry point and Webpack will look for this file unless configured differently. Import the libraries like this:
import $ from 'jquery'
import 'bootstrap'
// Do something with jQuery
$(document).ready(() => console.log('Hello world!'))
Then run Webpack using npx:
npx webpack
A file named main.js should be created in a folder called dist that contains the bundled code. This is your output file. You can use a <script> tag in your HTML file to load this JavaScript:
<!-- assuming your index.html is in the dist folder -->
<script src='main.js'></script>
Once you get here, you can explore more advanced things like importing Bootstrap components individually, minifying code, multiple bundles, transpiling TypeScript, etc.
You will likely need to add a Webpack configuration file very soon as there is only so much that can be done using zero-config mode.
Good practice is to keep two sepearate bundles for the application logic and external libraries and in webpack this can be achieved by the following code,
app.js - appliation index file,
vendors.js - import all external libraries in this file
entry: {
app: './src/app.js',
vendors: './src/vendors.js'
}
To get a single file, import vendors.js file inside app.js file and give entry key in webpack as
entry: './src/app.js'
Let us assume that you have the files in src directory. You can merge multiple files by specifying them in webpack.config.js to have a single named file as an output. I hope this is what you are looking for.
const path = require('path');
module.exports = {
entry: {
'bundle.js': [
path.resolve(__dirname, 'src/file1.js'),
path.resolve(__dirname, 'src/file2.js')
]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [{
exclude: /node_modules/
}]
}
};
As above, the two files "file1.js" and "file2.js" will be combined into a single file "bundle.js" and stored in "dist" directory.
You can also exclude node_modules by specifying a rule in module object of webpack configuration.
I followed the webpack official "get started" guide for a front end page and I'm wondering if it's intended to also be used in a development environment.
I managed to bundle all my foo.js dependencies but do I have to bundle everything together again each time I alter my foo.js or is there another way to be able to code and keep using the bundled dependencies?
webpack.config.js
var path = require('path');
module.exports = {
entry: './foo.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'foo.bundle.js'
},
resolve: {
alias: {
jquery: "jquery/src/jquery"
}
}
};
foo.js
require(['vue', 'jquery'], function(Vue, $){
console.log(Vue);
dynamo(Vue);
});
My planned workaround is to define a window.dynamo closure that is invoked in the afterwards loaded webpack bundle. The dynamo function would import the dev version foo.js (the one that is being developed on).
<script>
window.dynamo = function(Vue){
console.log(Vue);
}
</script>
<script src="/js/foo.bundle.js"></script>
What are your thoughts on about webpack and dev environment?
I found that passing the --watch parameter to webpack would make it watch all files and bundle them on the fly when one is modified:
webpack.js --watch
Also #connexo pointed on towards using https://github.com/vuejs-templates/webpack, which I didn't try yet because it implies knowledge about vue-cli. But it's definetly the next step.
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.