Related
Buffer is not defined after migrating from CRA(create react app)
"vite": "^2.7.12"
I try to add plugins, add define for Buffer, but it's not work.
const viteConfig = defineConfig({
/* define: {
"Buffer": {}
},*/
plugins: [reactRefresh(), react()],
build: {
rollupOptions: {
input: {
main: resolve('index.html'),
},
},
},
clearScreen: false
});
Install this library
#esbuild-plugins/node-globals-polyfill
and add this in your vite.config.js
export default defineConfig({
// ...other config settings
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true
})
]
}
}
})
add this libary import to your vite.config.js
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
Николай Сычев solution didn't work for me at first.
Instead, I succeeded by simply
installing buffer as a dev dependency
yarn add buffer (use npm equivalent if you use npm)
and then adding it to the global scope in the index.html like this:
<html lang="en">
<head>
<script type="module">
import { Buffer } from "buffer";
window.Buffer = Buffer;
</script>
...
It also works for similar dependencies like process which you'd import in the index.html like this:
import process from "process";
window.process = process;
Update
For a different project I needed util, which required process. The above suggested method didn't suffice in that case.
Instead I found out that #esbuild-plugins (for vite dev) and rollup-plugin-polyfill-node (for vite build) would successfully provide all these nodejs packages.
Here is a full vite.config.ts that works for me:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { NodeGlobalsPolyfillPlugin } from '#esbuild-plugins/node-globals-polyfill'
import { NodeModulesPolyfillPlugin } from '#esbuild-plugins/node-modules-polyfill'
import rollupNodePolyFill from 'rollup-plugin-polyfill-node'
export default defineConfig({
plugins: [vue()],
base: '',
optimizeDeps: {
esbuildOptions: {
// Node.js global to browser globalThis
define: {
global: 'globalThis'
},
// Enable esbuild polyfill plugins
plugins: [
NodeGlobalsPolyfillPlugin({
buffer: true,
process: true,
}),
NodeModulesPolyfillPlugin()
]
}
},
build: {
rollupOptions: {
plugins: [
rollupNodePolyFill()
]
}
}
})
Be careful to use rollup-plugin-polyfill-node which is an updated and maintained fork of rollup-plugin-node-polyfills.
For me the above configuration did not work, I had to make changes in 3 files ,
in vite.config.ts , index.html and adding packages
1.Install Packages
yarn install process util buffer events
yarn add #esbuild-plugins/node-modules-polyfill
2.Update vite.config
import GlobalPolyFill from "#esbuild-plugins/node-globals-polyfill";
import react from "#vitejs/plugin-react";
import { resolve } from "path";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [react()],
optimizeDeps: {
esbuildOptions: {
define: {
global: "globalThis",
},
plugins: [
GlobalPolyFill({
process: true,
buffer: true,
}),
],
},
},
resolve: {
alias: {
process: "process/browser",
stream: "stream-browserify",
zlib: "browserify-zlib",
util: "util",
},
},
});
3.Update index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/assets/images/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<script>
window.global = window;
</script>
<script type="module">
import process from "process";
import EventEmitter from "events";
import {Buffer} from "buffer";
window.Buffer = Buffer;
window.process = process;
window.EventEmitter = EventEmitter;
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.js"></script>
</body>
</html>
Another approach is:
npm i -D rollup-plugin-polyfill-node
Then update vite.config.ts with the following:
import nodePolyfills from 'rollup-plugin-polyfill-node'
rollupOptions: {
plugins: [
// ...plugins
nodePolyfills(),
],
// ...rollupOptions
},
I am trying to build an angular 2 application using typescript in visual studio 2015 application. I am using angular release candidate 1.
I am getting the following error message in the console of my browser while running the application.
index.html:24 Error: Error: XHR error (404 Not Found) loading http://localhost:3622/app.js(…)
I cannot understand why it is trying to look for app.js file. I have set index.html as the start page.
As seen in the code below , I am trying to display data in the datatable. Is there any issue with how I have setup the systemjs.js file or with the system.import statement in index.html file
Please find my folder structure
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Angular 2 Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/primeui/primeui-ng-all.min.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function (err) { console.error(err); });
</script>
</head>
<body>
<my-app>Loading..</my-app>
</body>
</html>
Systemjs.config.js
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'#angular': 'node_modules/#angular',
'primeng': 'node_modules/primeng'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'.': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
var packageNames = [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/testing',
'#angular/upgrade',
'#angular/router-deprecated'
];
// add package entries for angular packages in the form '#angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function (pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
main.ts
import { bootstrap } from '#angular/platform-browser-dynamic';
// Our main component
import { AppComponent } from './app/app.component';
bootstrap(AppComponent, []).catch(err => console.error(err));
app.component.ts
import { Component } from '#angular/core';
import { RiskListComponent } from './components/risks/risk-list.component';
import { DataTable, Column } from 'primeng/primeng';
#Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h1>{{pageTitle}}</h1>
<rm-risks> </rm-risks>
</div>
` ,
directives: [RiskListComponent, DataTable, Column]
})
export class AppComponent {
pageTitle: string = 'Test UK Trader';
}
risk-list.component.ts
import { Component } from '#angular/core'
import { DataTable, Column } from 'primeng/primeng';
#Component({
selector: 'rm-risks',
directives: [DataTable, Column],
templateUrl: '/app/risks/risk-list.component.html'
})
export class RiskListComponent {
pageTitle: string = 'Risk List';
risks: any[] = [
{
"riskId": 1,
"reference": "HISC9308336",
"insuredName": "SA 84161",
"inceptionDate": "March 19, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": "100",
"allocatedTo": "Broker User",
"allocatedCompany": "Broker"
},
{
"riskId": 2,
"reference": "HISC9308340",
"insuredName": "Upper Loi",
"inceptionDate": "April 25, 2016",
"riskType": "Quote",
"status": "Indication",
"grossPremium": "312.22",
"allocatedTo": "Andy Marples",
"allocatedCompany": "Broker"
}
];
}
risk-list.component.html
<h3 class="first">{{pageTitle}}</h3>
<p-dataTable [value]="risks" [rows]="10" [paginator]="true" [pageLinks]="3" [rowsPerPageOptions]="[5,10,20]">
<p-column field="reference" header="Reference"></p-column>
<p-column field="insuredName" header="Insured Name"></p-column>
<p-column field="inceptionDate" header="Inception Date"></p-column>
<p-column field="riskType" header="Risk Type"></p-column>
<p-column field="status" header="Status"></p-column>
<p-column field="grossPremium" header="Gross Premium"></p-column>
<p-column field="allocatedTo" header="Allocated To"></p-column>
<p-column field="allocatedCompany" header="Allocated Company"></p-column>
</p-dataTable>
tsconfig.js
{
"compileOnSave": false,
"compilerOptions": {
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
"outDir": "../dist/",
"rootDir": ".",
"sourceMap": true,
"target": "es6",
"inlineSources": true
},
"exclude": [
"node_modules",
"typings",
"typings/main",
"typings/main.d.ts"
]
}
I would move the main.ts file under the app folder and import it this way:
<script>
System.import('app/main').catch(function (err) { console.error(err); });
</script>
You also need to have this configuration for SystemJS:
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
my error:
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (traceur, line 0)
Error: invoke#http://localhost:3000/node_modules/zone.js/dist/zone.js:323:34
runGuarded#http://localhost:3000/node_modules/zone.js/dist/zone.js:230:54
http://localhost:3000/node_modules/zone.js/dist/zone.js:206:40
Error loading http://localhost:3000/traceur
Error loading http://localhost:3000/ts/app.js
my folder structure is like this:
index.htmn
package.json
systemjs.config.js
typings.json
->ts/app.js
->node_modules/*
->typings/*
I tried changing destination path of my source app file but did not have any luck.
index.html
<html>
<head>
<title>First App - Hello world</title>
<script src="node_modules/es6-shim/es6-shim.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').then(null, console.error.bind(console));
</script>
<body>
<gs-test></gs-test>
</body>
</html>
in systemjs.config file i tried changing map part for my app but still the same.
I also tried with changing different version of libraries but did not help.
systemjs.config.js
// See also: https://angular.io/docs/ts/latest/quickstart.html
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'ts',
'rxjs': 'node_modules/rxjs',
'#angular': 'node_modules/#angular'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'app.js', defaultExtension: 'js'},
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' }
};
var packageNames = [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router',
'#angular/router-deprecated',
'#angular/testing',
'#angular/upgrade',
];
// add package entries for angular packages in the form '#angular/common': { main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages
}
// filterSystemConfig - index.html's chance to modify config before we register it.
if (global.filterSystemConfig) { global.filterSystemConfig(config); }
System.config(config);
})(this);
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude": [
"node_modules",
"typings/main",
"typings/main.d.ts"
]
}
could be something with typings but i guess then td file would be missing. I did "typing install" before starting first time app.
typings.json
{
"ambientDependencies": {
"es6-shim": "registry:dt/es6-shim#0.31.2+20160317120654",
"jasmine": "registry:dt/jasmine#2.2.0+20160412134438",
"node": "registry:dt/node#4.0.0+20160509154515"
}
}
Please let me know what could be wrong with my setup.
tnx!
miha
When my main.ts is to bootstrap app.ts, everything looks good.
main.ts
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from 'app/app';
import {ROUTER_PROVIDERS,ROUTER_DIRECTIVES} from 'angular2/router';
import {PLATFORM_DIRECTIVES,provide} from 'angular2/core';
bootstrap(AppComponent,
[ROUTER_PROVIDERS,
provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi:true}),
]);
app.ts
import {Component,View} from 'angular2/core';
import {RouteConfig} from 'angular2/router';
import {PlayerManagement} from './partials/player-management';
import {Report} from './partials/report';
#Component({
selector: 'my-app',
templateUrl: 'app/appComponent.html',
})
#RouteConfig([
{path:'/playerManagement', name: 'PlayerManagement', component: PlayerManagement},
{path:'/report', name: 'Report', component: Report}
])
export class AppComponent { }
But when I try to change to bootstrap another ts , login.ts, it gives me the error
angular2.js:22823 EXCEPTION: Token must be defined!
execute # main.ts:22
the code line is,
execute: function() {
bootstrap(LoginComponent, [ROUTER_PROVIDERS, provide(PLATFORM_DIRECTIVES, {
useValue: [ROUTER_DIRECTIVES],
multi: true
})]);
}
I compare the login.ts to app.ts , but no clue yet...
login.ts
import {Component,View} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
#Component({
selector: 'login',
templateUrl: 'app/login.html',
})
/*
#RouteConfig([
{path:'/app', name: 'AppComponent', component: AppComponent}
])
*/
export class LoginComponent { }
Updated main.ts
import {bootstrap} from 'angular2/platform/browser';
import {LoginComponent} from 'app/login';
import {ROUTER_PROVIDERS,ROUTER_DIRECTIVES} from 'angular2/router';
import {PLATFORM_DIRECTIVES,provide} from 'angular2/core';
bootstrap(LoginComponent,
[ROUTER_PROVIDERS,
provide(PLATFORM_DIRECTIVES, {useValue: [ROUTER_DIRECTIVES], multi:true}),
]);
index.html
<!doctype html>
<html lang="">
<head>
<base href="/">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>video-platform</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="lib/es6-shim.min.js"></script>
<script src="lib/angular2-polyfills.js"></script>
<script src="lib/traceur-runtime.js"></script>
<script src="lib/system-csp-production.src.js"></script>
<script src="lib/Reflect.js"></script>
<script src="lib/angular2.js"></script>
<script src="lib/Rx.js"></script>
<script src="lib/router.dev.js"></script>
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'ts'
}
}
});
System.import('app/main')
.then(null, console.error.bind(console));
</script>
</head>
<body>
<login>Loading....</login>
<my-app>Loading....</my-app>
</body>
</html>
My folder structure is
src
-app
--app.ts
--appComponent.html
--login.html
--login.ts
--main.ts
Strack trace updated.
STACKTRACE:
BrowserDomAdapter.logError # angular2.js:22823
ExceptionHandler.call # angular2.js:1165
(anonymous function) # angular2.js:12624
run # angular2-polyfills.js:138
(anonymous function) # angular2.js:13328
NgZone.run # angular2.js:13290
ApplicationRef_.bootstrap # angular2.js:12602
bootstrap # angular2.js:24543
execute # main.ts:22
ensureEvaluated # system-csp-production.src.js:2678
execute # system-csp-production.src.js:2796
doDynamicExecute # system-csp-production.src.js:715
link # system-csp-production.src.js:908
doLink # system-csp-production.src.js:569
updateLinkSetOnLoad # system-csp-production.src.js:617
(anonymous function) # system-csp-production.src.js:430
run # angular2-polyfills.js:138
zoneBoundFn # angular2-polyfills.js:111
lib$es6$promise$$internal$$tryCatch # angular2-polyfills.js:1511
lib$es6$promise$$internal$$invokeCallback # angular2-polyfills.js:1523
lib$es6$promise$$internal$$publish # angular2-polyfills.js:1494
(anonymous function) # angular2-polyfills.js:243
run # angular2-polyfills.js:138
zoneBoundFn # angular2-polyfills.js:111
lib$es6$promise$asap$$flush # angular2-polyfills.js:1305
I am using ts, but i have attached the js (main.js) here as well
System.register("app/main", ["angular2/platform/browser", "app/login", "angular2/router", "angular2/core"], function($__export) {
"use strict";
var bootstrap,
LoginComponent,
ROUTER_PROVIDERS,
ROUTER_DIRECTIVES,
PLATFORM_DIRECTIVES,
provide;
return {
setters: [function($__m) {
bootstrap = $__m.bootstrap;
}, function($__m) {
LoginComponent = $__m.LoginComponent;
}, function($__m) {
ROUTER_PROVIDERS = $__m.ROUTER_PROVIDERS;
ROUTER_DIRECTIVES = $__m.ROUTER_DIRECTIVES;
}, function($__m) {
PLATFORM_DIRECTIVES = $__m.PLATFORM_DIRECTIVES;
provide = $__m.provide;
}],
execute: function() {
bootstrap(LoginComponent, [ROUTER_PROVIDERS, provide(PLATFORM_DIRECTIVES, {
useValue: [ROUTER_DIRECTIVES],
multi: true
})]);
}
};
});
package.json
{
"name": "video-platform",
"version": "0.0.0",
"scripts": {
"build": "gulp",
"start": "gulp dev"
},
"dependencies": {
"angular2": "2.0.0-beta.2",
"traceur": "0.0.102",
"es6-promise": "^3.0.2",
"es6-shim": "^0.33.3",
"rxjs": "5.0.0-beta.0",
"zone.js": "0.5.10",
"reflect-metadata": "0.1.2",
"systemjs": "0.19.6"
},
"devDependencies": {
"gulp": "3.9.0",
"gulp-rename": "1.2.2",
"gulp-traceur": "0.17.2",
"gulp-webserver": "0.9.1",
"gulp-print":"*"
}
}
gulpfile.js
var gulp = require('gulp'),
rename = require('gulp-rename'),
traceur = require('gulp-traceur'),
webserver = require('gulp-webserver');
// run init tasks
gulp.task('default', ['dependencies', 'ts','html', 'css']);
// run development task
gulp.task('dev', ['watch', 'serve']);
// serve the build dir
gulp.task('serve', function () {
gulp.src('build')
.pipe(webserver({
open: true
}));
});
// watch for changes and run the relevant task
gulp.task('watch', function () {
//gulp.watch('src/**/*.js', ['js']);
gulp.watch('src/**/*.ts', ['ts']);
gulp.watch('src/**/*.html', ['html']);
gulp.watch('src/**/*.css', ['css']);
});
// move dependencies into build dir
gulp.task('dependencies', function () {
return gulp.src([
'node_modules/traceur/bin/traceur-runtime.js',
'node_modules/systemjs/dist/system-csp-production.src.js',
'node_modules/systemjs/dist/system.js',
'node_modules/reflect-metadata/Reflect.js',
'node_modules/angular2/bundles/angular2.js',
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/es6-shim/es6-shim.min.js',
'node_modules/es6-shim/es6-shim.map',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js'
])
.pipe(gulp.dest('build/lib'));
});
// transpile & move js
gulp.task('js', function () {
return gulp.src('src/**/*.js')
.pipe(rename({
extname: ''
}))
.pipe(traceur({
modules: 'instantiate',
moduleName: true,
annotations: true,
types: true,
memberVariables: true
}))
.pipe(rename({
extname: '.js'
}))
.pipe(gulp.dest('build'));
});
// transpile & move ts
gulp.task('ts', function () {
return gulp.src('src/**/*.ts')
.pipe(rename({
extname: ''
}))
.pipe(traceur({
modules: 'instantiate',
moduleName: true,
annotations: true,
types: true,
memberVariables: true
}))
.pipe(rename({
extname: '.ts'
}))
.pipe(gulp.dest('build'));
});
// move html
gulp.task('html', function () {
return gulp.src('src/**/*.html')
.pipe(gulp.dest('build'))
});
// move css
gulp.task('css', function () {
return gulp.src('src/**/*.css')
.pipe(gulp.dest('build'))
});
I use webpack to build React components.
Here is the JSX file:
// index.js
var React = require('react');
var ReactDOM = require('react-dom');
var renderHelloComponnet = function(id) {
ReactDOM.render(
<h1>Hello, World!</h1>,
document.getElementById(id)
);
}
Then, I want to call the function renderHelloComponnet in html
I have the config file for webpack:
module.exports = {
entry: {
index: './src/index.js'
},
output: {
path: __dirname + '/build',
filename: '[name].bundle.js',
libraryTarget: "var",
library: ["ABC"],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: { presets:['react'] }
}
]
}
}
However I can't render my component in html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script type="text/javascript" src="./build/index.bundle.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/javascript">
ABC.renderHelloComponnet('example');
</script>
</body>
</html>
I get the error: TypeError: ABC.renderHelloComponnet is not a function
What you export in your module.exports is what you get in your library var. So if in your index.js you export renderHelloComponent:
module.exports = renderHelloComponent;
then in your ABC var you'll get the function:
<script type="text/javascript">
ABC('example');
</script>
If you want your library var to actually have the renderHelloComponent method you can export an object with this function inside:
module.exports = {
renderHelloComponent: renderHelloComponent
}
Then you will be able to do this:
<script>
ABC.renderHelloComponent('example');
</script>