Javascript ES6 modules name resolution - javascript

I'm absolutely sure, that I'm asking a silly question, but I really do not understand how this line of code works
import React from 'react';
My question: who and where searches for 'react' name?
For example, this site tells me, that for module-name I should use relative of absolute path, e.g
import React from './react';
or
import React from '/home/user/react';
I thought that 'react' is same as './react' but I've created ReactJS applcation via create-react-app command and didn't find any file named react.js in application folder.
So, obviously there is some tool or rule by which module name has been resolved to a proper file, but I cannot find proper documentation about this.

Import statements are importing packages by name from the node_modules directory in your app, which is where they're saved when you run an installation command such as npm install or yarn inside your app.
When you write:
import React from 'react';
As far as you're concerned, it's as if you'd written:
import React from './node_modules/react/index.js';
Importing by package name means you don't have to be aware of how a given package is structured or where your node_modules directory is relative to your javascript file.

Related

The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script

I Just created a react app. The npm start seems to work fine but npm run build is constantly failing. I need to run npm run build to deploy it on some website.
Already gone through all posts related to this on stackoverflow.com. But didn't found any working solution.
import './App.css';
import 'https://kit.fontawesome.com/a076d05399.js'
import Navbar from './components/navbar';
import Homepage from './components/homepage';
import Skills from './components/Skills';
import Project from './components/project';
import Contact from './components/contact';
Error Message
Failed to compile.
The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script
The problem here was the import statement of an external js file.
import 'https://kit.fontawesome.com/a076d05399.js';
You can add the file in index.html & run build.
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
And yes there's no problem with import statement in css.
#import url("https://cdn.jsdelivr.net/npm/remixicon#2.5.0/fonts/remixicon.css");
In my case, it was failing because using external styles
import "https://unpkg.com/leaflet#1.6.0/dist/leaflet.css";
Fixed with using via npm:
npm i leaflet
import 'leaflet/dist/leaflet.css';
Official docs

Webpack - Alias folder for use within installed package

I have some reusable React components published to NPM, that I am installing and using within my React application. Is it possible for me to set an alias in my React app, that can be used within these NPM components? For example, I want to allow the use of a folder common, which is within my React App, within the React components. So if I do this in my React components, it should work
import someVal from 'common';
I am bundling these React components with Webpack, and sending down the transpiled, bundled version for use within the React application. I tried setting the alias the regular way within the React app webpack config (by setting resolve.alias), but it does not work. Can this be done? Or am I approaching this incorrectly? Any suggestions would be great, thanks!
Edit: So the React components from NPM are within my node_modules folder, and it is already bundled up via it's own Webpack config. I then run these components through my React application Webpack config as well (I'm whitelisting the folder), in the hopes that the new common alias will be added there. But no luck. I keep getting a
someVal is undefined error.
My common file has the following: Ignore the logic for now (I'm only posting a part of the code)
import _myClass from '../components/MyClass';
const myClass = _myClass; // Other things are done to it
export default myClass;
In my React components Webpack bundle file (after I fixed the default import statement)
/* harmony import */ var common__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! common */ "./src/common/index.js");
...
return common__WEBPACK_IMPORTED_MODULE_25__["default"].myFunction({
...
});
This still seems to be looking for common within the React components package, and not within the React app package that I am trying to use this in.

How to export multiple library variants from a single NPM package

I'm creating a node library that could be partially used in web browsers.
My current structure is something like:
package.json
lib/
index.js
node.js
web.js
modules/
some-function.js
some-node-function.js
some-web-function.js
...
"lib/index.js" is specified as "main" in package.json
I'm using each file inside lib/ to re-export functions from modules/ filtered by target (all/node/web)
And I would like to use it like this:
import fullLibrary from "my-library";
import {someFunction} from "my-library";
import webOnlyLibrary from "my-library/web";
import {someWebFunction} from "my-library/web";
import nodeOnlyLibrary from "my-library/node";
import {someNodeFunction} from "my-library/node";
BUT keeping index.js, node.js and web.js inside /lib!
Currently only the first two import statements work (because index.js is pointed from package.json).
I know that I could place those files in the root of the package and it would work as expected when importing, but I was wondering if there was a way to do the same while keeping the files in /lib for cleanness.
In any case, is this the recommended way to expose multiple variants of a same library from a single NPM package?
Just for anyone that is having similar questions regarding libraries structure and organization.
Back then I started working with monorepos using Lerna and Yarn Workspaces and I haven't regret it. I think this is the most efficient way to go in terms of modularity, readability, scalability and maintainability.
Specifically, the question code would be traduced into this:
import webOnlyLibrary from "#my-library/web";
import {someWebFunction} from "#my-library/web";
import nodeOnlyLibrary from "#my-library/node";
import {someNodeFunction} from "#my-library/node";

