Cannot browserify materialize-css npm module - npm

I am new to materialize css framework. I am using laravel-elixir 4.0.0 with gulp to browserify the installed npm materialize-css module.
Here are my configurations
package.json
{
"private": true,
"devDependencies": {
"gulp": "^3.8.8"
},
"dependencies": {
"jquery": "^2.2.0",
"laravel-elixir": "^4.0.0",
"materialize-css": "^0.97.5"
}
}
gulpfile.js
var gulp = require('gulp');
var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| ELIXIR ASSET MANAGEMENT
|--------------------------------------------------------------------------
*/
elixir.config.sourcemaps = true;
// Set the path for compiled assets
var build_path = "public/compiled/";
elixir(function(mix) {
/*
|----------------------------------------------------------------------
| Javascript browserification
|----------------------------------------------------------------------
*/
mix.browserify(
"app.js",
build_path + "app.js"
);
});
app.js
window.$ = window.jQuery = require('jquery')
require('materialize-css');
However, when I run gulp command it returns the following errors:-
gulp-notify: [Laravel Elixir] Browserify Failed!: Cannot find module
'jQuery' from
'/var/www/laravel5/node_modules/materialize-css/bin'
My node versions:-
node v5.6.0, npm v3.6.0

Note: I'm not using Elixir. Only Gulp, browserify and materialize-css.
This is what I have in my project using materialize-css:
in the package.json I have added to the devDependencies list browserify-shim, and configured it:
"dependencies":{
"materialize-css": "xx.yy.zz",
"jquery": "xx.yy.zz",
...
},
"devDependencies": {
"browserify": "xx.yy.zz"
"browserify-shim": "xx.yy.zz"
...
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
"materialize": "./node_modules/materialize-css/bin/materialize.js"
},
"browserify-shim": {
"jquery": "$",
"materialize": "materialize"
},
"browserify": {
"transform": [
"browserify-shim"
]
},
...
in the app.js file I'm then importing jQuery and materialize as usual:
var $ = require('jquery');
require('materialize');
Then just used the regular recipe for gulp and browserify to build them.

Related

npm install can't find all packages and when forced to install npm start has issues

