I just currently working on Express js+typescript with Sequelize ORM and want to bundle using Webpack. The problem is I got warning and fail each time trying to bundle.
Here is my warning/error message:
WARNING in ./~/sequelize/lib/dialects/mysql/connection-manager.js
Module not found: Error: Can't resolve 'mysql' in 'D:\Project\MyMe\node_modules\sequelize\lib\dialects\mysql'
# ./~/sequelize/lib/dialects/mysql/connection-manager.js 20:17-33
# ./~/sequelize/lib/dialects/mysql/index.js
# ./~/sequelize/lib/sequelize.js
# ./~/sequelize/index.js
# ./src/server/models/index.js
# ./src/server/controllers/TopUp.ts
# ./src/server/controllers/index.ts
# ./src/router/router.ts
# ./src/App.ts
# ./src/index.ts
WARNING in ./~/express/lib/view.js
80:29-41 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/sequelize.js
686:60-73 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/mysql/connection-manager.js
18:17-60 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/mssql/connection-manager.js
18:15-71 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/postgres/connection-manager.js
20:14-57 Critical dependency: the request of a dependency is an expression
WARNING in ./~/sequelize/lib/dialects/sqlite/connection-manager.js
22:15-71 Critical dependency: the request of a dependency is an expression
ERROR in ./~/pg/lib/native/index.js
Module not found: Error: Can't resolve 'pg-native' in 'D:\Project\MyMe\node_modules\pg\lib\native'
# ./~/pg/lib/native/index.js 9:13-33
# ./~/pg/lib/index.js
# ./~/sequelize/lib/dialects/postgres/connection-manager.js
# ./~/sequelize/lib/dialects/postgres/index.js
# ./~/sequelize/lib/sequelize.js
# ./~/sequelize/index.js
# ./src/server/models/index.js
# ./src/server/controllers/TopUp.ts
# ./src/server/controllers/index.ts
# ./src/router/router.ts
# ./src/App.ts
# ./src/index.ts
Here is my package.json:
"devDependencies": {
"#types/body-parser": "^1.16.3",
"#types/chai": "^3.5.2",
"#types/chai-http": "0.0.30",
"#types/debug": "0.0.29",
"#types/express": "^4.0.35",
"#types/mocha": "^2.2.41",
"#types/morgan": "^1.7.32",
"#types/node": "^7.0.18",
"chai": "^3.5.0",
"chai-http": "^3.0.0",
"mocha": "^3.3.0",
"ts-loader": "^2.0.3",
"ts-node": "^3.0.4",
"typescript": "^2.3.2",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5"
},
"dependencies": {
"body-parser": "^1.17.1",
"debug": "^2.6.6",
"express": "^4.15.2",
"morgan": "^1.8.1",
"pg": "^6.1.5",
"pg-hstore": "^2.3.2",
"sequelize": "^3.30.4"
}
Below is my webpack.config.js
var path = require('path');
var webpack = require('webpack')
var fs = require('fs')
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: './src/index.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
loaders: [
{
test: /\.ts?$/,
loader: 'ts-loader',
exclude: /node_modules/,
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
devServer: {
port: 3000
},
target: 'node'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
minimize: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Fyi, before I'm adding Sequelize to my project its bundle fine with Express+typescript only. I know there is something I'm missing because I'm still new to webpack env. Thanks.
I think that's because sequalize is made for nodejs. Not every module is "compatible". So you can't "just" hang it in there. I never used sequalizer in this setup, but it makes sense. I found an article that shows the steps needed to incorporate it:
https://www.google.nl/amp/s/scotch.io/amp/tutorials/creating-an-angularjs-application-with-sequelize-part-1
Hope this helps you.
Related
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));
I have few serverless project created without using ES6/ES7 support. In our new project, i wanted to integrate this with serverless but not able to get it going.
Here is my serverless.yml file
#sls offline start --skipCacheInvalidation
service: test
provider:
name: aws
runtime: nodejs8.10 # set node.js runtime
memorySize: 1024 # set the maximum memory of the Lambdas in Megabytes
timeout: 300 # the timeout is 10 seconds (default is 6 seconds)
stage: ${opt:stage, 'dev'} #${self:provider.stage} # setting the env stage to dev, this will be visible in the routes
region: us-east-1
logRetentionInDays: 14 # Set the default RetentionInDays for a CloudWatch LogGroup
deploymentBucket:
name: api-test
# custom:
# stage: ${opt:stage, self:provider.stage}
environment: ${file(env.yml):${self:provider.stage}}
plugins:
- serverless-webpack
- serverless-offline
# serverless optimization
package:
individually: true
# serverless-webpack configuration
# Enable auto-packing of external modules
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
functions:
createCampaign:
handler: src/Campaign.CreateCampaign
name : campaign-createcampaign-${self:provider.stage} #custom lambda name instead of auto generated
description: To create campaign
events:
- http:
path: campaign
method: post
cors: true
getAllCampaign:
handler: src/Campaign.GetCampaign
name : campaign-getall-${self:provider.stage} #custom lambda name instead of auto generated
description: To retrieve all campaign
events:
- http:
path: campaign
method: get
cors: true
My campaign.js is under /src folder in my code. I tried this using https://medium.com/#kilgarenone/write-es6-es7-in-serverless-framework-using-babel-7-and-webpack-4-5bd742168e1a
My webpack config is following.
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
//entry: slsw.lib.entries,
entry: {handler : './src/Campaign.js'},
target: 'node',
// Generate sourcemaps for proper error messages
devtool: 'source-map',
// Since 'aws-sdk' is not compatible with webpack,
// we exclude all node dependencies
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
optimization: {
// We no not want to minimize our code.
minimize: false,
},
performance: {
// Turn off size warnings for entry points
hints: false,
},
// Run babel on all .js files and skip those in node_modules
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: __dirname,
exclude: /node_modules/,
},
],
},
};
My package.json is
{
"name": "orim-api",
"version": "1.0.0",
"description": "",
"main": "handler.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.4",
"#babel/preset-env": "^7.4.4",
"babel-loader": "^8.0.5",
"babel-plugin-source-map-support": "^2.0.1",
"serverless-offline": "^4.9.4",
"serverless-webpack": "^5.3.0",
"webpack": "^4.30.0",
"webpack-node-externals": "^1.7.2"
},
"dependencies": {
"dotenv": "^7.0.0",
"mongoose": "^5.5.5",
"source-map-support": "^0.5.12"
}
}
My .babelrc file is
{
"plugins": ["source-map-support", "transform-runtime"],
"presets": [
["env", { "node": "8.10" }],
"stage-3"
]
}
When i execute sls offline start --SkipCacheInvalidateion, i get following warning
WARNING in ./src/Campaign.js 5:12-29
"export 'connectToDatabase' was not found in '../db'
And it seems like webpack and babel-loader isn't transpile my entire code
From the doc, this is something you can try:
// webpack.config.js
const _ = require('lodash');
const slsw = require('serverless-webpack');
module.exports = {
...
entry: _.assign({
handler : './src/Campaign.js'
}, slsw.lib.entries),
...
};
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');
})
I am using a modified aurelia-navigation-skeleton to build my project (modified because I am also adding a servicestack backend).
First the error:
[16:33:59] Error tracing npm:crypto-browserify#3.11.0/example/bundle.js at file:///C:/MyProjectPath/jspm_packages/npm/crypto-browserify#3.11.0/example/bundle.js
Error: Unable to calculate canonical name to bundle file:///test.js. Ensure that this module sits within the baseURL or a wildcard path config.
at getCanonicalNamePlain (C:\MyProjectPath\node_modules\systemjs-builder\lib\utils.js:227:13)
at getCanonicalName (C:\MyProjectPath\node_modules\systemjs-builder\lib\utils.js:150:19)
at C:\MyProjectPath\node_modules\systemjs-builder\lib\trace.js:565:36
at run (C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\es6.promise.js:87:22)
at C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\es6.promise.js:100:28
at flush (C:\MyProjectPath\node_modules\karma\node_modules\core-js\modules\_microtask.js:18:9)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
I am not using crpto-browserify myself so I assume it is a dependency somewhere either within the skeleton or within Aurelia itself.
Project layout:
ProjectRoot
-- build (from skeleton)
-- tasks
-- src (standard aurelia layout here)
-- app.js/main.js/app.html
-- views
-- resources
-- etc...
-- default.html
-- node_modules
-- jspm_packages
-- jspm.config.js
-- package.json
jspm.config.js
System.config({
defaultJSExtensions: true,
transpiler: "typescript",
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"aurelia-animator-css": "npm:aurelia-animator-css#1.0.1",
"aurelia-api": "npm:aurelia-api#3.1.1",
"aurelia-authentication": "npm:aurelia-authentication#3.3.0",
"aurelia-bootstrapper": "npm:aurelia-bootstrapper#2.1.1",
"aurelia-dependency-injection": "npm:aurelia-dependency-injection#1.3.0",
"aurelia-dialog": "npm:aurelia-dialog#1.0.0-beta.3.0.1",
"aurelia-fetch-client": "npm:aurelia-fetch-client#1.1.1",
"aurelia-framework": "npm:aurelia-framework#1.1.0",
"aurelia-pal-browser": "npm:aurelia-pal-browser#1.1.0",
"aurelia-router": "npm:aurelia-router#1.2.1",
"aurelia-templating-binding": "npm:aurelia-templating-binding#1.3.0",
"bootstrap": "github:twbs/bootstrap#3.3.7",
"font-awesome": "npm:font-awesome#4.7.0",
"moment": "npm:moment#2.17.1",
"numeral": "npm:numeral#2.0.4",
"servicestack-client": "npm:servicestack-client#0.0.26",
"text": "github:systemjs/plugin-text#0.0.9",
"typescript": "npm:typescript#2.2.1",
"github:jspm/nodelibs-assert#0.1.0": {
"assert": "npm:assert#1.4.1"
},
...
...
...
}
bundle.js
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var bundles = require('../bundles.js');
var config = {
force: true,
baseURL: '.',
configPath: './jspm.config.js',
bundles: bundles.bundles
};
gulp.task('bundle', ['build'], function() {
return bundler.bundle(config);
});
gulp.task('unbundle', function() {
return bundler.unbundle(config);
});
bundles.js
module.exports = {
"force": true,
"packagePath": ".",
"configPath": [ // SystemJS/JSPM configuration files
"./jspm.config.js"
],
"injectionConfigPath": "./jspm.config.js",
"bundles": {
"dist/app-build": {
"includes": [
"[**/*.js]",
"**/*.html!text",
"**/*.css!text"
],
"options": {
"inject": true,
"minify": true,
"depCache": false,
"rev": true
}
},
"dist/aurelia": {
"includes": [
"aurelia-api",
"aurelia-authentication",
"aurelia-framework",
"aurelia-pal-browser",
"aurelia-bootstrapper",
"aurelia-dependency-injection",
"aurelia-dialog",
"aurelia-fetch-client",
"aurelia-router",
"aurelia-animator-css",
"aurelia-templating-binding",
"aurelia-polyfills",
"aurelia-templating-binding",
"aurelia-templating-resources",
"aurelia-templating-router",
"aurelia-loader-default",
"aurelia-history-browser",
"aurelia-logging-console",
"moment",
"numeral",
"servicestack-client",
"bootstrap",
"bootstrap/css/bootstrap.css!text"
],
"options": {
"inject": true,
"minify": true,
"depCache": false,
"rev": true
}
}
}
};
The error means nothing to me and other posts about this error talk about changing the BaseURL, but I don't know what I would change it to to make this work. Any help would be appreciated.
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...