Import from subfolder of npm package

I've been working on creating a small library of React components for use in several other projects. I am publishing the package internally (using a private GitHub repository) and then including in another project. However, when I go to import from a subdirectory of the package I am not able to do so as the paths don't match.
The projects using the package all utilize webpack to bundle/transpile code as I am trying to avoid doing any building in the component library if possible.
Directory Structure
- package.json
- src/
- index.js
- Button/
- index.js
- Button.jsx
- ButtonGroup.jsx
- Header/
- index.js
- Header.jsx (default export)
package.json
...
"main": "./src/index.js",
"scripts": "",
...
src/Button/index.js
import Button from './Button';
import ButtonGroup from './ButtonGroup';
export default Button;
export { Button, ButtonGroup};
src/index.js
Is this file actually necessary if only importing from subdirectories?
import Button from './Button';
import ButtonGroup from './Button/ButtonGroup';
import Header from './Header';
export { Button, ButtonGroup, Header };
Other Project
// This project is responsible for building/transpiling after importing
import { Button, ButtonGroup } from 'components-library/Button';
Example
Material-UI is a library of React components that is used by requiring in the following fashion: import { RadioButtonGroup } from 'material-ui/RadioButton. I've tried to figure out how this works for them but to no avail yet.
Similar Questions
How would I import a module within an npm package subfolder with webpack?
This is very nearly the correct approach I require, except that the import path used there involved the src/ directory, which I am trying to avoid (should be component-library/item, not component-library/src/item (which does work currently though))
Publishing Flat NPM Packages
This is exactly what I want except that I was hoping to not have a "build" phase in the package (rely on importing locations to build/transpile)
Questions
Can I skip the src/ directory somehow in the import path?
Can I skip any type of build phase in the package (so developers don't have to build before committing)?
How does a package similar to material-ui handle this?
Can I skip the src/ directory somehow in the import path?
Yes. Using the package.json "exports" field, which should be supported by Webpack in a near future (see this issue), but has already been supported by Node since Node 12 LTS following the Bare Module Specifier Resolution proposal:
package.json
...
"main": "./src/index.js",
"type": "module",
...
"exports": {
"./Button": "./src/Button/index.js",
"./Header": "./src/Header/index.js"
},
...
Now, the following code:
// This project is responsible for building/transpiling after importing
import { Button, ButtonGroup } from 'components-library/Button';
should be translated to:
import { Button, ButtonGroup } from 'components-library/src/Button/index.js';
which should correctly import the requested modules.
Caveat
Now, it would certainly be tempting to try a simpler version like:
...
"exports": {
"./Button": "./src/Button/",
"./Header": "./src/Header/"
},
...
so as the usual import statement
import { ... } from 'components-library/Button';
gets translated to
import { ... } from 'components-library/src/Button';
This looks nice, but it will not work in this case, because your submodules don't have each their own package.json file but rely on their index.js file to be found.
/!\ Unlike in CommonJS, there is no automatic searching for index.js or index.mjs or for file extensions.
src/index.js - Is this file actually necessary if only importing from subdirectories?
I don't think so, but you can keep it if you want.
Can I skip any type of build phase in the package?
Using the "exports" field does not require you to transpile your code.
The answer may depend on how you installed your components library. If you did it via either npm install <git-host>:<git-user>/<repo-name> or npm install <git repo url>,
You should be able to import {Button} from 'component-library/Button' as is, according to your first linked question. Similar to Node's require() resolution, Webpack should resolve subdirectories within component-library relative to component-library's entry point. You can find the docs on customizing the resolution behavior via the webpack.config.resolve property. material-ui seems to rely on resolving subdirectory imports from the module entry directory.
To distribute an ES module library, there's no need for building before distribution. However, projects such as create-react-app may need a pre-transpiled version.
Alternately, you can write import {Button} from 'components-library'.
Webpack will trace the dependencies back through each index without a fuss.
you have to install babel-plugin-module-resolver package
Specify the package relative path in your .babelrc file alias like this
{
"plugins": [
["module-resolver", {
"alias": {
"components-library": "./node_module/components-library"
}
}]
]
}
then you can import subdir of npm package like this
import { Button, ButtonGroup } from 'components-library/Button';
One of the possible solutions there is webpack aliasing system.
You can create another project, call it for example 'app-aliases', so your aliases will be reusable.
This project will has one js file with all of your packages paths:
const path = require('path');
module.exports = {
'#components': path.resolve(__dirname, 'node_modules/components-library/src'),
'#another': path.resolve(__dirname, 'node_modules/any/path/you/want'),
}
And then add it to the webpack configuration in any project which will be responsible for building/transpiling:
webpack.config.js
const appAliases = require('app-aliases');
const config = {
...
resolve: {
alias: {
...appAlises
}
}
}
In the runtime code you will be able to use it like this:
import {Button} from '#components/Button';
import {Something} from '#another'
If you are using typescript you will need to add the same aliases to the paths tsconfig property.
So answers to your questions are:
Yes, you can use any path in aliases
Yes, it is not necessary to build all of your projects
I see that now mui uses imports from directi packages (core for example), see https://material-ui.com/components/radio-buttons/ there is import Radio from '#material-ui/core/Radio';. But I hope they using re-export that I described below.
Also about node.js resolution mechanism.
When you import some library it tries to find node_modules/some-library/package.json and then main property inside it. This property should lead to your main entry point. Usually it is src/index.js (you should set it in package.json if it is no there yet). In this file you can re-export anything you want from internals file structure and will be able to use it without the full path.
Please see this repo for some examples.
I'am an angular developer never used react but what I could tell that material-ui are using monorepo where same concept exists in angular where we create one workspace and this workspace hold multiple project/packages as named in react. for more info Workspaces with Yarn
Material-ui using fake paths in tsconfig to make it appears like src folder doesn't exists this from the git you provided: tsconfig.json
This is possible but requires publishing a curated dist folder rather then the root of your project.
The whole thing is rather simple if you understand how module resolution works, and you just need a small script to prepare your distribution.
Lest I repeat all the details here, please see my answer for Importing from subfolders for a javascript package.

TypeScript import class from another project / module?

I am trying to alter the following build task written in Typescript in the following project:
https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts
I need an import like the one shown below (or something else that lets me uses the methods in the ios-signing-common module):
import sign = require('ios-signing-common/ios-signing-common');
That import is used in another file in another project:
https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/XamariniOS/xamarinios.ts, however that project is also the same as the ios-signing-common exists in.
https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/Common/ios-signing-common/ios-signing-common.ts
So is it possible to import the ios-signing-common module into the app-store-promote file?
I have tried adding the github path "Microsoft/vsts-tasks" as dependency in package.json, and it downloads it to node_modules, but I still can't resolve the ios-signing-common module.
I hope that any of you can lead me to a solution. :)
I guess I just needed to read up on how module resolving works.
I solved it by adding vsts-tasks as dependency in package.json:
"dependencies": {
"vsts-task-lib": "^0.9.7",
"vsts-tasks": "Microsoft/vsts-tasks"
},
Then I changed the require path to the following:
import sign = require('Agent.Tasks/Tasks/Common/ios-signing-common/ios-signing-common');
And it works!
EDIT - It could compile, but doesn't seem to work when I run it. It fails in the script because it can't find Agent.Tasks/Tasks/Common/ios-signing-common/ios-signing-common.

Categories

Resources