Require in react can't resolve path - javascript

I'm trying to use tracking-js library in my project I'm using react but I dont know if I'm doing anything wrong but keep showing that the module is not found, I already check my package.json and the module install. So this is how I require the module:
const tracking = require("tracking");
what am I doing wrong?

For node, including node-based build tools, first make sure that the module is present. Keep in mind that require does not care about the package.json of your app, only about the module files being present.
Check if node_modules/tracking is present.
Make sure the "main" JS file can be found. If there's a node_modules/tracking/package.json file, see if it has a main property and if the file it references exists. If there is no main property, make sure there's an index.js in the root of the module directory.
If all this is fine and you're getting the module not found error at runtime in client-side JavaScript, then your bundling config may be incorrect, and your webpack/browserify/whatever config will have to be scrutinized for bugs.

Related

Recommended PhpStorm configuration for Shopware?

I have noticed the JavaScript classes not resolving when typing the following in a Shopware JavaScript plugin:
This got me thinking. Is there any way to solve this not resolving? Are there any other configuration recommendations for Shopware development in PhpStorm? I've already seen some in the Shopware Academy backend course and the documentation, but might there be more?
Updated answer, quick solution
In your project directory tree find src/Storefront/Resources/app/storefront, right click the folder, Mark directory as, Resource Root. This should make the aliased modules resolved.
Older answer, possible permanent fix
Theoretically PhpStorm should be able to resolve the aliases defined in src/Storefront/Resources/app/storefront/webpack.config.js.
However it fails analyzing that file:
Webpack
Can't analyze webpack.config.js: coding assistance will ignore module resolution rules in this file.
Possible reasons: this file is not a valid webpack configuration file or its format is not currently supported by the IDE.
Error details: Definition file does not exists
I found the reason is line 465 of src/Storefront/Resources/app/storefront/webpack.config.js:
const injector = new WebpackPluginInjector('var/plugins.json', webpackConfig, 'storefront');
Replacing that line with the following line made the modules using the aliases resolvable:
const injector = new WebpackPluginInjector(path.resolve(projectRootPath, 'var/plugins.json'), webpackConfig, 'storefront');
If you're using the development template and the Shopware mono-repo is located in the platform diretory this change will make Webpack look for platform/var/plugins.json instead. So either copy or symlink var/plugins.json to that location.
This is obviously just a temporary workaround and needs to properly be fixed eventually.
As a side note: The separate webpack.config.js for the administration also fails to be analyzed by PhpStorm as of now. So this won't fix non-resolvable aliases for PhpStorm in the administration.

How to configure Webpack to build without importing an external module?

I Have a third-party library needed to be used in project ts code, which is added to the application using a CDN path in the HTML. And this library is exporting a window variable, which is used in the code.
The package is not available as an npm module. While running the webpack build it's failing with the following error message:
error TS2304: Cannot find name 'CUSTOM_WINDOW_VARIABLE'.
I have added this in name in the webpackconfig.js file as :
externals: {
CUSTOM_WINDOW_VARIABLE: "CUSTOM_WINDOW_VARIABLE",
},
But still getting the same error.
How to tell webpack to ignore these global variables while building. Or convert them to window.CUSTOM_WINDOW_VARIABLE from CUSTOM_WINDOW_VARIABLE.
As I know your problem is not about webpack at all. The issue is most likely throwing from ts-loader which uses tsc compiler your tsx? files so in order to fix this issue you might need to define the type for your global value which is available on window as following steps:
Create your project typing dir and the file types/global.d.ts (you can name whatever you want, feel free to use my suggested name in terms of no idea how to name it) with following content:
// global.d.ts
// You can define your own type by replacing with the exact type
declare const CUSTOM_WINDOW_VARIABLE: any;
Make sure your tsconfig.json which is placed at repo's root dir in most cases includes your types dir by adding to include config option:
// tsconfig.json
{
"include": ["types", ...]
}
Hopefully it would work for your case
PS: If you don't import your library as externals, basically you don't have to configure the externals property in your webpack.config file