I bought this template and am having troubles with npm install and npm start. Do you all have tips on fixing the vulnerabilties when I install and then after that is there something I need to do to get npm start to work?
When I run npm install I get the following output:
PS C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0> npm install
up to date, audited 935 packages in 2s
61 packages are looking for funding
run `npm fund` for details
8 vulnerabilities (1 moderate, 7 high)
To address issues that do not require attention, run:
npm audit fix
To address all issues possible (including breaking changes), run:
npm audit fix --force
Some issues need review, and may require choosing
a different dependency.
Run `npm audit` for details.
PS C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0>
I can force the install with npm install --no-audit, but when I try npm start I get the following:
PS C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0> npm start
npm ERR! Missing script: "start"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR! npm star # Mark your favorite packages
npm ERR! npm stars # View packages marked as favorites
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\jonat\AppData\Local\npm-cache\_logs\2022-09-02T21_58_05_615Z-debug-0.log
Upon looking in my package.json it appears start is missing from the scripts section. I added "start": "./bin/www" to the package.json and it gave me the following output:
PS C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0> npm start
> boland-2.0#1.0.0 start
> node ./bin/www
node:internal/modules/cjs/loader:959
throw err;
^
Error: Cannot find module 'C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0\bin\www'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
at Function.Module._load (node:internal/modules/cjs/loader:804:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
PS C:\Users\jonat\OneDrive\Documents\Projects\Boland_Front_end\boland_ecommerce_theme_bs5_v2.0>
here is package.json
{
"name": "boland-2.0",
"version": "1.0.0",
"description": "",
"main": "gulpfile.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
#I added the below line to try and get npm start to work
"start": "node ./bin/www"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.16.0",
"#babel/preset-env": "^7.16.4",
"babelify": "^10.0.0",
"browser-sync": "^2.27.7",
"browserify": "^17.0.0",
"del": "^6.0.0",
"glob": "^7.2.0",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^6.1.0",
"gulp-clean-css": "^4.3.0",
"gulp-cli": "^2.3.0",
"gulp-file-include": "^2.3.0",
"gulp-rename": "^2.0.0",
"gulp-sass": "^5.0.0",
"gulp-sourcemaps": "^3.0.0",
"gulp-uglify": "^3.0.2",
"sass": "^1.45.0",
"sass-migrator": "^1.5.3",
"vinyl-buffer": "^1.0.1",
"vinyl-source-stream": "^2.0.0"
},
"dependencies": {
"aos": "^3.0.0-beta.6",
"bootstrap": "^5.1.3",
"imagesloaded": "^4.1.4",
"jquery": "^3.6.0",
"jquery-countdown": "^2.2.0",
"jquery-nice-select": "^1.1.0",
"masonry-layout": "^4.2.2",
"popper.js": "^1.16.1",
"simplebar": "^5.3.6",
"smooth-scroll": "^16.1.3",
"sticky-js": "^1.3.0",
"swiper": "^7.3.1"
}
}
here is my gulpfile.js:
'use strict';
var { src, dest, series, parallel, watch } = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sass = require('gulp-sass')(require('sass'));
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var browsersync = require('browser-sync').create();
var uglify = require('gulp-uglify');
var cleanCSS = require('gulp-clean-css');
var del = require('del');
var glob = require('glob');
var autoprefixer = require('gulp-autoprefixer');
var fileinclude = require('gulp-file-include');
// Define paths
var paths = {
here: './',
base: {
base: {
dest: './'
},
node: {
dest: './node_modules'
}
},
src: {
base: {
dir: './',
files: './**/*',
dest: './public'
},
html: {
dir: './html/*.html',
files: './html/**/*.html',
dest: './public',
cleanHtml: './public/*.html',
},
js: {
dir: './js',
files: './js/custom/**/*.js',
theme: './js/theme.js',
dest: './public/assets/js',
clean: './public/assets/js/*.js',
},
scss: {
dir: './scss',
files: './scss/**/*',
main: './scss/*.scss',
dest: './public/assets/css'
},
vendor: {
files: [
"./node_modules/jquery/dist/jquery.min.js",
"./node_modules/jquery-countdown/dist/jquery.countdown.min.js",
"./node_modules/swiper/swiper-bundle.min.js",
"./node_modules/imagesloaded/imagesloaded.pkgd.min.js",
"./node_modules/simplebar/dist/simplebar.min.js",
"./node_modules/masonry-layout/dist/masonry.pkgd.min.js",
"./node_modules/jquery-nice-select/js/jquery.nice-select.min.js"
],
css: [
"./node_modules/swiper/swiper-bundle.min.css",
"./node_modules/simplebar/dist/simplebar.min.css",
"./node_modules/jquery-nice-select/css/nice-select.css"
],
dest: './public/assets/vendor/node_modules/js',
destCss: './public/assets/vendor/node_modules/css',
clean: './public/assets/vendor/node_modules'
}
}
};
//Clean public folder html,css,js
function cleanUp() {
return del([paths.src.js.clean,paths.src.vendor.clean, paths.src.scss.dest, paths.src.html.cleanHtml]);
};
//Copy vendor to assets/vendor folder
function copyVendor() {
return src(paths.src.vendor.files)
.pipe(dest(paths.src.vendor.dest))
.pipe(browsersync.stream());
}
function copyVendorCss() {
return src(paths.src.vendor.css)
.pipe(dest(paths.src.vendor.destCss))
.pipe(browsersync.stream());
}
//BrowserSync
function browserSync(done) {
browsersync.init({
server: {
baseDir: [paths.src.base.dest]
},
});
done();
};
function browsersyncReload(done) {
browsersync.reload();
done();
};
function bundleJs() {
var files = glob.sync('./js/theme.js');
return (
browserify({
entries: files,
debug: true,
cache: {},
packageCache: {}
}).transform(babelify, {
global: true,
presets: ["#babel/preset-env"]
})
.bundle()
.pipe(source('theme.bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(sourcemaps.write(paths.here))
.pipe(dest(paths.src.js.dest))
);
};
//styles
function buildCss() {
return src(paths.src.scss.main)
.pipe(sourcemaps.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(sourcemaps.write(paths.here))
.pipe(dest(paths.src.scss.dest))
.pipe(browsersync.stream());
};
function minifyCss() {
return src(paths.src.scss.main)
.pipe(sourcemaps.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoprefixer())
.pipe(cleanCSS())
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write(paths.here))
.pipe(dest(paths.src.scss.dest))
.pipe(browsersync.stream());
};
//Copy html
function html() {
return src(paths.src.html.dir)
.pipe(fileinclude({
prefix: '##',
basepath: '#file',
indent: true
}))
.pipe(dest(paths.src.html.dest))
.pipe(browsersync.reload({
stream: true
}));
};
function watchFiles() {
watch(paths.src.scss.files, series(buildCss, minifyCss));
watch(paths.src.js.files, series(bundleJs, browsersyncReload));
watch(paths.src.html.files, series(html, browsersyncReload));
};
exports.watchFiles = watch;
exports.buildCss = buildCss;
exports.bundleJs = bundleJs;
exports.minifyCss = minifyCss;
exports.html = html;
exports.copyVendor = copyVendor;
exports.copyVendorCss = copyVendorCss;
exports.cleanUp = cleanUp;
exports.default = series(cleanUp, html, buildCss, minifyCss, copyVendor, copyVendorCss, bundleJs, parallel(browserSync, watchFiles));

Why babelConfig not working in webpack encore?

I want to add support for async / await functions for my project.
I install
"#babel/core": "^7.2.0",
"#babel/plugin-transform-runtime": "^7.2.0",
"#babel/preset-env": "^7.2.0",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-stage-2": "^7.0.0",
"#babel/runtime": "^7.2.0",
It's my webpack.config.js
const Encore = require('#symfony/webpack-encore');
Encore
.setOutputPath('public/build')
.setPublicPath('/build')
.addEntry('app', './assets/app.js')
.enableSourceMaps(!Encore.isProduction())
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableVueLoader()
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})
;
const config = Encore.getWebpackConfig();
config.externals = {
mode: 'development',
// global app config object
config: JSON.stringify({
apiUrl: 'http://localhost:80',
devServer: {
public: 'http://localhost:3000',
disableHostCheck: true,
},
})
};
config.node = {
fs: "empty"
};
module.exports = config;
When I run a server dev, I get an error.
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Duplicate plugin/preset detected.
If you'd like to use two separate instances of a plugin,
they need separate names, e.g.
plugins: [
['some-plugin', {}],
['some-plugin', {}, 'some unique name'],
]
I can not understand what the problem is.
I also created a .babelrc file and wrote the same configuration in it. But unfortunately, this did not help (
Use .babelrc for change babel config like this. This file should be in your project root
{
"plugins": ["#babel/plugin-transform-runtime"],
"presets": [
[
"#babel/preset-env",
...
],
...
]
}
Then remove this from your webpack.config.js
.configureBabel(function(babelConfig) {
babelConfig.presets.push('#babel/preset-env');
babelConfig.presets.push('#babel/preset-stage-2');
babelConfig.plugins.push('#babel/plugin-transform-runtime');
})

Proper Jest configuration with React-native 0.56

After upgrading to react-native 0.56 I'm experiencing tons of babel reated errors on jest specs that used to run just fine.
I realize that react-native 0.56 requires babel7 and that's probably related but I don't have enough experience/understaanding in babel to figure out what I'm missing.
Some error examples:
/xxx/spec/Bootstrap.test.js:6
import thunk from 'redux-thunk';
^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
another:
import { rootReducer } from '../store';
^
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
My package.json jest config is as follows:
"jest": {
"preset": "react-native",
"collectCoverage": true,
"coverageReporters": [
"cobertura",
"lcov"
],
"coverageDirectory": "coverage",
"globals": {
"__TEST__": true
},
"moduleNameMapper": {
"styled-components": "<rootDir>/node_modules/styled-components/dist/styled-components.native.cjs.js"
},
"moduleDirectories": [
"node_modules",
"/"
],
"transformIgnorePatterns": [
"node_modules/(?!react-native|react-navigation)/"
],
"setupFiles": [
"jest-localstorage-mock",
"./node_modules/appcenter/test/AppCenterMock.js",
"./node_modules/appcenter-analytics/test/AppCenterAnalyticsMock.js",
"./node_modules/appcenter-crashes/test/AppCenterCrashesMock.js"
]
},
.babelrc is defined as follows:
{
"presets": ["react-native"],
"env": {
"development": {
"plugins": ["transform-class-properties"]
},
"test": {
"plugins": ["transform-class-properties"]
}
}
}
I also have the following devdependencies:
"#babel/core": "^7.0.0-beta.52",
"babel-core": "^7.0.0-beta.52",
"babel-eslint": "~8.2.5",
"babel-plugin-module-resolver": "^3.1.1",
"babel-plugin-transform-class-properties": "~6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.5",
"babel-preset-expo": "~4.0.0",
"babel-preset-react-native": "^5.0.1",
"babel-preset-react-native-stage-0": "^1.0.1",
"babel-preset-stage-0": "^6.24.1",
I've tried several approaches but couldn't progress much.
Besides the jest environment, the application runs fine.
Details of the workaround I did to move on, while 0.57 wasn't ready:
Basically I had to create 2 config files:
jest-acceptance.config (with the following relevant snippets)
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/custom_b7_processor.js"
},
"testRegex": "(/test/.*|(\\.|/)spec)\\.js$",
jest-unit.config (with the following relevant snippets)
"preset": "react-native",
"testRegex": "(/test/.*|(\\.|/)test)\\.js$",
That custom_b7_processor, is some sort of internal code from react-native:
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* #format
* #flow
*/
/* eslint-disable */
'use strict';
const {transformSync: babelTransformSync} = require('#babel/core');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const babelRegisterOnly = require('metro-babel-register');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const generate = require('#babel/generator').default;
const nodeFiles = RegExp(
[
'/local-cli/',
'/metro(?:-[^/]*)?/', // metro, metro-core, metro-source-map, metro-etc
].join('|'),
);
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
/* $FlowFixMe(site=react_native_oss) */
const transformer = require('metro/src/reactNativeTransformer');
module.exports = {
process(src /*: string */, file /*: string */) {
if (nodeFiles.test(file)) {
// node specific transforms only
return babelTransformSync(
src,
Object.assign(
{filename: file},
{sourceType: 'script', ...nodeOptions, ast: false},
),
).code;
}
const {ast} = transformer.transform({
filename: file,
localPath: file,
options: {
ast: true, // needed for open source (?) https://github.com/facebook/react-native/commit/f8d6b97140cffe8d18b2558f94570c8d1b410d5c#r28647044
dev: true,
inlineRequires: true,
platform: '',
projectRoot: '',
retainLines: true,
sourceType: 'unambiguous', // b7 required. detects module vs script mode
},
src,
plugins: [
[require('#babel/plugin-transform-block-scoping')],
// the flow strip types plugin must go BEFORE class properties!
// there'll be a test case that fails if you don't.
[require('#babel/plugin-transform-flow-strip-types')],
[
require('#babel/plugin-proposal-class-properties'),
// use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
{loose: true},
],
[require('#babel/plugin-transform-computed-properties')],
[require('#babel/plugin-transform-destructuring')],
[require('#babel/plugin-transform-function-name')],
[require('#babel/plugin-transform-literals')],
[require('#babel/plugin-transform-parameters')],
[require('#babel/plugin-transform-shorthand-properties')],
[require('#babel/plugin-transform-react-jsx')],
[require('#babel/plugin-transform-regenerator')],
[require('#babel/plugin-transform-sticky-regex')],
[require('#babel/plugin-transform-unicode-regex')],
[
require('#babel/plugin-transform-modules-commonjs'),
{strict: false, allowTopLevelThis: true},
],
[require('#babel/plugin-transform-classes')],
[require('#babel/plugin-transform-arrow-functions')],
[require('#babel/plugin-transform-spread')],
[require('#babel/plugin-proposal-object-rest-spread')],
[
require('#babel/plugin-transform-template-literals'),
{loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
],
[require('#babel/plugin-transform-exponentiation-operator')],
[require('#babel/plugin-transform-object-assign')],
[require('#babel/plugin-transform-for-of'), {loose: true}],
[require('#babel/plugin-transform-react-display-name')],
[require('#babel/plugin-transform-react-jsx-source')],
],
});
return generate(
ast,
{
code: true,
comments: false,
compact: false,
filename: file,
retainLines: true,
sourceFileName: file,
sourceMaps: true,
},
src,
).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
require.resolve('metro/src/reactNativeTransformer'),
require.resolve('#babel/core/package.json'),
]),
};
At my .babelrc I had to include the following:
"presets": ["./node_modules/babel-preset-react-native-b6"],
That is pointing to a fork I made of the babel preset that React-native was using at 0.56-
https://github.com/lhrolim/babel-preset-react-native.
At my package.json I had te following babel dependencies
"babel-preset-react-native": "~5.0.2",
"babel-preset-react-native-b6": "github:lhrolim/babel-preset-react-native",
The test scripts I used then:
"test": "npm run test-acc && npm run test-unit",
"test-acc": "jest --config=jest_acceptance-config.json",
"test-unit": "jest --config=jest_unit-config.json",
I believe there might be some redundancies here and there, but that's what worked for me.

