Unable to build jQuery ui with webpack - javascript

I'm unable to successfully include jQuery UI in my project using webpack. jQuery has been working, but when I visit a page of my app that requires jQuery-UI I get the following warning:
jQuery.Deferred exception: $(...).draggable is not a function TypeError: $(...).draggable is not a function
And error:
jquery.js:4055 Uncaught TypeError: $(...).draggable is not a function
I'm nearly brand new to building javascript code using webpack/node, so it's very possible I've made a naive mistake.
This is my config file:
config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/js/index.js',
mode: 'development',
output: {
filename: 'index.js',
path: 'path/js',
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader'
]
},
{
test: /\.js$/,
enforce: 'pre',
use: ['source-map-loader'],
},
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '../css/index.css',
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery',
})
],
resolve : {
alias: {
// bind version of jquery-ui
"jquery-ui": "jquery-ui/jquery-ui.js",
// bind to modules;
modules: path.join(__dirname, "node_modules"),
}
},
}
My entrypoint:
index.js
import '../sass/index.scss';
const $ = require("jquery");
require('webpack-jquery-ui');
require('webpack-jquery-ui/draggable');
global.$ = global.jQuery = $;
import 'bootstrap';
Each time I make a change I run the command:
npx webpack --config config.js
There are no errors output from this.
Where am I going wrong?
Update
Upon Chris G suggestion in comments I've tried the following:
import '../sass/index.scss';
const $ = require('webpack-jquery-ui');
global.$ = global.jQuery = $;
import 'bootstrap';
Upon rebuilding I get a series of errors in the console such as:
ERROR in (webpack)-jquery-ui/index.js
Module not found: Error: Can't resolve 'jquery-
ui/themes/base/autocomplete.css' in
'.../webpack/node_modules/webpack-jquery-ui'
# (webpack)-jquery-ui/index.js 57:0-49
# ./src/js/index.js
This is what's returned when running "npm install --save jquery jquery-ui"
npm WARN saveError ENOENT: no such file or directory, open '.../webpack/package.json'
npm WARN enoent ENOENT: no such file or directory, open '.../webpack/package.json'
npm WARN webpack No description
npm WARN webpack No repository field.
npm WARN webpack No README data
npm WARN webpack No license field.
Could this now be an install problem?

From my understanding, there are couple of things you need to do:
All you need to do is to only install webpack-jquery-ui.
I don't think you should are now resolving the correct jquery-ui in your webpack.config.js, just remove that alias of "jquery-ui"
resolve: {
alias: {
// bind to modules;
modules: path.join(__dirname, "node_modules"),
}
},
Finally, I don't think webpack-jquery-ui exports a jquery object for you so don't assign and export it in global anymore since it's currently available in your module with ProvidePlugin. So just simply write like following:
import '../sass/index.scss';
require('webpack-jquery-ui');
require('webpack-jquery-ui/draggable');
// $ is available in the module via `ProvidePlugin`
global.$ = global.jQuery = $;
import 'bootstrap';

Related

Failed to resolve module specifier "babel-runtime/regenerator"

I'm following the instructions for this link. https://reactjs.org/docs/add-react-to-a-website.html
I have the following code and it works:
const domContainers = document.querySelectorAll('[name="uiattr"]');
domContainers.forEach((element) => {
const id = element.id.split("-")[1];
ReactDOM.render(e(LikeButton), element);
});
If i change it to this code and add async to it:
const domContainers = document.querySelectorAll('[name="uiattr"]');
domContainers.forEach(async (element) => {
const id = element.id.split("-")[1];
const attr = await getAttr(id);
ReactDOM.render(e(LikeButton), element);
});
i get the following error in the console with nothing else: Failed to resolve module specifier "babel-runtime/regenerator"
I installed bable like this: npm install babel-cli#6 babel-preset-react-app#3
and i deploy with this command: js-dev$ npx babel --watch src --out-dir ../prj/static/prj/js/ --presets react-app/prod
I am new to the babel world, i'm assuming i need something else, but have no idea. I'm assuming the syntax is correct, only because its compiling without error. Something i've seen babel fail on when i have it wrong.
The React tutorial is indeed very confusing and doesn't cover all aspects.
I would suggest to just install react & react-dom: npm install --save react react-dom
You will need webpack to bundle your code and babel + a couple of plugins to compile your JSX, use async functions, ...: npm install --save-dev #babel/core #babel/preset-env #babel/preset-react #babel/plugin-transform-runtime babel-loader webpack webpack-cli.
Create a webpack.config.js file in your root folder:
const path = require('path');
module.exports = {
mode: "development", // or production
entry: {
app1: './react/app1/index.js'
},
watch: true,
output: {
filename: "[name].js",
path: path.join(__dirname, "public/react")
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
}
]
}
};
Create a .babelrc file in your root folder:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": ["#babel/plugin-transform-runtime"]
}
Example react/app1/index.js file:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(<App />, document.getElementById("myContainer"));
Write your react code in ./react/app1/index.js (you can import other React files, modules, ...)
Then in your html just put a script tag: <script src="public/react/app1.js"></script>

