Friends,
I'm trying to keep an external file out of the Webpack bundle, but to remain as a dependency - a settings file in this case. I've tried several variations of the following -
externals: {
'Settings': JSON.stringify(require('./settings.json'))
},
...but Webpack keeps including it in the bundle. The only examples I've found in the docs are of common presets like jQuery, nothing is mentioned of local but external files. Help? Thanks!
So after much research, the only way, as of writing this answer, to fetch an external file is to, in a way, ignore Webpack and simply add another script call to the index.html. This is what I ended up doing -
<body>
<div id="whatever-app-id"></div>
<script type="text/javascript" src="settings.js"></script>
<script type="text/javascript" src="app.js" defer></script>
</body>
For good measure, you can also add the webpack externals as mentioned in #gmaliar 's answer with reference to the global object declared in the settings.js file. However that's somewhat redundant as the object is global anyway.
Hope it helped anyone.
How about?
// Outside of webpack context
var fs = require("fs");
var settings = JSON.parse(fs.readFileSync('./settings.json', 'utf8'));
// Within webpack context
externals: {
'Settings': settings
}
Related
So recently I was making a website and I added a login page. I wanted to check if the username and password entered existed in the database and if not it would give an alert saying invalid username or password. My code is:
<form>
<label>Enter Username:</label>
<input type="text" id="username">
<br>
<label>Enter Password:</label>
<input type="password" id="password">
<br>
<input type="submit" onclick="submitLoginInfo()">
</form>
and the js is
const { LoginSchemaModel } = require('./dbconfig.js')
// import { LoginSchemaModel } from './dbconfig'
requirejs()
function submitLoginInfo () {
let usernameElement = document.querySelector('#username')
let passwordElement = document.querySelector('#password')
console.log(`Username Element is HTMLElement: ${usernameElement instanceof HTMLElement}`);
console.log(`Username Element is HTMLElement: ${passwordElement instanceof HTMLElement}`);
alert(`usernameElement = ${usernameElement}`);
alert(`passwordElement = ${passwordElement}`);
alert(`username = ${usernameElement.value}`);
alert(`password = ${passwordElement.value}`);
}
Now the problem is with the require because that is not supported. So I decided to use imports instead and added "type"="module" to my package.json but was still getting an error in the console saying I can't use it. Then I used requirejs and ran into this issue where I couldn't import requirejs without using the require function. When I tried to add
var requirejs = require('requirejs')
requirejs.config({
nodeRequire: require
});
it would say that I couldn't use require(). When I tried to do it in a seperate file I realized I had to require that file to use requirejs which wouldn't work. I have no idea on how to fix this, I have been searching stack overflow and other websites but nothing mentions this. I want to know if there is a different way which I have just been missing this whole time.
I will assume that you are just declaring the js in some HTML with a script that will run in the client. Like that <script src="./myscript.js"></script>
Why you couldn't use require
require is the way we import modules in Node.js(an engine that runs javascript outside the browser) or any other javascript engine that adopts the CommonJs modules pattern. Browsers uses what is called ESModules.
Why did changing type="module" in package.json didn't solve this problem?
The package.json file is completely ignored by the browser, it doesn't affect anything in the javascript you import from the script tag. package.json is file used by node.js(and other engines). And type="module" is used in Node.js to use import instead of require, so wouldn't fix even if the browser read it.
How can we import things in browser javascript
Firstly I have to say that browsers usually expect people to use some bundling tool like webpack. (bundler is just a program that transforms all your .js files into a single .js file) instead of importing modules directly, but if you want to do it only using a web-browser and nothing more you can:
Add the type="module" in the script tag.
<script type="module" src="./myscript.js"></script>
Use something like the live server extension of vscode
Because, browsers cannot give .html files to have full access to your files, so you need to simulate a server in a folder.
So now you can simple use import {thing} from "./myscript.js" that will work.
How to use the require.js lib in the browser.
I have to say that you shouldn't use it, it is used by people that want some packages made for node.js to work on browser. But if one would want to use requires only using the browser they would have to remember that when we do npm i requirejs it creates downloads it into the node_modules folder, so we would have to import from there. But again, you shouldn't do that to solve your problem. Stick to the import.
Rationale
I'm making a small website using svelte and sveltekit, and a library (roslibjs) that seems to be only usable within <head>.
It worked only in those 2 types of scenarios for me:
put everything in <head> and output to the console
import the library in <head>, but only by using <script src='https link here'></script>.
Everything else goes into onMount, outside of <head>.
1 is not acceptable, and while 2 is a temporary fix, I really don't want to rely on external links. (the site might be used in an offline environment)
What I tried
Since if I have all the code relying on the library inside <head> it works just fine, I tried to do so. But so long I couldn't find a way to export variables from <head>.
Example:
<svelte:head>
<script>
let a = 10
</script>
</svelte:head>
<p>{a}</p>
This throws an error saying 'a' is not defined.
Change the import line to <script src="node_modules/roslib/build/roslib.js"></script>, directly from the node_modules folder.
While this works in npm run dev, it doesn't once after npm run build.
What I expect
To be able to use the library with svelte3, but by using it from npm, not an external link.
One way to tackle this might be to export variables from <head>, but I couldn't find a way to do so.
I've looked for this problem - I see others have the same problem, BUT the fixes don't fix it.
The fix mentioned was to run a web server, which I did.
In my html header I have
<script type="text/javascript" src="d3.v4.js"></script>
I my html body I have
<script type="text/javascript" src="stuff.js"></script>
stuff.js contains:
d3.csv("stuff.csv").get(function(error, data){
console.log(error)
console.log(data);
})
stuff.csv exists. It is in the same directory as a html and js files. It is a good file. I can read it.
One solution that seems to have worked for other people is to use a webserver. So I ran xampp with the document root set to the same directory where the js, html, and csv reside. It still does not work.
In each case, there is a value for error; there is no value for data.
I saw tutorials regarding webpack and i'm able to bundle everything in bundle.js and i'm able to import jquery in .js files.
In my application i'm using ajax,bootstrap-table, so i need jquery and bootstrap-table in index.html
Using webpack how can i pack and load these in html file using webpack?
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
This is my webpack.config.js
var webpack =require('webpack');
module.exports = {
entry: './app.js',
output: {
filename: './bundle.js'
},
node: {
fs: 'empty',
net: 'empty',
tls: 'empty'
},
plugins:[
new webpack.ProvidePlugin({
$:'jquery',
jQuery:'jquery'
})
]
};
If i want jquery in js file, in my nodejs file i'm adding require('jquery') but i want to load those in html?I didn't find much materials regarding this. If anyone knows please help!!!Thanks a lot in advance!!
Are you importing bootstrap inside app.js too?
Based on the current setup, the bundle is generated in the directory in which you have your webpack config file.
if you already have your html template[index.html], then you should include the relative path of the bundled js file in the index.html
i.e. <script src="./bundle.js"></script>
else if you want the bundled file to be included dynamically in your index.html template, you should have a look at html-webpack-plugin
I've installed particle.js in my project and it works with the default effect, I have gone through this site http://vincentgarreau.com and found 5 effects: default, snow, NASA, Buddle and Nyan cat. My question is how can I use those effects in my project? I choose one and I downloaded the JSON config but I don't know how to add it to my project.
You just need to load the json file. The syntax would be something like this
<script>
particlesJS.load('particles-js', 'particles.json', function(){
console.log('particles.json loaded...');
});
</script>
Write the appropriate path if these files are located elsewhere. The 'particles.json' file will be your config file you downloaded from somewhere. You can even edit the particles.json file yourself to get your desired result.
This video by Traversy media is a great reference if you wish to dig deep into particle js and create your own desired effects.
Good luck!
https://www.youtube.com/watch?v=qK3cgD09Qf0&t=1567s