npm run build for React app using incorrect path for index.js source

My npm run build fails with this:
✖ Building demo
Failed to compile with 1 error.
ERROR in multi ./node_modules/nwb/polyfills.js ./demo/src/index.js
Module not found: Error: Can't resolve '/Users/david/git/demoapp/demo/src/index.js' in '/Users/david/git/demoapp'
# multi ./node_modules/nwb/polyfills.js ./demo/src/index.js
Error running command: Build failed with errors.
Error: Build failed with errors.
at /Users/david/git/demoapp/node_modules/nwb/lib/webpackBuild.js:82:17
at emitRecords.err (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:269:13)
at Compiler.emitRecords (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:375:38)
at emitAssets.err (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:262:10)
at applyPluginsAsyncSeries1.err (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:368:12)
at next (/Users/david/git/demoapp/node_modules/tapable/lib/Tapable.js:218:11)
at Compiler.compiler.plugin (/Users/david/git/demoapp/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
at Compiler.applyPluginsAsyncSeries1 (/Users/david/git/demoapp/node_modules/tapable/lib/Tapable.js:222:13)
at Compiler.afterEmit (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:365:9)
at require.forEach.err (/Users/david/git/demoapp/node_modules/webpack/lib/Compiler.js:354:15)
at /Users/david/git/demoapp/node_modules/async/dist/async.js:473:16
at iteratorCallback (/Users/david/git/demoapp/node_modules/async/dist/async.js:1050:13)
at /Users/david/git/demoapp/node_modules/async/dist/async.js:958:16
at /Users/david/git/demoapp/node_modules/graceful-fs/graceful-fs.js:43:10
at FSReqWrap.oncomplete (fs.js:112:15)`
This is incorrect in '/Users/david/git/demoapp' because the index is in /Users/david/git/demoapp/src or /Users/david/git/demoapp/lib for the ES5 version, /Users/david/git/demoapp/es for the ES6 version
My nwb.config.js looks like this:
const path = require('path');
function excludeNodeModulesExcept (modules) {
var pathSep = path.sep;
if (pathSep === '\\') { // must be quoted for use in a regexp:
pathSep = '\\\\';
}
var moduleRegExps = modules.map(function (modName) { return new RegExp("node_modules" + pathSep + modName);});
return function (modulePath) {
if (/node_modules/.test(modulePath)) {
for (var i = 0; i < moduleRegExps.length; i++) {
if (moduleRegExps[i].test(modulePath)) {
console.log("Allowed babel transpiling of " + modulePath);
return false;
}
}
return true;
}
return false;
};
}
module.exports = {
type: 'react-component',
npm: {
esModules: true,
umd: false
},
webpack: {
rules: {
babel: {
exclude: excludeNodeModulesExcept(['kontraktor-client', 'kontraktor-common']),
options: {
babelrc: false,
cacheDirectory: true
}
}
}
}
};
The relevant part of my package.json looks like this:
{
"name": "demoapp",
"version": "1.0.0",
"description": "Demo App",
"main": "lib/index.js",
"module": "es/index.js",
"files": [
"css",
"es",
"lib",
"umd"
],
"scripts": {
"build": "nwb build-react-component",
"images": "node imagesServer/index.js",
"serve": "nwb serve-react-app",
"clean": "nwb clean-module",
"start": "npm-run-all --parallel serve images",
"test": "nwb test-react",
"test:coverage": "nwb test-react --coverage",
"test:watch": "nwb test-react --server"
},
Is there a way of specify to nwb where the source index.js is located? I want to build a ES5 version of this React application.
Another confusion is that some posts and tutorials states that a directory named 'dist' is used to output the built code from 'npm run build'?
react-app doesnot support importing files outside src folder. so short answer ;you will have to eject'
or you can use npm link but your module must be exporting es5 beacuse again react-app will not transpile it for you.

How to include Underscore.js in angular2 project built using angular-cli

I want to include underscore.js inside angular2 project built using angular-cli.
Till now I am unable to do so. I tried so far:
1- npm install underscore --save
2- tsd install underscore
3- script src="node_modules/underscore/underscore.js" , reference in index.html
4- inside system-config.js
/** Map relative paths to URLs. */
var map = {
'underscore': '../node_modules/underscore/underscore.js'
};
/** User packages configuration. */
var packages = {
'underscore': '../node_modules/underscore/underscore.js'
};
5- import * as _ from 'underscore';
But underscore.js is not getting copied in 'dist' directory during run-time , and browser complain of not finding underscore.js. I think I am missing something at Point#4.
Any help is much appreciated as I am beginning learning angular2.
Please remember that this project is made by angular-cli, and not by any other seed project. Other than Underscore.js, project is working fine.
[EDIT]
package.json has "underscore": "^1.8.3" in dependencies
Using Angular CLI 1.0.0-rc.1, the recommended solution is described here:
Angular2 2.4 How to load external libraries sush as Underscore into angular2.
npm install underscore --save // save to dependencies: required to run
npm install #types/underscore --save-dev // save to dev dependencies: required in dev mode
Then in your component class:
import * as _ from 'underscore';
...
subtitle = _.head(['xyz'])
Alternatively, there is another way to load "static" scripts in angular-cli as described here https://www.npmjs.com/package/angular-cli#global-library-installation:
In .angular-cli.json, add it to the scripts array:
"scripts": ["../node_modules/underscore/underscore.js"]
This will load underscore.js, but this is not a good way to make it available for use in your typescript classes.
install underscore using npm
Go to yourappname/src/typings.d.ts and add this line
declare module 'underscore';
then run ng build
Angular 2 full 3 file snippets
package.json
{
"name": "angular2-quickstart",
"version": "1.0.0",
"scripts": {
"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ",
"lite": "lite-server",
"postinstall": "typings install",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings"
},
"license": "ISC",
"dependencies": {
"#angular/common": "2.0.0",
"#angular/compiler": "2.0.0",
"#angular/core": "2.0.0",
"#angular/forms": "2.0.0",
"#angular/http": "2.0.0",
"#angular/platform-browser": "2.0.0",
"#angular/platform-browser-dynamic": "2.0.0",
"#angular/router": "3.0.0",
"#angular/upgrade": "2.0.0",
"angular2-in-memory-web-api": "0.0.20",
"bootstrap": "^3.3.6",
"core-js": "^2.4.1",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.12",
"systemjs": "0.19.27",
"tsd": "^0.6.5",
"underscore": "^1.8.3",
"zone.js": "^0.6.23"
},
"devDependencies": {
"concurrently": "^2.2.0",
"lite-server": "^2.2.2",
"typescript": "^2.0.2",
"typings": "^1.3.2"
}
}
systemjs.config.js
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'node_modules/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'underscore': 'npm:underscore',
'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'underscore':{
main: './underscore.js',
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
}
}
typings.json
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160725163759",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160909174046"
},
"ambientDependencies": {
"underscore": "github:DefinitelyTyped/DefinitelyTyped/underscore/underscore.d.ts#f0990e288ac73d593e982995947567aa2643b828"
}
}
1- npm install underscore --save
2- tsd install underscore (if tsd not install first install that)
3) now do npm install
4) then npm start
install underscore:
npm i underscore --save
in angular-cli.json:
"scripts": [
"../node_modules/underscore/underscore-min.js",
...
],
after run command:
ng build
in component:
declare var _: any;
#Component({...})
Do you have in your project a file called Package.json?
If Yes, you can try to add this line
"underscore": "^1.8.3",
in the dependencies of this file.
Modifications in system-config.ts
var map = {
"underscore": "node_modules/underscore",
};
var packages = {
'underscore': { main: 'index.js', defaultExtension: 'js' }
};
var packageNames = [
'#angular/common',
'#angular/compiler',
'#angular/core',
'#angular/http',
'#angular/platform-browser',
'#angular/platform-browser-dynamic',
'#angular/router-deprecated',
'#angular/testing',
'#angular/upgrade',
];
packageNames.forEach(function(pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});
var config = {
map: map,
packages: packages,
paths: {
"underscore": "/node_modules/underscore.js"
}
};
And to do a npm install after that.
I think you might have missed a step? Did you remember to setup underscore in the "angular-cli-build.js" file? This step tells clingon to put underscore in the vendor folder (/dist/vendor).
Here's how I got underscore working.
Install underscore and typings:
npm install underscore --save
typings install underscore --save --ambient
Setting up underscore in "angular-cli-build.js":
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(js|js.map)',
'rxjs/**/*.+(js|js.map)',
'#angular/**/*.+(js|js.map)',
'moment/moment.js',
'underscore/underscore.js'
]
});
};
Then underscore get compiled to the vendor folder (/dist/vendor), and now it's possible to point to this location from the system.config.ts file:
const map: any = {
"underscore": "vendor/underscore/underscore.js",
"moment": "vendor/moment/moments.js"
};
/** User packages configuration. */
const packages: any = {
'underscore': {
format: 'cjs'
},
'moment': {
format: 'cjs'
}
};
Remember to use the hole path including the .js hope this helps :)
I did the same as with moment, from the docs: https://github.com/angular/angular-cli/wiki/3rd-party-libs
I am using Angular-cli, all I did was to add this line in package.json
"underscore": "^1.8.3",
and then I Run:
1. npm install underscore --save
2. npm install
and it worked...