Webpack alias pointing to a parent directory which dosn't have webpack configured

I have a project which doesn't include webpack in the root direct, it's installed in my website folder within root directory.
project
-> src
-> App.js
-> Hello.js
-> index.js
-> website
-> webpack.config.js
-> index.js
-> package.json
and in my webpack.config.js file I added a alias entry to point to my components folder:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
resolve: {
alias: {
'#my-app/components': path.resolve(__dirname, '../src/'),
}
},
module: {
rules: [
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
},
}
The problem is: When I try to import my component like this import { Hello } from '#my-app/components'; and I try to npm run build, I get this error message:
ERROR in ../src/Hello.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/.../my-new-proj/src/Hello.js: Unexpected token (4:2)
I'm not sure if this problem is caused just because I'm pointing my components alias in a parent directory which doesn't have its own webpack config or it's something else.
I pushed my code to github so you can see the complete folder structure: https://github.com/osnysantos/my-new-project
Your problem has nothing to do with webpack alias. If you follow the the emitted error, you will see that babel-loader does not recognize the JSX. I see you have added react-presets to your babelrc file, however those seem to be overwritten by your webpack config. Either remove the preset array from the webpack config, or add react preset to them.

How to require webpack generate js file with requirejs?I use vue-cli

I make my project by vue-cli.
vue init webpack vue-demo
cd vue-demo
npm install
npm run dev
Now I want to devolop some components. And i want to use them in requirejs.
webpack config
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
filename: '[name].js',
libraryTarget: 'umd',
library:'senyint'
}
Q1:It generate three files. app.js manifest.js vendor.js
The demo has a Hello.vue . I want to require the js file by what webpack generate.
But I require them,it's undefiend . Why? What's the wrong?
Where I should export ?
Now I export in main.js like this.
import Hello from 'components/Hello'
module.exports = {
Hello
}
Q2:I dont want to package without vue.
So i configure this
externals: {
vue: 'vue'
}
If i do this, when npm run dev show error "Uncaught TypeError: Cannot read property 'config' of undefined"
It cause cant find Vue.
If i configure externals vue how to make it run?
Q1:
Open the javascript file app.js i found
define("senyint", ["vue"], factory);
at this line. The 'senyint' is a package name,webpack generate the js,but it doesnt work.
I modify the code like this
define(["vue"], factory);
Require it and it works. But I dont know why.... I just can resolve this problem;
main.js export .vue components
import Hello from 'components/Hello.vue'
export const scom = {
Hello
}
requirejs config
requirejs.config({
baseUrl: 'js/common',
paths: {
module: '../modules'
},
shim: {
app: {
deps:['vue','manifest','vendor']
}
}
})
requirejs(['module/demo', 'app'], function (demojs, app) {
debugger
console.log(app)
})
Q2:
I builded my project with vue-cli webpack template. (not webpack-simple)
In build directory has 'webpack.base.conf.js' and 'webpack.prod.conf.js'
Modify webpack.prod.conf.js add
externals: {
vue: {
root: 'Vue',
commonjs: 'vue',
commonjs2: 'vue',
amd: 'vue'
}
},
and dont add the code in 'webpack.base.conf.js' .Then npm run build it will package without vue.js .Npm run dev use webpack.base.conf.js ,it will run with vue

Webpack: Bundle.js - Uncaught ReferenceError: process is not defined

