Browserify Shim Buffer core module - javascript

I'm trying to browserify my library where there are Buffer core module being use in different places.
I want to shim this core Buffer with another library that we are using.
I have tried to look into https://github.com/thlorenz/browserify-shim where I can specify my module that I want to shim but it doesn't seem to work.
I've created file called shim.js
var Buffer = require('myModule').Buffer;
module.exports = {
Buffer: { exports: Buffer }
};
in Package.json
{
...
"dependencies": {
"MD5": "^1.2.1",
"browser-request": "^0.3.1",
"browserify-shim": "^3.6.0",
...
},
"devDependencies": {
...
},
"browserify-shim": "./shims.js"
}
And in Gruntfile.js (I'm using grunt-browserify)
browserify: {
src: "./index.js",
options: {
transform: ['browserify-shim'],
browserifyOptions: {
builtins: false
},
bundleOptions: {
standalone: "mylibrary"
}
}
}
},
Right now when I grunt build the file I'm still seeing this being require in:
[function(_dereq_,module,exports){
(function (Buffer){
And in my browser is complaining about
Uncaught Error: Module name "buffer" has not been loaded yet for context: _. Use require([])

Related

Webpack can't resolve #import of scss/css

I have a main Stylesheet style.scss, which I imported in my main JavaScript file script.js:
import "./style.scss";
This works great, and I could build my website that way in dev mode. Now I wanted to try and use separate Stylesheet and import them in my main stylesheet with the #import rule, like so:
#import "./blocks/SCSS/test.scss" screen and (min-width: 600px);
But now I get this error message:
ERROR in ./dev/style.scss (./node_modules/css-loader/dist/cjs.js!./node_modules/sass-loader/dist/cjs.js!./dev/style.scss)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
Error: Can't resolve './blocks/SCSS/test.scss' in 'D:\Art Files\Design\Eigene Projekte\WP Book Theme Dev\dev'
And I don't understand why it can't resolve it. I use modules for my JavaScript as well, which works great. But now with SCSS, it does not work at all.
I tried googling for a solution and checked out several open threads, none could help me.
Here are some I checked out on Stackoverflow:
Module build failed (from ./node_modules/postcss-loader/src/index.js)
Module build failed (from ./node_modules/css-loader/dist/cjs.js): CssSyntaxError
Module build failed (from ./node_modules/sass-loader/dist/cjs.js)
Webpack: getting this error: build failed (from ./node_modules/css-loader/dist/cjs.js):
My Node version was 12.18.3, where I had the error first. Now I updated my node to the LTS to 14.15.4, still the same error.
Here are my Webpack config files:
// webpack.common.js
const path = require("path");
module.exports = {
entry: "./dev/script.js",
module: {
rules: [
{
test: /\.html$/i,
use: ["html-loader"],
},
{
test: /\.(svg|png|jpg)$/i,
use: {
loader: "file-loader",
options: {
esModule: false,
name: "[name].[hash].[ext]",
outputPath: "assets/images",
},
},
},
],
},
};
// webpack.dev.js
const path = require("path");
const common = require("./webpack.common.js");
const { merge } = require("webpack-merge");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = merge(common, {
mode: "development",
plugins: [
new HtmlWebpackPlugin({
template: "./dev/post.html",
}),
],
module: {
rules: [
{
test: /\.scss$/i,
use: ["style-loader", "css-loader", "sass-loader"],
},
],
},
devServer: {
contentBase: "./dist",
},
output: {
filename: "script.dev.js",
path: path.resolve(__dirname, "dist"),
publicPath: "./",
},
});
Here are my webpack dependencies:
"devDependencies": {
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^5.0.1",
"file-loader": "^6.2.0",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^4.5.0",
"mini-css-extract-plugin": "^1.3.3",
"optimize-css-assets-webpack-plugin": "^5.0.4",
"sass": "^1.32.0",
"sass-loader": "^10.1.0",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.0.3",
"webpack": "^5.11.1",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.1",
"webpack-merge": "^5.7.3"
},
This is what I did to fix my problem. Amaresh already mentioned something, about what I might be missing, but that didn't help me out with my problem, as I was given no real explanation on why that would help.
In the end, I did install sass*, and since node-sass is deprecated, I didn't pay any mind to it.
The way I used #import was probably wrong. I was trying to do it the native CSS way (MDN), but SCSS might have been overwriting that. #import by SCSS is also deprecated by now and not recommended. When I rechecked the SCSS Website, I went to their guide on how to use SCSS, and they mentioned how I could use #use to import another stylesheet. What I learned was that I need to use Partials. I had to lead filenames with an underscore to create a namespace for that, and import it using the #use rule.
From their example:
// _base.scss
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
// styles.scss
#use 'base';
.inverse {
background-color: base.$primary-color;
color: white;
}
* I don't know if the installation of sass actually helped or not. Since the package is dealing with JavaScript, which I have not done so in my file. But since the package is also mentioned in the sass-loader, I will keep it.
What is important to remember when using #use is how you handle the file in the new file.
// src/_list.scss
#mixin list{
ul {
display: flex;
flex-direction: row;
li {
text-align: center;
padding: 5px;
}
}
}
By only calling the URL, you have to specify the namespace and then what you want to use from that namespace.
// styles.scss
#use "src/list";
header {
#include list.list;
}
You can call a new namespace and give it a custom name.
// styles.scss
#use "src/list" as myList;
header {
#include myList.list;
}
Or you can call it and name it with an asterisk, making it available, without having to write the namespace when calling it.
// styles.scss
#use "src/list" as *;
header {
#include list;
}
For further reading, please check out their documentation on #use.
Check whether you have installed all these packages:
sass (https://www.npmjs.com/package/sass)
sass-loader (https://www.npmjs.com/package/sass-loader)
css-loader (https://www.npmjs.com/package/css-loader)
style-loader(https://www.npmjs.com/package/style-loader)
node-sass (https://www.npmjs.com/package/node-sass)
you might be missing node-sass

How to configure jest with babel

I'm configuring simple project for testing using jest and babel. How do i make them work together ?
I have tried instructions mentioned here: https://jestjs.io/docs/en/getting-started but couldn't accomplish it.
abc.test.js
import {PI} from "./mathconsts";
describe("tests",()=>{
test('assert pi', () => {
expect(PI).toBe(3.14);
});
});
mathconsts.js
export const PI = 3.14;
package.json
{
"name": "simple-testing",
"version": "1.0.0",
"description": "Project to write simple tests",
"main": "index.js",
"scripts": {
"test": "jest"
},
"dependencies": {
"axios": "0.19.0",
"dotenv": "8.1.0"
},
"devDependencies": {
"#babel/core": "^7.6.4",
"#babel/preset-env": "^7.6.3",
"babel-jest": "^24.9.0",
"jest": "24.9.0",
"prettier": "1.18.2"
}
}
babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
jest.config.js
module.exports = {
transformIgnorePatterns: [
"/node_modules/"
],
}
error found:
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/tests/abc.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { PI } from "./mathconsts";
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
How do i make it run ?

Brunch doesn't compile uikit js files

I am trying to compile my code using brunch, but the line js/components.js doesn't compile.
I tried changing the path from regex to a normal link, but nothing seems to make my components.js to be written.
Running brunch build -d doesn't give me any info about any of those files.
// package.json
"dependencies": {
"babel-brunch": "^7.0.1",
"brunch": "^2.10.17",
"clean-css-brunch": "^2.10.0",
"javascript-brunch": "^2.10.0",
"sass-brunch": "^2.10.8",
"uglify-js-brunch": "^2.10.0"
}
// brunch-config.js
module.exports = {
paths: {
'public': 'web',
'watched': ['app/Resources']
},
files: {
javascripts: {
joinTo: {
'js/app.js': /^app/,
// the next line is where my problem is
'js/components.js': /^bower_components\/uikit\/dist\/js\/components/
}
},
stylesheets: {
joinTo: {
'css/style.css': /style.scss/
}
}
}
};
I expect the file components.js to be written in my web/js/ directory, but nothing ever happens.

Nuxt Error: Syntax Unexpected token export after installation

I am using Nuxt for my Vue project, It was working fine. I deleted my yarn and NPM cache due to other project issues. I re-installed the packages for my Nuxt app. The app is Universal and Uses express. Installation and Dev server is running, but when I try to visit http://localhost:3000/,
The error:
SyntaxError: Unexpected token export, shows up every time.
I know this is babel issue but I don't how to resolve this issue on Nuxt.
Nuxt Configuration:
const pkg = require('./package')
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: pkg.name,
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [
'element-ui/lib/theme-chalk/index.css',
'#mdi/font/css/materialdesignicons.min.css'
],
/*
** Plugins to load before mounting the App
*/
plugins: [
'#/plugins/element-ui',
'~/plugins/vee-validate.js'
],
/*
** Nuxt.js modules
*/
modules: [
// Doc: https://github.com/nuxt-community/axios-module#usage
'#nuxtjs/axios',
'#nuxtjs/apollo'
],
apollo: {
tokenName: 'yourApolloTokenName', // optional, default: apollo-token
tokenExpires: 10, // optional, default: 7
includeNodeModules: true, // optional, default: false (this includes graphql-tag for node_modules folder)
authenticationType: 'Basic', // optional, default: 'Bearer'
// optional
errorHandler (error) {
console.log('%cError', 'background: red; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;', error.message)
},
// required
clientConfigs: {
default: {
// required
httpEndpoint: 'http://localhost:4000',
// optional
// See https://www.apollographql.com/docs/link/links/http.html#options
httpLinkOptions: {
credentials: 'same-origin'
},
// You can use `wss` for secure connection (recommended in production)
// Use `null` to disable subscriptions
wsEndpoint: null, // optional
// LocalStorage token
tokenName: 'apollo-token', // optional
// Enable Automatic Query persisting with Apollo Engine
persisting: false, // Optional
// Use websockets for everything (no HTTP)
// You need to pass a `wsEndpoint` for this to work
websocketsOnly: false // Optional
},
test: {
httpEndpoint: 'http://localhost:5000',
wsEndpoint: 'ws://localhost:5000',
tokenName: 'apollo-token'
},
// alternative: user path to config which returns exact same config options
}
},
/*
** Axios module configuration
*/
axios: {
// See https://github.com/nuxt-community/axios-module#options
},
/*
** Build configuration
*/
build: {
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
}
}
My package.json file
{
"name": "app",
"version": "1.0.0",
"description": "My exceptional Nuxt.js project",
"author": "Saima",
"private": true,
"scripts": {
"dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate"
},
"dependencies": {
"#mdi/font": "^3.3.92",
"#nuxtjs/apollo": "^4.0.0-rc2.3",
"#nuxtjs/axios": "^5.0.0",
"cross-env": "^5.2.0",
"element-ui": "^2.4.6",
"express": "^4.16.3",
"graphql-tag": "^2.10.1",
"less": "^3.9.0",
"less-loader": "^4.1.0",
"nuxt": "^2.0.0",
"vee-validate": "^2.1.5"
},
"devDependencies": {
"babel-preset-env": "^1.7.0",
"babel-register": "^6.26.0",
"nodemon": "^1.11.0"
}
}
Help would be appreciated.
I just checked your issue and it happens when you use element UI with Nuxt. Update your Nuxt configuration like this(Andrew Answer):
plugins: [
{src: '~/plugins/element-ui', ssr: false},
{src: '~/plugins/vee-validate.js', ssr: true},
],
This error can show up if you're importing an ES6 module which needs to be transpiled in order to load into the UI. In that case, this is fixed by adding the module into the transpile key of the build section of nuxt.config.js (at time of this post, the Nuxt transpile docs are a little confusing).
For instance, if you're trying to import a module called #stylelib then you'd want the following in your nuxt.config.js:
export default {
...
build: {
...
transpile: ['#stylelib']
}
}
I had the same issue and it was found in my nuxt.config.js file where i had placed some extra code with a ',' at the end of that code. The code in question was at the top of the file.
The code:
env: {
strapiBaseUri: process.env.API_URL || "http://localhost:1337"
},
My setup details are:
Nuxtjs (version as of March 20, 2020)
Apollo and Graphql
Strapi (backend)
For me (typescript Nuxt) it was using:
npm run start
instead of:
npm run dev

Grunt with babel and browserify

I have a simple JavaScript project that uses Babel to transpile ECMAScript 6 to ES5 and then needs Browserify to take advantage of ES6's Modules.
As so, I came up with this Gruntfile.js to compile it:
module.exports = function(grunt) {
"use strict";
grunt.loadNpmTasks('grunt-babel');
grunt.loadNpmTasks('grunt-browserify');
grunt.initConfig({
"babel": {
options: {
sourceMap: true
},
dist: {
files: {
"lib/pentagine.js": "lib/pentagine_babel.js",
"demos/helicopter_game/PlayState.js": "demos/helicopter_game/PlayState_babel.js"
}
}
},
"browserify": {
dist: {
files: {
"lib/pentagine.js": "lib/pentagine_babel.js",
"demos/helicopter_game/PlayState.js": "demos/helicopter_game/PlayState_babel.js"
}
}
}
});
grunt.registerTask("default", ["babel", "browserify"]);
};
grunt runs just fine without any errors. However, I get the following errors:
Uncaught SyntaxError: Unexpected reserved word on export
Uncaught SyntaxError: Unexpected reserved word on import
Basically what I'm doing in the main file is the following:
export class Game {
...
}
And then importing it like:
import {Sprite, Game} from "lib/pentagine";
I'm doing all the code according to ECMAScript 6. However, the export/import does not seem to be working and is instead colliding with JavaScript reserved words (despite me having browserify.js working).
Shouldn't you browserify the files created after the babel task? Note that the property name is the destination file and the value after the : is the source file. (I assume that your ES6 files are called filename.js instead of filename_babel.js)
files: {
"destination_file": "src_file"
}
Which leads to:
grunt.initConfig({
"babel": {
options: {
sourceMap: true
},
dist: {
files: {
"lib/pentagine_babel.js": "lib/pentagine.js",
"demos/helicopter_game/PlayState_babel.js": "demos/helicopter_game/PlayState.js"
}
}
},
"browserify": {
dist: {
files: {
"lib/pentagine_browserified.js": "lib/pentagine_babel.js",
"demos/helicopter_game/PlayState_browserified.js": "demos/helicopter_game/PlayState_babel.js"
}
}
}
});
or just lib/pentagine_babel.js": "lib/pentagine_babel.js" to browserify the same file.

Categories