I have made small app using Angular2, I am getting following error in Chrome browser:
zone.js:323 Error: ReferenceError: packages is not defined
at materialComponents.forEach.name (http://localhost:4200/system-config.js:17:5)
at Array.forEach (native)
at eval (http://localhost:4200/system-config.js:16:20)
Evaluating http://localhost:4200/system-config.js
Error loading http://localhost:4200/system-config.js
Basically, this error happening on the following code.
system-config.ts
/** Map relative paths to URLs. */
const map: any = {
'#angular2-material': 'vendor/#angular2-material', // created in vendor directory
'ng2-material': 'vendor/ng2-material',
'moment': 'vendor/moment/moment.js'
};
/** User packages configuration. */
const packages: any = {};
// Material Components
const materialComponents = [
'core',
'checkbox',
'input',
'progress-bar',
'progress-circle',
'radio',
'sidenav',
'slide-toggle',
'toolbar'
];
materialComponents.forEach(name => { //Here it says package not defined
packages[`#angular2-material/${name}`] = {
format: 'cjs',
defaultExtension: 'js',
main: name + '.js'
};
});
Thanks
Related
I'm new to frontend world, I would like to write some test using protractor-image-comparison. I followed installation instructions from https://github.com/wswebcreation/protractor-image-comparison. Also I make configuration according to this page.
When I try to use functions form this lib I get following error: "TypeError: Cannot read property 'checkFullPageScreen' of undefined". I'm getting a warrning in protractor.conf.js in
const protractorImageComparison = require('protractor-image-comparison');
"Could not find a declaration file for module
'protractor-image-comparison'.
'/home/rafa/repos/example/src/example/node_modules/protractor-image-comparison/index.js'
implicitly has an 'any' type. Try npm install
#types/protractor-image-comparison if it exists or add a new
declaration (.d.ts) file containing declare module
'protractor-image-comparison';"
So I did, I made simple *.d.ts file with `declare module protractor-image-comparison' in it, but it didn't solve the problem just the warning disappear. It's propably the config issue, but I can't handle it or maybe I made wrong declaration. This is my config file :
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const reporter = require("cucumber-html-reporter");
const path = require("path");
const jsonReports = path.join(process.cwd(), "/reports/json");
const htmlReports = path.join(process.cwd(), "/reports/html");
const targetJson = jsonReports + "/cucumber_report.json";
const cucumberReporterOptions = {
jsonFile: targetJson,
output: htmlReports + "/cucumber_reporter.html",
reportSuiteAsScenarios: true,
theme: "bootstrap",
};
exports.config = {
allScriptsTimeout: 110000,
restartBrowserBetweenTests: true,
//SELENIUM_PROMISE_MANAGER: false,
specs: [
'./e2e/**/login.feature'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
cucumberOpts: {
format: "json:" + targetJson,
require: ['./e2e/steps/*.ts', "./e2e/timeout.ts"],
},
useAllAngular2AppRoots: true,
onPrepare: () => {
browser.ignoreSynchronization = true;
const protractorImageComparison = require('protractor-image-comparison');
browser.protractorImageComparison = new protractorImageComparison(
{
baselineFolder: "report/screens/baseline",
screenshotPath: "report/screens/actual"
}
);
},
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e'
});
},
onComplete: () => {
reporter.generate(cucumberReporterOptions);
}
};
Ok, I solved it. The reason why I was getting this TypeError is that I lunched few test scenarios and onPrepare was lunched only in the begining. I move config of protractor-image-comparison to cucumber befor hook and everything works fine now.
I'm developing a website with webpack. When I have a code like this:
import $ from 'jquery';
function foo() {};
module.exports = foo;
I got the error Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'.
Turns out that changing import $ from 'jquery' to var $ = require('jquery') don't cause any errors.
Why import with module.exports causes this error? Is anything wrong in using require instead?
You can't mix import and module.exports. In the import world, you need to export things.
// Change this
module.exports = foo;
// To this
export default foo;
This happens if other modules down stream have an unexpected require tree. Babel changes require to import where it isn't supposed to which causes the aforementioned issue #Matthew Herbst. To solve this add "sourceType": "unambiguous" to your babelrc file or babel.config.js so that #babel/plugin-transform-runtime won't do this change of require expression to import in your commonjs files. eg:
module.exports = {
presets: [
'#quasar/babel-preset-app'
],
"sourceType": "unambiguous"
}
You can use require with export. But not import and module.exports.
In my react-native-web case, just use an additional webpack rule, then the TypeError: Cannot assign to read only property 'exports' of object is fixed. Maybe you can ref to it.
npm install --save-dev react-app-rewired
Create a config-overrides.js in your project root
// used by react-app-rewired
const webpack = require('webpack');
const path = require('path');
module.exports = {
webpack: function (config, env) {
config.module.rules[1].use[0].options.baseConfig.extends = [
path.resolve('.eslintrc.js'),
];
// To let alias like 'react-native/Libraries/Components/StaticRenderer'
// take effect, must set it before alias 'react-native'
delete config.resolve.alias['react-native'];
config.resolve.alias['react-native/Libraries/Components/StaticRenderer'] =
'react-native-web/dist/vendor/react-native/StaticRenderer';
config.resolve.alias['react-native'] = path.resolve(
'web/aliases/react-native',
);
// Let's force our code to bundle using the same bundler react native does.
config.plugins.push(
new webpack.DefinePlugin({
__DEV__: env === 'development',
}),
);
// Need this rule to prevent `Attempted import error: 'SOME' is not exported from` when `react-app-rewired build`
// Need this rule to prevent `TypeError: Cannot assign to read only property 'exports' of object` when `react-app-rewired start`
config.module.rules.push({
test: /\.(js|tsx?)$/,
// You can exclude the exclude property if you don't want to keep adding individual node_modules
// just keep an eye on how it effects your build times, for this example it's negligible
// exclude: /node_modules[/\\](?!#react-navigation|react-native-gesture-handler|react-native-screens)/,
use: {
loader: 'babel-loader',
},
});
return config;
},
paths: function (paths, env) {
paths.appIndexJs = path.resolve('index.web.js');
paths.appSrc = path.resolve('.');
paths.moduleFileExtensions.push('ios.js');
return paths;
},
};
Also create a web/aliases/react-native/index.js
// ref to https://levelup.gitconnected.com/react-native-typescript-and-react-native-web-an-arduous-but-rewarding-journey-8f46090ca56b
import {Text as RNText, Image as RNImage} from 'react-native-web';
// Let's export everything from react-native-web
export * from 'react-native-web';
// And let's stub out everything that's missing!
export const ViewPropTypes = {
style: () => {},
};
RNText.propTypes = {
style: () => {},
};
RNImage.propTypes = {
style: () => {},
source: () => {},
};
export const Text = RNText;
export const Image = RNImage;
// export const ToolbarAndroid = {};
export const requireNativeComponent = () => {};
Now you can just run react-app-rewired start instead of react-scripts start
I just started to use webpack and am trying to load jquery synchronously
Here is my main.js
var $ = require('jquery');
require('javascript/index.js');
require('less/index.less');
and here is my webpack.config
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var path = require('path');
module.exports = {
entry: './assets/javascript/main.js',
output: {
path: './assets',
filename: '/javascript/bundle.js'
},
module : {
loaders : [
{
test: /\.css/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader")
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader")
}
]
},
plugins: [
new ExtractTextPlugin("/css/[name].css")
],
resolve : {
root: path.resolve('./assets'),
extensions: ['', '.js', '.less']
}
};
my index.js looks like this
$(document).ready(function () {
var body = $('body');
var backgrounds = new Array(
'url(./../images/bg1.jpg)' ,
'url(./../images/bg2.jpg)' ,
'url(./../images/bg3.jpg)' ,
'url(./../images/bg4.jpg)'
);
var current = 0;
function nextBackground() {
console.log("Changing bg");
current++;
current = current % backgrounds.length;
body.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 1000);
body.css('background-image', backgrounds[0]);
});
and on execution throws the error
Uncaught ReferenceError: $ is not defined
I really don't understand this error since if I look into the generated bundle.js Jquery clearly is getting defined.
I already tried to add this to my resolve:
resolve : {
root: path.resolve('./assets'),
extensions: ['', '.js', '.less'],
alias: {
jquery: "jquery"
}
}
but the error is still persistent
Edit: Here is a snipped of the created bundle.js
var $ = __webpack_require__(2);
__webpack_require__(3);
__webpack_require__(4);
According to your code, you need to add this to your index.js
var $ = require('jquery');
That's because when you used the webpack to build your code, each files(e.g index.js) would be wrap into a function which is defined by webpack.
So all the variables defined in your main.js are not accessable to index.js, coz they are now in different function which are not sharing the same scope.
You can either expose jquery to global(window) use the expose-loader or you need to require the jquery manually.
Hope this can solve your problem. : )
What you are looking for is the ProvidePlugin:
Automatically loaded modules. Module (value) is loaded when the identifier (key) is used as free variable in a module. The identifier is filled with the exports of the loaded module.
For example:
Add this plugin to your config:
new webpack.ProvidePlugin({
$: "jquery"
})
Somewhere in your code:
// in a module
$("#item") // <= just works
// $ is automatically set to the exports of module "jquery"
Make sure you got jquery installed via NPM
I'm trying to load qwest.js using the dojo (ArcGIS) AMD loader but am getting a multipleDefine error.
require([
// `../vendor/react/react.js`, // this works fine
`../vendor/qwest/qwest.min.js`, // this causes error
], (
// React,
qwest,
) => { ... })
At first I thought it was because I added it as a package in the dojo config object, but doing this throws the exact same error.
Config:
require({
async: true
, parseOnLoad: true
, packages: [{
name: `app`
, location: `${location.pathname}js`
, main: `main`
}]
}, [`app`])
I don't really know why you get that error but you can workaround it by letting qwest thinking commonjs should be used instead of amd:
//for testing purpose
require({
packages: [{ name: 'pyrsmk', location: 'https://rawgit.com/pyrsmk'}]
});
//the trick is to let qwest think you use commonjs instead of amd
window.module = {};
require(['pyrsmk/qwest/master/build/qwest.min'], function(qwest) {
qwest = module.exports;
delete window.module;
console.log(qwest);
});
<script src="https://rawgit.com/dojo/dojo/1.10/dojo.js"></script>
I'm trying to compile two different JS files using broccoli-requirejs. A logical way to go about this seemed to be to run the requireJs filter on my scripts tree twice, with two different configurations. Doing so produces some really strange errors that, to me, resembles a race condition or something.
See below for Broccoli config and error output.
var compileCoffee = require("broccoli-coffee"),
compileStatic = require("broccoli-static-compiler"),
mergeTrees = require("broccoli-merge-trees"),
requireJs = require("broccoli-requirejs"),
_ = require("lodash");
var scripts = compileStatic("app/coffee", {
srcDir: "/",
destDir: "scripts"
});
scripts = compileCoffee(scripts, {bare: true});
var rjsOptions = {
baseUrl: "scripts",
inlineText: true,
optimize: "uglify",
stubModules: ["text"],
paths: {
knockout: "empty:"
}
};
var fooScript = requireJs(scripts, {
requirejs: _.extend(rjsOptions, {
include: ["foo"],
insertRequire: ["main"],
mainConfigFile: "scripts/main.js",
name: "main",
out: "scripts/main.js"
})
});
var barScript = requireJs(scripts, {
requirejs: _.extend(rjsOptions, {
insertRequire: ["bar"],
mainConfigFile: "scripts/main.js",
name: "bar",
out: "scripts/bar.js"
})
});
module.exports = mergeTrees([
fooScript,
barScript
]);
I get the following error when building this:
$ broccoli build build
Error: Merge error: file scripts/bar.js exists in /home/fredrik/app/tmp/require_js_filter-tmp_dest_dir-yMHQNi3F.tmp and /home/fredrik/app/tmp/require_js_filter-tmp_dest_dir-C8Wv970J.tmp
Pass option { overwrite: true } to mergeTrees in order to have the latter file win.
at mergeRelativePath (/home/fredrik/app/node_modules/broccoli-merge-trees/index.js:98:21)
at mergeRelativePath (/home/fredrik/app/node_modules/broccoli-merge-trees/index.js:122:17)
at /home/fredrik/app/node_modules/broccoli-merge-trees/index.js:23:5
at $$$internal$$tryCatch (/home/fredrik/app/node_modules/broccoli-merge-trees/node_modules/promise-map-series/node_modules/rsvp/dist/rsvp.js:490:16)
at $$$internal$$invokeCallback (/home/fredrik/app/node_modules/broccoli-merge-trees/node_modules/promise-map-series/node_modules/rsvp/dist/rsvp.js:502:17)
at $$$internal$$publish (/home/fredrik/app/node_modules/broccoli-merge-trees/node_modules/promise-map-series/node_modules/rsvp/dist/rsvp.js:473:11)
at Object.$$rsvp$asap$$flush [as _onImmediate] (/home/fredrik/app/node_modules/broccoli-merge-trees/node_modules/promise-map-series/node_modules/rsvp/dist/rsvp.js:1581:9)
at processImmediate [as _immediateCallback] (timers.js:345:15)
Build failed
And if I do pass {overwrite: true} to the mergeTrees call, I get the output of the first requireJs call (ie. the scripts/main.js), but with the filename bar.js.
It seems my problem was totally unrelated to both Broccoli and broccoli-requirejs. It's my call to _.extend that overwrites rjsConfig object. And since the actual r.js optimization with its of the config object doesn't happen before the trees are merged, the result of the second _.extend call is passed in twice.
Simply changing the order of the arguments passed to _.extend made it work as expected:
var fooScript = requireJs(scripts, {
requirejs: _.extend({
include: ["foo"],
insertRequire: ["main"],
mainConfigFile: "scripts/main.js",
name: "main",
out: "scripts/main.js"
}, rjsOptions)
});