Make package available from browser and as npm package - javascript

I have main.js and two function on this file to export, like:
export function one() {}
export function two() {}
Next, I imported functions to index.js, with import:
import { one, two } from './src/main'
And bundled it, with webpack, and used index.js as entry point.
How I can make, to use this script, as npm package, and as CDN from bundled script (or just local connect from path)?
I found, solution like:
import { one, two } from './src/main'
window.one = one
window.two = two
export { one, two }
But, it's now seems very neat.
Thanks, for your ideas and comments.

Related

How to export a function in nodejs that I made

Every time I try to import into my nodejs file I get the error, cannot import outside a module
I have tried multiple solutions on StackOverFlow such as adding
"type":"module"
and setting file extensions to .mjs
I want to import constants from a different file but I am not sure how to
example
functions.js
export const myFunc = (param1) => return 'hello'
backend.js
import {myFun} from './.js'
How should I import them?
Sorry I accessed a similar question for constants but the same method does not work for functions
First, "type": "module" needs to be in the package.json or both JS files need to end in .mjs. You seem to be aware of this, but just making sure as the filenames you have provided don't end in .mjs, and you haven't provided your package.json.
When using arrow functions, the return is implied. If you try to use return in an arrow function, an error will occur. Also, in backend.js, you are importing myFun, which is not in functions.js. I believe you meant to import myFunc.
functions.mjs
export const myFunc = (param1) => "hello"
backend.mjs
import { myFunc } from './functions.mjs'
console.log(myFunc("test"))

How to properly export/import modules for library usage in javascript

I want to write a javascript library with two files:
snabbpixi.js
export function init() {
}
pixiapi.js
export function createElement() {
}
I want to use this library like this:
import { init } from 'snabbpixi';
import { createElement } from 'snabbpixi/pixiapi';
If I don't do anything and set the package.json for library as:
{
"main": "src/snabbpixi.js"
}
second import doesn't work (import { createElement } from 'snabbpixi/pixiap')
If I compile this library and export as umd format using webpack it also doesn't work.
How can I configure my library so I can import like this:
import { createElement } from 'snabbpixi/pixiap'
I normally do this sort of thing in TypeScript rather than straight JavaScript, but hopefully this works in basically the same way...
Try creating a new file (typically named index.js), with contents like this:
export * from './snabbpixi'; // Adjust paths as needed for your particular case.
export * from './snabbpixi/pixiapi';
Then make index.js your main.
The import you would use would then be flattened-out, however, looking more like:
import { init, createElement } from 'snabbpixi';
When you are using import { Something } from 'somewhere' you are calling on a named export from a given file or directory.
If the two files are in different directories then you can add an index.js file to each directory and then use export { default as function } from './file'
To do this you would have to export the default file from pixiapi and snabbpixi.
If you have both files importing into your index.js then you will still want to export them as defaults. But then you would do the following..
import file1 from './file1'
import file2 from './file2'
export default {
file1,
file2,
}
This will allow you to use the named imports as well and keep them in the same directory

Split Typescript logic into several files

I have several typescript files in my project and one entry file index.ts (output file is created by webpack).
Individual files with logic export nothing.
Eg. file-one.ts:
document.getElementById('btn').onclick = function() {
console.log('Hello world');
}
How can I import files like the one above into main - entry file?
Eg. index.ts:
import `./file-one`
Return ERROR:
ERROR in ./src/index.ts
Module not found: Error: Can't resolve './file-one.ts' in './src/index.ts'
Eg. file-one.ts:
export click() {
console.log('Hello world');
}
How can I import files like the one above into main - entry file?
Eg. index.ts:
import {click} from `./file-one.ts`
document.getElementById('btn').onclick = click;
You should be able to do that without any problem... a module can be imported even if it is not exporting anything.
I noticed that you are using a back-tick here ... it should be a string like import './file-one.ts' ( though a back-tick in that case should raise another error)
Anyway just make sure your webpack configuration can load typescript files, and that the path to your file is correct, and it should work.

Set a global service for import in Create React App

Is it possible to somehow declare a jsx file as a global file or a directory for import? For example instead of:
import { Navigation } from '../../../../../../helpers/NavigationService';
do just:
import { Navigation } from 'NavigationService';
I've seen it's possible in webpack config, but I don't see this file in create-react-app. Can I use somehow package.json for that?
There are three ways to solve your issue:
NODE_PATH (<- probably what you're looking for):
You can define an environment variable NODE_PATH=src/ and then you can import your service like so import { Navigation } from 'helpers/NavigationService';. It'll will work but this is not necessary what's best in my opinion.
No deep nesting:
No nesting, means no issue of deep nesting in the first place. You can try having a file hierarchy similar to this:
src/
/helpers
/components/
/componentA/
componentA
relatedComponent
otherRelatedComponent <- no need for nesting
/componentB/
...
The mono repo approach:
Having an internal helper package and have it imported like import { Navigation } from 'myproject-helpers/NavigationService'; may be a good compromise
You could set NODE_PATH='src' in .env file, using global imports instead, here's my solution, without having to eject.
.env:
NODE_PATH='src'
Create a folder src/services, inside it create the NavigationService, my example:
// src/services/NavigationService.js
export class NavigationService {
static runIt() {
console.log("Running");
}
}
In the App.js file, now you can import the navigation service directly, using global import, as follows:
// src/App.js
// ... import React and others
import { NavigationService } from "services/NavigationService";
class App extends Component {
componentDidMount() {
NavigationService.runIt();
}
// ... render method
}
If using VsCode, to get code completion, create jsconfig.json file, with the following:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"services/*": ["./src/services/*"]
}
}
}
I hope it helps!

Webpack 2 accessible functions from different js files

Just started using webpack-2 and have a question about global functions. Have these functions in js file named showPictures.js:
function isEmpty(el) {
var result = !$.trim(el.html());
return result;
}
function showPicturesList() {
if (!isEmpty($('#picture-name-list'))) {
var pictureList = document.getElementById("added-pictures");
pictureList.style.visibility = 'visible';
}
}
And I have another file util.js in witch I am calling showPicturesList() function
window.onload = function(){
showPictureList();
}
Simply using js I would import both scripts into my html, but with webpack I can make one file for both of them so webpack.config.js I added both of these files as entry array.
My output file bundle.js looks as it should it has both of those files inside of it. The question is what would be the easiest way with minimal changes on js files to call showPictureList() function from utils.js file?
You can use ES2015/ES6 modules to import your functions which have been exported in another file. In your showPictures.js file you export the functions you want to expose, by adding the export keyword.
export function showPicturesList() {
if (!isEmpty($('#picture-name-list'))) {
var pictureList = document.getElementById("added-pictures");
pictureList.style.visibility = 'visible';
}
}
And then you need to import them in your util.js.
import { showPicturesList } from './showPictures';
For detailed informations on how to use modules you can have a look at Exploring JS: Modules.
With this you also don't need to add both files to entry in your webpack config, because webpack will see the imports and include eveything you're importing.

Categories

Resources