My package.json:
...
"scripts": {
"build": "gulp && webpack",
"webpack": "webpack"
},
...
"dependencies": {
"scrollto": "git://github.com/flesler/jquery.scrollTo.git" // ???
}
...
my backbone view:
const Backbone = require('backbone');
const _ = require('underscore');
const $ = require('jquery');
require('scrollto'); // ???
...
_handleError(error) {
if (error) {
$('#header').focus();
$(window).scrollTo('#header'); // ????
} else {
...
}
},
...
Command:
gulp && webpack
Error:
Module not found: Error: Cannot resolve module 'scrollto' in /home/me/src/myproject/src/dashboard/static/js/views/query
Anything missing or wrong?
Thanks
UPDATE
Fixed:
"jquery.scrollto": "^2.0.0"
require('jquery.scrollto');
Related
Why do I keep getting error message "SyntaxError: Cannot use import statement outside a module" when I use Babel and Jest?
I have a super simple app that contains two modules:
// moduleTwo.mjs:
let testFuncOneModTwo = () => {
return ('String generated by fn in moduleTwo.mjs')
}
export {testFuncOneModTwo }
/////////////
// moduleOne.mjs:
import {testFuncOneModTwo} from './moduleTwo.mjs'
let testFuncOneModOne = () => {
return (testFuncOneModTwo())
}
export { testFuncOneModOne }
//////////////
Here's my Jest test file:
// myTest.test.js:
import * as myImports from './moduleOne.mjs';
test('tests fn in module that calls fn in another module.', () => {
expect(myImports.testFuncOneModOne()).toEqual( 'String generated by fn in
moduleTwo.mjs' );
});
/////////////
// babel.config.json:
{
"presets": ["#babel/preset-env"]
}
// package.json:
{
"name": "JestIsVeryTesting",
"version": "1.0.0",
"description": "",
"main": "moduleOne.mjs",
"scripts": {
"test": "jest --coverage "
},
"jest": {
"transform": {
"^.+\\.js?$": "babel-jest"
}
},
"dependencies": {
"#babel/runtime": "^7.18.6"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/plugin-transform-runtime": "^7.18.6",
"#babel/preset-env": "^7.18.6",
"babel": "^6.23.0",
"babel-jest": "^28.1.2",
"jest": "^28.1.2"
}
}
// The error message (edited by me):
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. ...
...
...
Details:
/xxx/xxx/xxx/xxx/moduleOne.mjs:91
import { testFuncOneModTwo } from './moduleTwo.mjs';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 |
> 2 | import * as myImports from './moduleOne.mjs';
| ^
3 |
4 | test('tests fn in module that calls fn in another module.', () => {
5 | expect(myImports.testFuncOneModOne()).toEqual( 'This string returned by a function in moduleTwo.mjs' );
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (myTest.test.js:2:1)
Help would be much appreciated as this is driving me mad.
In case anyone is interested I solved the problem myself in the end:
To the top level of the package.json file I added:
"type": "module"
This tells node that all files in the project that end with '.js' are ES6 files
I changed the extensions of my modules to '.js'
(so that
'moduleOne.mjs' became 'moduleOne.js'
and
'moduleTwo.mjs' became 'moduleTwo.js'
)
This is in keeping with the value of the package.json file's "jest" field, which has value:
"transform": {
"^.+\\.js?$": "babel-jest"
}
Im creating an NFL football simulator in nodejs and am having trouble exporting one of my variables. As you can see in my get_teams.js i make many HTTP requests. I then process the responseArr and format the data. Where I am running into an issue is when I try and export the sorted_teams_array. you can find this code at the very bottom of get_teams.js.
I then try and import this array into tester.js and console log it. I will eventually use this file to inject a mongo database with the array, but for now am just trying to console log it and cannot get it to work. I am using the --experimental-modules in my npm scripts when I run npm run tester, and still nothing. Any help would be great! I am a noobie so please no hate!
get_teams.js
import axios from 'axios';
import Nfl_team from '../models/teamModel.js';
import Offensive_stats from '../models/offensiveStatsModel.js';
import Defensive_stats from '../models/defensiveStatsModel.js';
import Game_stats from '../models/gameStatsModel.js';
import colors from 'colors';
import dotenv from 'dotenv';
dotenv.config();
const teams = {};
function get_teams() {
axios.all([
axios.get(`https://api.sportsdata.io/api/nfl/fantasy/json/Standings/${process.env.SEASON}?key=${process.env.API_KEY}`),
// ... many more gets
])
.then(function (responseArr) {
responseArr[0].data.forEach(element => {
teams[element.Team] = new Nfl_team(element.Team, element.Name, element.Wins, element.Losses, element.Ties,
element.Percentage, element.DivisionWins, element.DivisionLosses, element.DivisionTies,
element.PointsFor, element.PointsAgainst)
});
// many more forEach blocks on responseArr[1, 2, 3...]
/* power rating algorithm logic
_____________________________________________ */
const teams_array = Object.entries(teams);
export const sorted_teams_array = teams_array.sort((a, b) => {
if (a[1].average_victory_margin > b[1].average_victory_margin) return -1;
if (a[1].average_victory_margin < b[1].average_victory_margin) return 1;
return 0;
})
console.log(sorted_teams_array);
teams_array.forEach(element => {
console.log(`average victory margin for ${element[0]} = ${element[1].average_victory_margin}`)
});
})
.catch(function (error) {
// handle error
console.log(error);
})
}
get_teams();
tester.js
import { sorted_teams_array } from './get_teams';
console.log(sorted_teams_array);
/// returns
(node:58769) ExperimentalWarning: The ESM module loader is experimental.
internal/modules/esm/resolve.js:61
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module /Users/jojovera/Documents/nflSIMULATION/teams/get_teams imported from /Users/jojovera/Documents/nflSIMULATION/teams/tester.js
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:61:13)
at Loader.resolve (internal/modules/esm/loader.js:94:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:240:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
package.json
{
"name": "optionsscript",
"version": "1.0.0",
"description": "",
"main": "app.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node --experimental-modules app.js",
"afc_west": "node --experimental-modules ../nflSIMULATION/teams/afc_west.js",
"get_teams": "node --experimental-modules ../nflSIMULATION/teams/get_teams.js",
"tester": "node --experimental-modules ../nflSIMULATION/teams/tester.js",
"get_offensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_offensive_stats.js",
"get_defensive_stats": "node --experimental-modules ../nflSIMULATION/teams/get_defensive_stats.js",
"get_victory_margin": "node --experimental-modules ../nflSIMULATION/teams/get_victory_margin.js",
"power_rank": "node --experimental-modules ../nflSIMULATION/teams/power_rank.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.0",
"cheerio": "^1.0.0-rc.5",
"colors": "^1.4.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"nodemon": "^2.0.6",
"stats-lite": "^2.2.0",
"terminal-kit": "^1.44.0",
"tofixed": "^1.0.0"
}
}
As addressed in the comments and chat, there were two issues: ESM isn't supported in Node 12, so an update to 15 fixed that. The other issue is that nothing was validly exported from get_teams: import and export are top-level keywords, and the export was taking place inside a .then. These minor changes allow the function to be imported and its result used in the tests:
export function get_teams() {
return axios.all([
/// rest of code
return sorted_teams_array;
})
.catch(function (error) {
// handle error
console.log(error);
})
}
Usage example:
import { get_teams } from './get_teams'
get_teams.then((teams) => {
teams.forEach(console.log)
})
I have made a npm module in a private git repo and I'm trying to access it in another application.
I'm using reactjs, webpack and npm
So I have the module:
dist
src
| form-mapper
| formMapper.js
| myfile.js
| index.js
package.json
webpack.config.js
Webpack.config.js is like this:
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js'
}
}
Package.json is like this:
{
"name": "my-awesome-module",
"version": "1.0.0",
"license": "ISC",
"main": "./dist/bundle.js",
"scripts": {
"prepare": "npm run build",
"build": "webpack --mode production",
"start": "webpack-dev-server --open --mode development"
},
"devDependencies": {
"webpack": "^4.43.0",
"webpack-cli": "^4.3.0",
"webpack-dev-server": "^3.11.0"
}
}
formMapper.js as 2 functions that I'm trying to export:
export function mapForm() {
// some code
}
export function mapUiFormToBackEnd() {
// some code
}
And index.js:
import * as FormMapper from './form-mapper/formMapper'
export { mapForm, mapUiFormToBackEnd } from './form-mapper/formMapper'
export default FormMapper
I've tried a lot of things in index.js so I let everything here just to show you guys what I've already tried.
In my app that needs to use this module I import the module using npm (git+ssh://...) which is working since I can see my module inside node_modules.
When I try to import using:
import FormMapper from 'my-awesome-module'
componentDidMount() {
FormMapper.mapForm()
}
I have this error:
my-awesome-module__WEBPACK_IMPORTED_MODULE_2___default.a.mapForm is not a function
That's my first time trying to create my own npm module and I clearly don't understand everything. I tried several guide but it seems I'm not abla to make it right.
Thanks for the help.
Edit:
When I log my import in my application
import FormMapper from 'my-awesome-module'
componentDidMount() {
console.log(FormMapper)
FormMapper.mapForm()
}
I see an empty object {} getting logged
update your formMapper.js in a more proper way
const mapForm = () => {
// Code here
}
const mapUiFormToBackEnd = () => {
// Code here
}
module.exports = {mapForm, mapUiFormToBackEnd }
on your index.js
// If you just want the mapForm and mapUiFormToBackEnd
const {mapForm, mapUiFormToBackEnd} = require('./form-mapper/formMapper');
// Or if you just want to get all it's fucntion just import it like this
const FormMapper = require('./form-mapper/formMapper') // No need for *
// export the whole FormMapper
module.exports = FormMapper;
// If you want to export a specific functions inside FormMapper
module.exports = {mapForm, mapUiFormToBackEnd }
How can I import markdown files as strings in Next.js to work on client and server side?
You can configure your Next.js webpack loaders to load markdown files and return them as strings, for example:
docs/home.md
# Home
This is my **awesome** home!
pages/index.js
import React from 'react';
import markdown from '../docs/home.md';
export default () => {
return (
<div>
<pre>{markdown}</pre>
<small><i>Import and render markdown using Next.js</i></small>
</div>
);
};
package.json
{
"name": "example",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"file-loader": "^1.1.6",
"next": "^4.2.1",
"raw-loader": "^0.5.1",
"react": "^16.2.0",
"react-dom": "^16.2.0"
}
}
next.config.js
module.exports = {
webpack: (config) => {
return Object.assign({}, config, {
externals: Object.assign({}, config.externals, {
fs: 'fs',
}),
module: Object.assign({}, config.module, {
rules: config.module.rules.concat([
{
test: /\.md$/,
loader: 'emit-file-loader',
options: {
name: 'dist/[path][name].[ext]',
},
},
{
test: /\.md$/,
loader: 'raw-loader',
}
]),
}),
});
}
};
When running:
$ npm run dev
Something like this would appear:
With the markdown string you can do whatever you would like. For example, process it with marksy.
Quicker and "Next.js way" is to use plugin next-mdx
Documentation: https://github.com/vercel/next.js/tree/canary/packages/next-mdx
// next.config.js
const withMDX = require('#zeit/next-mdx')({
extension: /\.mdx?$/
})
module.exports = withMDX({
pageExtensions: ['js', 'jsx', 'mdx']
})
Just install raw-loader
npm install --save raw-loader
then edit your next.config.js
webpack: (config) => {
config.module.rules.push({
test: /\.md$/,
use: 'raw-loader',
});
return config;
},
Updates: emit-file-loader not strictly required, raw-loader deprecated in favor of asset modules
Some updates to https://stackoverflow.com/a/47954368/895245 possibly due to newer developments:
asset modules superseded raw-loader: https://stackoverflow.com/a/47954368/895245 No need to install any extra packages for that anyomore
emit-file-loader does not seem necessary anymore, not sure if it was needed, or if it is for something more specialized
so we can simplify things slightly to:
pages/index.js
import world from '../world.md'
export default function IndexPage() {
return <div>hello {world}</div>
}
next.config.js
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.module.rules.push(
{
test: /\.md$/,
// This is the asset module.
type: 'asset/source',
}
)
return config
},
}
package.json
{
"name": "test",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "12.2.0",
"react": "17.0.2",
"react-dom": "17.0.2"
}
}
world.md
my md world
Getting it to work from Typescript
Unfortunately boch raw-loader and asset modules require a bit more work from typescript: https://github.com/webpack-contrib/raw-loader/issues/56#issuecomment-423640398 You have to create a file:
global.d.ts
declare module '*.md'
Otherwise the import will fail with:
Type error: Cannot find module '../world.md' or its corresponding type declarations.
Full example:
global.d.ts
declare module '*.md'
pages/index.tsx
import world from '../world.md'
export default function IndexPage() {
const what: string = 'my'
// Would fail on build as desired.
// const what2: int = 'world2'
return <div>hello {what} {world}</div>
}
next.config.js
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.module.rules.push(
{
test: /\.md$/,
type: 'asset/source',
}
)
return config
},
}
package.json
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start",
"type-check": "tsc"
},
"dependencies": {
"next": "v12.2.0",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"#types/node": "12.12.21",
"#types/react": "17.0.2",
"#types/react-dom": "17.0.1",
"typescript": "4.0"
}
}
world.md
my md world
How can I import jQuery as the dependency for bootstrap in ES6?
I tried with:
import {$,jQuery} from 'jquery';
import bootstrap from 'bootstrap';
But I always get this error:
transition.js:59 Uncaught ReferenceError: jQuery is not defined
Which points to this file:
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
Any ideas?
EDIT:
my gulp file:
var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var gutil = require('gulp-util');
gulp.task('es6', function() {
browserify({
entries: 'js/app.js',
debug: true
})
.transform(babelify, { presets: ['es2015'] })
.on('error',gutil.log)
.bundle()
.on('error',gutil.log)
.pipe(source('compile.js'))
.pipe(gulp.dest('js'));
});
gulp.task('default', ['es6']);
EDIT 2:
package.json:
{
"name": "es6",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-preset-es2015": "^6.16.0",
"babelify": "^7.3.0",
"browserify": "^13.1.0",
"gulp": "^3.9.1",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.7",
"pump": "^1.0.1",
"vinyl-source-stream": "^1.1.0"
},
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
},
"browserify-shim": {
"jquery": "$", // or change it to jQuery
},
"browserify": {
"transform": [
"browserify-shim"
]
}
}
error:
Starting 'build'... events.js:160
throw er; // Unhandled 'error' event
^
Error: SyntaxError: Unexpected token } in JSON at position 526 while
parsing json file
I've tried this answer and it worked.
// webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
In general the destructuring you are doing in the import is not right, as the $ or jQuery object is the main one:
import $ from 'jquery';
// or
import jQuery from 'jquery'
In your case you are dealing with a module (boostrap-transition) which does want jQuery in the global scope to be used.
I had a similar issue some time ago with the materialize module too on this thing.
If you are using webpack you can follow #galkowskit answer steps.
In case you are using browserify instead, what you need is a browserify transform as the follow:
"browser": {
"jquery": "./node_modules/jquery/dist/jquery.js",
},
"browserify-shim": {
"jquery": "$", // or change it to jQuery
},
"browserify": {
"transform": [
"browserify-shim"
]
}
You can put this inside your package.json file: when Gulp is going to call browserify it will read your package.json for configuration tips and execute this shim for jQuery.
In Webpack I usually use (webpack.config.js):
externals: {
jquery: "jQuery"
}
And then:
import jQuery from 'jQuery';
You could also try:
import * as jQuery from 'jQuery';
If you are using curley bracket in es6 you are saying you want only that segment from several segment this module returns.
Jquery expose only one thing so you could do:
import $ from 'jquery';
Or
import jQuery from 'jquery';
It will always expose to one default variable
import jQuery from 'jquery';
or
import $ from 'jquery';