So, I know there are a lot of similar questions here, I read all, as well as several web articles. Still, I cannot find a solution. I simply want to import es modules from lodash. Currently using rollup via codekit app.
Simply doing one of the following, will always end up in an empty js file:
import each from 'lodash-es';
import { each } from 'lodash-es';
import each from 'lodash-es/forEach';
import each from 'node_modules/lodash-es';
They all will end with the empty (currently compiling in iife):
(function () {
'use strict';
})();
Why?
If the function isn't used in the code in any way, it will get stripped from the production output due to a process called tree shaking. It's an optimization that looks at code imports and then eliminates any unused code as a result.
It turns out that was the case here as each wasn't used and it was imported only.
Related
Hi i'm currently learning nodejs and I try to import a json file like this :
'use strict'
import data from 'users.json'
console.log(data)
Each time I get this error "Cannot find package 'users.json'"
But if I read the file with fs it worked so can you explain me how to do please
try :
import data from './users'
which is the es6 method of doing things or if you want an older syntax method you can try
const data = require('./users')
Okay so the explanation just is this, those fullstops and forward slash are used to indicate relative paths to the file the import is being called from, which means somethings you'd see something like for example ../file/help. The ./ means go up one directory ../ means go up two directories and so on. The name after the slash just tells your program the folder to go in to look for the file to import from so ./folder means go up one directory and enter into the folder directory and so on.
Almost forgot to mention, you should not import from a json file or a text file or any other file that does not have a .js extention(of which you do not actually have to specify) unless absolutely neccessary. To deal with files in node you have to use the fs library.
const fs =require('fs')
....
fs.readFile('./users.json','utf-8',(err,jsonString)=>{
const data = JSON.parse(jsonString);
//whatever other code you may fanacy
}
take a look at the fs module for a list of awesome features you can use to play with files
While the selected answer is correct, here's an explanation that I hope might add some clarity:
import MyModule from 'some-module'
is ES6 import syntax, as opposed to the older CommonJS syntax, which uses require.
CommonJS's require can be used to import files generally; ES6's import statement is more specific, and is generally used for importing js files which meet the criteria for being a module (having an export statement), or specific assets such as CSS sheets. Unlike require, it won't generally work for reading in files that are not modules.
You can't mix CommonJS require and ES6 import in the same file (at least not easily), so if you're using ES6 import and wish to read a file, do so with fs.readFileSync or a similar method. If the file is a json string, you'll need to parse it with JSON.parse().
If you want to use ES6 (NOT CommonJS) module system but want to use the Node.js version which is less than V18 (supports direct json import) then use the below approach.
import { createRequire } from "module";
const require = createRequire(import.meta.url); // construct the require method
const data = require("users.json"); // Now you can use require method in ES6
console.log(data)
Hello guys i have a little question about importing files into a single .js file.
Which way is better (best practice), what's the scenario that is used for:
import './file;'
import { something } from './file'
import * as evertything from './file'
Because i see that 2 and 3 are the same thing but different syntax(maybe Syntactic Sugar).
All three do different things.
import './file;'
That loads the file, and does not import anything. This is useful if you want to initialize that module (or add some external dependency, e.g. a css file if you use Webpack).
import { something } from './file'
That just imports something from the file, therefore a bundler could optimize all other dependencies away. I'd always try to go with that instead of
import * as evertything from './file'
That imports everything from that module under a namespace, and therefore makes treeshaking more difficult (the bundler cannot optimize it well). I'd only use that if you need everything from that dependency, or if that dependency is loaded externally nevertheless (e.g. import * as React from "react").
I guess the following MDN documentation will make you clear about those things:
import - JavaScript|MDN
As far as I know, 1st method is used when you have only one default export. 2nd is used when you have multiple default exports but you don't want all of them to load and want only few of them. 3rd is the case when you want everything under a single object (which can be used similar to namespace in other programming languages).
I'm using ES6 dynamic import to load a Sass file, according to an environment variable.
It's working fine, but when I build the production directory with Webpack, all the Sass files are exported as a JS chunk in the build directory.
After some research, I finally understand that import() look for similar files with the same path (only when I put a variable in the import)
It's quite problematic, I'd like to get the correct Sass file exported, and not the others.
import(`./assets/scss/App.${brandName}.scss`)
Any idea ?
Normally, you can't do that!
Because import statement must be at the top. Thus, you cannot define the variable before import statement. Hence, you cannot utilize the variable in import statements.
But, you can trick to use like this:
import brandName from 'your_path_to_brandName_export'
import(`./assets/scss/App.${brandName}.scss`)
Update
I am not sure about dynamic import, but it might help you further. See this proposal:
<script type="module">
import * as module from './utils.mjs';
module.default();
// → logs 'Hi from the default export!'
module.doStuff();
// → logs 'Doing stuff…'
</script>
See this source for further help.
Hope, this helps!
This question already has answers here:
import module just to run it
(2 answers)
Closed 6 years ago.
I am running Webpack, Babel and Vue.js and I want to split up my entry file. Currently I have an app.js file which is the starting point to my application.
I have some bits and pieces of Code I want to put into a bootstrap.js file which I want to include in my main app.js file can I can have a clean file to start out with Vue and add components in it as I go.
Some examples of what I would want to put in my bootstrap.js file:
import messagesNL from './translations/nl';
Vue.use(VeeValidate, {
locale: 'nl',
dictionary: {
nl: {
messages: messagesNL
}
}
});
window.Vue = Vue;
So pretty much setup for plugins, global configuration, etc. I feel like this is not your typical module and I find it hard to create a module like structure for this file so I basically use this in my app.js file:
import bootstrap from './bootstrap';
Having no idea if this would work, it seems to just import everything neatly without me having done a module exports {} like syntax.
Now the bootstrap variable that I assigned to that file is unused in app.js since it's only used to require the file and my IDE kind of 'greys` it out to let me know it is unused.
Is there another syntax for this so that I don't have to assign a name to it? Is this approach ok to split up my file, or should I be doing something else?
I haven't put it into a proper module yet because then it would have it's own local scope and I would be unsure how to set up Vue with all the plugins, etc. If anybody has a better suggestion I am open to it.
Cheers.
To include a file without importing anything you can just drop the <name> from part of the statement:
import './bootstrap';
This will execute the target module without affecting the scope of the active module, but it may have side-effects such as declaring globals or modifying existing globals.
As stated in the MDN docs for Import a module for its side effects only:
Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.
import '/modules/my-module.js';
I am running browserify on my code, it is as follows:
import './app';
//——————————————————————————————————————————————————//
// Components
//——————————————————————————————————————————————————//
import './components/_ntToggleClass';
app is simply
const app = angular.module('app', []);
while files in components are, well, components. But they are using forementioned app:
app.directive('ntToggleClass', () => {
... }
When I put everything in one file by hand, all worked. But after I used browserify on this, I am getting
Uncaught ReferenceError: app is not defined
When I look inside the code, both var app and the directive are there.
I've slapped together a quick sample on github. This will give you a working repository that runs browserify.
I've removed my previous comments, as I think the repo should answer your questions.
edit: I think I just now got your question, you were trying to create a global variable app to just be used in each other file?
This is impossible when using browserify, any variable that isn't required in your file will be returning undefined.
When using browserify, just require whatever you need.
A friend of mine came with help ;-)
I am using Babel (I thought thas was obvious, since I used import not require) for my coding (Babelify with es2015, to be precise), so, as I have import, I need export too.
Solution is very simple, all I had to do is to put
export default app;
at the end of my app.js file and then import it using
import app from '../app';
into my directives/components etc.
I think it's about definition ordering.
const app = angular.module('app', []);
This part should be top of below part:
app.directive('ntToggleClass', () => {
... }