Here's my webpack.config.js
"use strict";
module.exports = {
entry: ['./main.js'],
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{test: /\.json$/, loader: "json"},
]
},
externals: {
React: 'react',
},
target: "node",
};
And Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jQuery from 'jquery';
import vis from 'vis';
import babel from 'babel-core';
The Bundle.js is inserted in my Index.html. The browser then gives the error:
Uncaught ReferenceError: process is not defined
at Object.measureMethods (bundle.js:1297)
at Object.<anonymous> (bundle.js:530)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:288)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:158)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:110)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:90)
What should I change in the webpack.config.js to make this error go away?
For Webpack 5, you can reference process/browser from the appropriate plugins part of webpack.config.js:
// webpack needs to be explicitly required
const webpack = require('webpack')
// import webpack from 'webpack' // (if you're using ESM)
module.exports = {
/* ... rest of the config here ... */
plugins: [
// fix "process is not defined" error:
new webpack.ProvidePlugin({
process: 'process/browser',
}),
]
}
Then run
npm install process
before building.
For namespaced environment variables (more secure) check lines 10 - 28 on this StackBlitz page.
With dotenv package:
Install dotenv:
yarn add -D dotenv or npm i -D dotenv
Add .env file in your project root with the required variables:
NODE_ENV=development
apiKey=w23io222929kdjfk
domain=example.domain.org
Define these variables with webpack.DefinePlugin:
// webpack.config.js
const webpack = require('webpack')
const dotenv = require('dotenv')
// this will update the process.env with environment variables in .env file
dotenv.config();
module.exports = {
//...
plugins: [
// ...
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
// ...
]
//...
}
Access environment variables in your source code:
// src/index.js
alert(process.env.NODE_ENV)
alert(process.env.apiKey)
StackBlitz example: https://stackblitz.com/edit/node-kdfi4z?file=index.js
You need to add a plugin to define your env (in webpack config):
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
This is how i resolved the
ReferenceError: process is not defined
error with Webpack 5
npm i --save-dev process
Delete the "node_modules" folder
Add const webpack = require('webpack'); at the top of your config file
In your webpack config file, plugin section, add below:
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
Also in the webpack add the alias like below:
resolve: {
alias: {
process: "process/browser"
},
Now do npm i
...and when you build your application the error will disappear.
you can read about webpck migration [here]
Webpack 5 removes the ability to access environment variables using the notation process.env.MY_ENV_VAR. I had this same problem because I was getting a Uncaught ReferenceError: process is not defined error in my browser console. From the documentation of porting from v4 to v5 of Webpack, they mention the following:
1. Before upgrading to v5, verify that you can easily do it
Try to set the following options in your webpack 4 configuration and
check if build still works correctly.
module.exports = {
// ...
node: {
Buffer: false,
process: false
}
};
webpack 5 removes these options from the configuration schema and will always use false.
You have to remove these options again when upgrading your
configuration for webpack 5.
2. Handling env vars because process was removed
Regarding Runtime Errors:
process is not defined.
webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code.
Want to support frontend and browser usage? Use the exports or imports package.json field to use different code depending on the
environment.
Also use the browser field to support older bundlers,.
Alternative: Wrap code blocks with the typeof process checks. Note that this will have a negative impact on the bundle size.
Want to use environment variables with process.env.VARIABLE? You need to use the DefinePlugin or EnvironmentPlugin to define these
variables in the configuration.
Consider using VARIABLE instead and make sure to check typeof VARIABLE !== 'undefined' too. process.env is Node.js specific
and should be avoided in frontend code.
Therefore, given the above information, it is possible to use environment variables using one of the two plugins below.
const webpack = require("webpack");
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
"process.env.MY_ENV_VAR": JSON.stringify(process.env.MY_ENV_VAR)
}),
new webpack.EnvironmentPlugin(['MY_ENV_VAR']); // <--This is shorthand, does the same thing as the DefinePlugin
],
};
Then in your production code it's still feasable to refer to the environment variable in the same way, example:
console.log(process.env.MY_ENV_VAR);
However, as they said in the documentation included above, using process.env is NOT the recommended way since that is Node.js specific.
Webpack 5, the easiest solution for me...
npm install dotenv-webpack --save-dev
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
To avoid error like denoted in the question I had have provide in webpack.config.js the next configuration (note defining variable level: process.env):
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env)
})
Now it works fine. I'm using webpack 5.30.0, Vue 2.6.12 and vuelidate 0.7.6.
Error I had before in browser console:
Uncaught ReferenceError: process is not defined
at Object.../node_modules/vuelidate/lib/withParams.js
It is not good thing, that browser client library "vuelidate" requires Node.js specific env variables. Confused build and runtime areas in library.
Works for me to allow reading env variables inside React, using "webpack": "^5.1.3",
webpack.config.js
const webpackConfig = {
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
],
};
:)
Having dotenv-webpack/dotenv in your webpack and still doesn't work on Angular? Most probably you're trying to access process.env when running the Angular app on the browser (without Angular Universal), e.g. by ng serve.
Run npm i -S process and then in polyfills.ts paste the code below
import * as process from "process";
window["process"] = process;
Alternatively, if that's not the case and you're looking for webpack to obtain environmental variables then (I don't know why no one suggested yet) dotenv-webpack is the simplest one.
const dotenv = require("dotenv-webpack");
const webpackConfig = {
plugins: [new dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Of course you need to have them defined in .env file at the root of your project.
If it is useful for someone:
I tried almost every approach in this thread unsuccessfully.
When I went deeper into the problem I realized that what was causing this error on my application was the usage of assert lib:
import * as assert from 'assert';
...
assert(myVariable !== undefined, "Try to update undefined myVariable ");
BTW: I'm using Angular#~11.2.7
My problem was process is undefined error on internet explorer 11 using webpack 5.
This is how I solved my problem with process.env.MY_ENV_VAR thanks to #ArianPopalyar.
Ref. Answer
In addition to her solution, I added EnvironmentPlugin in webpack.config.js:
...
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser'
}),
new webpack.EnvironmentPlugin({
PATH_MODERN: 'dist/modern/domready.min.js',
PATH_LEGACY: 'dist/legacy/domready.min.js',
DEBUG: false
}),
...
]
and using it in index.js
if (process.env.PATH_LEGACY) {
// ...
}
Easy way: prepend the variable "NODE_ENV" when you call webpack i.e. NODE_ENV=production webpack --watch