Require third party RequireJS modules with Webpack

I'm working on an application that needs to pull in the ReadiumJS library, which uses AMD modules. The app itself is written in es6 w/ webpack and babel. I've gotten the vendor bundle working correctly, and it's pulling in the built Readium file, but when I try to require any of the modules Webpack says it can't resolve them. Anyone ever do this before with Webpack and RequireJS? Here's some info that may help - not sure what else to include as this is my first time really using Webpack..
Folder Structure
/readium-src
/readium-js
/ *** all readium-specific files and build output (have to pull down repo and build locally)
/node_modules
/src
/app.js -> main entry for my app
/webpack.config.babel.js
webpack.config.js entries
entry: {
vendorJs: [
'jquery',
'angular',
'../readium-src/readium-js/build-output/_single-bundle/readium-js_all.js',
'bootstrap/js/alert.js' //bootstrap js example
],
appJs: './app.js'
}
Trying to require it in app.js
var readiumSharedGlobals = require('readium_shared_js/globals');
I never really got into using RequireJS, so really struggling to understand how to consume that type of module along side other types of modules with webpack. Any help greatly appreciated :)
Update
If I change my app.js to use this instead:
window.rqReadium = require('../readium-src/readium-js/build-output/_single-bundle/readium-js_all.js');
Then it appears to try to load all the modules, but I get a strange error:
Uncaught Error: No IPv6
At this point, I'm unsure of
Should I have to require the entire path like that?
Is this error something from webpack, requirejs, or Readium? Tried debugging, but couldn't find anything useful...
UPDATE 8/12/2016
I think this is related to an issue with a library that Readium is depending on: https://github.com/medialize/URI.js/issues/118
However, I'm still not clear on how to correctly import AMD modules with webpack. Here's what I mean:
Let's say I have an amd module defined in moneyService.amd.js like this:
define('myMoneyService', ['jquery'], function($) {
//contrived simple example...
return function getDollaz() { console.log('$$$'); }
});
Then, in a sibling file, app.js, I want to pull in that file.
//this works
var getDollaz = require('./moneyService.amd.js');
//this works
require(['./moneyService.amd.js'], function(getDollaz) { getDollaz(); }
//this does not
require(['myMoneyService' /*require by its ID vs file name*/], function(getDollaz) {
getDollaz();
}
So, if we cannot require named modules, how would we work with a third party lib's dist file that has all the modules bundled into a single file?
Ok, so there's a repo out there for an Electron ePub reader using Readium, and it's using webpack: https://github.com/clebeaupin/readium-electron This shows a great way to handle pulling in RequireJS modules with webpack.
One super awesome thing I found is that you can specify output.library and output.libraryTarget and webpack will transpose from one module format to another... freaking awesome! So, I can import the requirejs module, set output library and libraryTarget to 'readium-js' and 'commonjs2' respectively, then inside my application code I can do import Readium from 'readium-js';

"Uncaught ReferenceError: require is not defined" with Angular 2/webpack

I am working an HTML template from a graphic design company into my Angular 2 project using node and webpack.
The HTML pulls in various scripts like this:
<script src="js/jquery.icheck.min.js"></script>
<script src="js/waypoints.min.js"></script>
so I am requiring them in my component.ts:
var icheckJs = require('../js/jquery.icheck.min');
var waypointsJs = require('../js/waypoints.min');
There are several other scripts too and some SASS which appears to be working correctly.
webpack is happy and build it all and an 'npm start' is successful too. However, when it reaches the browser, I get this complaint:
Uncaught ReferenceError: require is not defined node_modules/angular2/platform/browser.js:1 Uncaught ReferenceError: require is not defined
which is actually thrown by this line from url.js:
var punycode = require('punycode');
Is this a CommonJs require? I hadn't used this in web development before a few weeks ago so I'm still untangling the various requires from webback, CommonJs et at.
An extract from my webpack.config.js for the .js loader looks like this:
{ test: /\.js$/, loader: 'script' }
How do I work around this error?
WebPack can do this alone. You need to make sure you load the initial chunk first using a script src tag. It will typically be the value of the entry: key in the WebPack config with -bundle appended. If you're not doing explicit chunking, your entry chunk should be both an initial and entry chunk and have the WebPack runtime in it. The WebPack runtime contains and loads the require function before your code runs.
Your components or whatever you're requiring need to be required from the entry file since your scripts will start there. Basically, if you're not explicitly chunking, the entry point JS file is the only one you can include with script src. Everything else needs to be required from it. What you include will typically have bundle in the JS filename. By default, it should be main-bundle.js.
For anyone that is looking for an answer but the above doesn't work:
Short
Add or Replace current target in webpack.config.js to target: 'web'
A bit longer
Webpack has different targets, if you've experimented with this and changed your target to node it will use 'require' to load chuncks.
The best thing is to make your target (or to add) target: 'web' in your webpack.config.js. This is the default target and loads your chuncks in a way the browser can handle.
I eventually found this solution here.
You can do this in one line assumed that you have
the bundle in dist/bundle.js
the source file client code that will render the page in the browser in
client/client.js
webpack && webpack ./client/client.js dist/bundle.js \
&& webpack-dev-server --progress --color
You need to run webpack again since if some sources in the library change you will get the last changes then in the dist/bundle.js package (of course you can add like a grunt file watch task for this). webpack-dev-server will run the server then.

RequireJS: Cannot find module 'domReady'

I have quite an annoying, but probably simple, problem that I just cannot figure out.
In a TypeScript file I have defined the following line:
import test1 = require('domReady');
This "domReady" module is defined in a main.js file that is loaded as the entry point for RequireJS. The definition is as followed:
require.config({
paths: {
'domReady': '../domReady',
}
However... in my TypeScript file I simply get a "cannot find module 'domReady'" and it is driving me insane, as I have double checked the pathing to the file and it is indeed in the correct location with the correct name. Additionally, I am fairly certain that the domReady.js file IS AMD compatible, so it should define an external module just fine! (domReady GitHub Link).
I seriously can't understand why the module can't be found in the import statement. Does anyone have any ideas to what the problem may be?
EDIT 1
The directory structure is as follows:
.
+--App
| +--main.js
| +--dashboard.js
+--domReady.js
The import statement takes place in the "dashboard.js" file, and the config for require.js happens in "main.js".
In order for TypeScript to find a module, you must actually provide module information to TypeScript.
TypeScript doesn’t yet support AMD-style paths configuration, it doesn’t ever use calls within your JavaScript code (like require.config()) to configure itself, and it won’t treat JavaScript files on disk as modules when compiling. So right now, you aren’t doing anything to actually give the compiler the information it needs to successfully process the import statement.
For your code to compile without error, you have to explicitly declare an ambient declaration for the module you’re importing within the compiler, in a separate d.ts file:
// in domReady.d.ts
declare module 'domReady' {
function domReady(callback: () => any): void;
export = domReady;
}
Then, include this d.ts in the list of files you pass to the compiler:
tsc domReady.d.ts App/main.ts App/dashboard.ts
Any other third party JavaScript code that you import also needs ambient declarations to compile successfully; DefinitelyTyped provides d.ts files for many of these.
I've had problems before when the path key and the directory name or file name are the same (in your case, domReady). Might not work, but worth giving it a quick try, i.e.
either
'domReadyModule': '../domReady',
require('domReadyModule')
or rename domReady.js to e.g. domReady-1.0.js and use
'domReady': '../domReady-1.0',
require('domReady')
If that doesn't work, I'd check the relative directories between main.js and the file that is doing the require, or else try importing another library in the same fashion, or finally compare with other libraries that you are importing successfully.
Good luck, hope you resolve the problem!

Categories

Resources