How to use babel-polyfill in gulpfile.js

In Babel docs they just say that to include import "babel-polyfill"; so that I can use ES6 generators but after I included that line in my gulpfile.js I still gen an exception : Uncaught ReferenceError: regeneratorRuntime is not defined
This is my gulpfile.js
import 'babel-polyfill';
var gulp = require("gulp"),
babel = require("gulp-babel"),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify');
gulp.task("babel", function() {
return gulp.src(jsSrc)
.pipe(concat('Main.js'))
.pipe(babel())
.pipe(gulp.dest(jsDest))
.pipe(rename('Main-min.js'))
.pipe(uglify())
.pipe(gulp.dest(jsDest));
});
jsSrc have maines6.js and other .js files. In maines6.js here is my generator:
function* anotherGenerator(i) {
yield i + 1;
yield i + 2;
yield i + 3;
}
I don't know how to use this.. can you help me?
Since you're just using gulp and not some sort of module bundler(webpack for e.g)
You should follow this guide https://github.com/babel/gulp-babel#runtime
npm install --save-dev babel-plugin-transform-runtime
and then use it like this
.pipe(babel({
plugins: ['transform-runtime']
}))
Should do the trick :)
EDIT:
Seems that babel-plugin-transform-runtime add require calls to the transformed file, so I guess you'll need to use a module loader. I would suggest webpack, although there are alternative like browserify and jspm.
You'll need
npm install -g webpack
npm install babel-loader babel-core babel-polyfill babel-preset-es2015 --save-dev
Then you'll need to create a webpack.config.js file. Here's a very primitive setup.
module.exports = {
context: __dirname + '/app',
entry: ['babel-polyfill', './entries/index.js'],
output: {
path: 'dist',
filename: '[name].js'
},
module: {
loaders: [
{
test: /\.js/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015']
}
}
]
}
};
With the config above the file structure should looke like this
project/
node_modules/
app/
entries/
main.js
dist/
main.js
webpack.config.js
package.json
Then just run webpack from your command line. If you want to get the minified version run webpack -p
to include the polyfill you need to require it at the top of the entry point to your application.
import 'babel/polyfill' would need to go at the top of your jsSrc entry file

Categories

Resources