Merge a third party javascript file into webpack bundle? - javascript

How can I merge a third party javascript file into my webpack bundle without getting checked on modules etc?
Because my third party javascript file is already bundled.

Well, the ideal would be for it to be bundled together, but you can work around this problem.
First, make sure it is imported somewhere on your dependency tree (webpack only knows about your file if it is imported).
Now, to be able to use external files, you have to use the external configuration.
For eg:
module.exports = {
//...
externals: {
jquery: 'jQuery'
}
};
States to webpack that this is going to be available as an external resource when this application is loaded.
Now you can add your already bundled file to your index.html and serve to the user.

Related

Nuxt (and Webpack): How to separate a single JS file to be reused by external app?

I've stumbled upon several pages about importing external files into a Nuxt project, but what I'm trying to do is the opposite.
I have two sites or apps: Site A and Site B. Site A is the main one built using Nuxt. Site B is a simple site with static pages, not using Nuxt or Vue.
Site A has a JavaScript file, let's say its path is /lib/common.js. I use it extensively on Site A. And I also want to use it on Site B.
However, when I do yarn generate on Site A, all my JS files, including common.js, get bundled into a JavaScript chunk files, and each file is named with a hash of the content of the file. For example, /lib/common.js, /lib/util.js get bundled up as /dist/_nuxt/05443d2eb25fc282bbea.js while /lib/user.js is bundled as /dist/_nuxt/1326d0fc90870f9f4ca4.js.
That means:
the file I want to use is actually bundled with other files into the same package, so if I load that file, I have to load extra code with it and,
I can't really predict the name of that file.
Is there a way for me to tell Nuxt, or most likely Webpack, to single out /lib/common.js into its own bundle and then save it as /dist/_nuxt/lib/common.js instead of a hash, so the filename is more predictable?
You would need to create a separate webpack configuration for that single file to achieve the desired result as only one output configuration per configuration file is supported[0].
[0] https://github.com/webpack/docs/wiki/configuration#output
Example common library configuration common.lib.config.js
var path = require('path');
module.exports = {
entry: './lib/common.js',
output: {
path: path.resolve(__dirname, 'dist/_nuxt/lib'),
filename: 'common.js'
}
};
And build it with webpack --config common.lib.config.js

Extracting a javascript file from webpack build

I am using webpack for a project where I need to have a javascript config file as part of the built files, but I cannot figure out how to do that.
So I need to have these files in the output:
index.html
app.js
config.js
I figure I need to either:
1) Copy the config.js file from the source folder to the build folder with CopyWebpackPlugin, or
2) Include the file in the compiled bundle and then extract it with ExtractTextWebpackPlugin.
I have tried dozens of different ways of configuring this, but when trying with the copy method, I get the file both inside the app.js bundle AND as a separate file. When I try with the extract method, I cannot seem to figure out how to extract javascript from the main bundle. The docs all seem to explain how to extract css.
How would I go about something like this?
You should be able to accomplish this by using multiple entry points.
https://webpack.js.org/concepts/entry-points/
entry: {
main: './path/to/file/app.js',
config: './path/to/file/config.js'
}
output: {
filename: 'output/path/[name].js'
}
A more complex option, which is typically used for vendor files, would be to use code-splitting.
https://webpack.js.org/guides/code-splitting/

how to use webpack to load CDN or external vendor javascript lib in js file, not in html file

I am using react starter kit for client side programming. It uses react and webpack. No index.html or any html to edit, all js files. My question is if I want to load a vendor js lib from cloud, how to do I do that?
It would be easy to do that in a html file. <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
However, in js file, it only uses npm installed packages. How can I import the above lib with no html file? I tried import and require, they only work for local files.
update 10/21/15
So far I tried two directions, neither is ideal.
#minheq yes there is a html file sort of for react start kit. It is html.js under src/components/Html. I can put cloud lib and all its dependencies there like this:
<div id="app" dangerouslySetInnerHTML={{__html: this.props.body}} />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>
<script src="/app.js"></script>
<script dangerouslySetInnerHTML={this.trackingCode()} />
</body>
Good news is it works, I don't need do anything else in js file, no import or require. However, now I have two jquery libs loaded in different ways. One in here, the other through npm and webpack. I wonder it will give me trouble later. The react-routing I use give me 'undefined variable' error if I type a none home path in browser window due to the server side loading I guess. So this solution is not very good.
Use webpack externals feature. This is documented as: link. "You can use the externals options for applications too, when you want to import an existing API into the bundle. I.e. you want to use jquery from CDN (separate tag) and still want to require("jquery") in your bundle. Just specify it as external: { externals: { jquery: "jQuery" } }."
However, the documentation I found a few places are all fussy about how to do this exactly. So far I have no idea how to use it to replace <script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script> in html.
externals is not intended to let you do this. It means "don't compile this resource into the final bundle because I will include it myself"
What you need is a script loader implementation such as script.js. I also wrote a simple app to compare different script loader implementations: link.
var $script = require("scriptjs");
$script("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
$('body').html('It works!')
});
You can create a script tag in your JS as
$("body").append($("<script src="https://forio.com/tools/js-libs/1.5.0/epicenter.min.js"></script>"))
There is one html file that is definitely being used to serve to users with your js bundle attached. Probably you could attach the script tag into that html file
Use webpack's externals:
externals allows you to specify dependencies for your library that are
not resolved by webpack, but become dependencies of the output. This
means they are imported from the environment during runtime.
I have looked around for a solution and most of all proposals were based on externals, which is not valid in my case.
In this other post, I have posted my solution: https://stackoverflow.com/a/62603539/8650621
In other words, I finished using a separate JS file which is responsible for downloading the desired file into a local directory. Then WebPack scans this directory and bundles the downloaded files together with the application.

How to change path for i18n with RequireJS r.js build

I'm using RequireJS for my javascript project, and r.js to build one single javascript file for production. This single file (main.js) is then uploaded to a CDN. This all works very fine, but now I'm trying to add i18n support.
The problem is that the location of the i18n file is relative to the main javascript file. So within a module, I would have:
define(['i18n!nls/text'], function(Translation) { });
This all works very fine when I'm developing, but for production the problem is that the translation file is not relative to the main.js file as this is placed in a CDN. I don't want to store the translation file in the CDN, so how do I change the reference to that file in the build process?
I found a solution to my problem.
In the RequireJS config I've added:
requirejs.config({
paths: {
nls: "/js/nls"
}
});
Because the path starts with a slash, RequireJS knows it's not relative. Now the problem I got was that the build would fail, as RequireJS would be looking for default language files in /js/nls. Therefore, I added a symlink from the root of my webserver to the nls directory on the machine.
Had the same issue.
Use baseUrl config
require.config({
baseUrl: '/path_for_not_included_modules/'
});

How to use RequireJS build profile + r.js in a multi-page project

I am currently learning RequireJS fundamentals and have some questions regarding a build profile, main files, and use of RequireJS with multi-page projects.
My project's directory structure is as follows:
httpdocs_siteroot/
app/
php files...
media/
css/
css files...
js/
libs/
jquery.js
require.js
mustache.js
mains/
main.page1.js
main.page2.js
main.page3.js
plugins/
jquery.plugin1.js
jquery.plugin2.js
jquery.plugin3.js
utils/
util1.js
util2.js
images/
Since this project is not a single-page app, I have a separate main file for each page (although some pages use the same main file).
My questions are:
Is RequireJS even practical for projects that are not single-page?
Without using the optimizer, each of my main files start with essentially the same config options:
requirejs.config({
paths: {
'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min'
},
baseUrl: '/media/js/',
// etc...
});
require(['deps'], function() { /* main code */ });
Is there a way to avoid this? Like having each main file include the same build profile without having to actually build it?
Should r.js go in httpdocs_siteroot's parent directory?
Is there something glaringly wrong with my app dir structure or my use of RequireJS?
First of all, this is not a question with a unique solution. I'll explain the way I use RequireJS that works for me, and may work for you :)
Second, English is not my mother language. Corrections and tips about the language will be very appreciated. Feel free, guys :)
1) Is require js even practical for projects that are not single-page?
It depends. If your project does not have shared code between pages for example, RequireJS help will be modest. The main idea of RequireJS is modularize the application into chunks of reusable code. If your application uses only page-specific code, then using RequireJS may not be a good idea.
2) Without using the optimizer, each of my main files start with essentially the same config options. Is there a way to avoid this? Like having each main file include the same build profile without having to actually build it?
The only way I see is making the configuration on the main file, or create a module that will configure RequireJS and then use that module as the first dependency on main.js. But this can be tricky. I do not use many main.js files in my applications; I use only one that acts as a loader (see below).
3) Should r.js go in httpdocs_siteroot's parent directory?
Not necessarily. You can put it inside the /media directory, since all your client stuff is there.
4) Is there something glaringly wrong with my app dir structure or my use of requirejs?
I would not say that. On the other hand, the structure is perhaps a bit too fragmented. For example, you can put all '3rd party stuff' inside a /vendor directory. But this is just sugar; your structure will work well and seems right. I think the major problem is the requirejs.config() call in multiple main files.
I had the same problems you are having now and I ended up with the following solution:
1) Do not wrap the non-AMD-compliant files with a define. Although it works, you can achieve the same results using the "shim" property in requirejs.config (see below).
2) In a multi-page application, the solution for me is not to require the page-specific modules from the optimized main.js file. Instead, I require all the shared code (3rd party and my own) from the main file, leaving the page-specific code to load on each page. The main file ends up only being a loader that starts the page-specific code after loading all shared/lib files.
This is the boilerplate I use to build a multi-page application with requirejs
Directory structure:
/src - I put all the client stuff inside a src directory, so I can run the optimizer inside this directory (this is your media directory).
/src/vendor - Here I place all 3rd party files and plugins, including require.js.
/src/lib - Here I place all my own code that is shared by the entire application or by some pages. In other words, modules that are not page-specific.
/src/page-module-xx - And then, I create one directory for each page that I have. This is not a strict rule.
/src/main.js: This is the only main file for the entire application. It will:
configure RequireJS, including shims
load shared libraries/modules
load the page-specific main module
This is an example of a requirejs.config call:
requirejs.config({
baseUrl: ".",
paths: {
// libraries path
"json": "vendor/json2",
"jquery": "vendor/jquery",
"somejqueryplugion": "vendor/jquery.somejqueryplufin",
"hogan": "vendor/hogan",
// require plugins
"templ": "vendor/require.hogan",
"text": "vendor/require.text"
},
// The shim section allows you to specify
// dependencies between non AMD compliant files.
// For example, "somejqueryplugin" must be loaded after "jquery".
// The 'exports' attribute tells RequireJS what global variable
// it must assign as the module value for each shim.
// For example: By using the configutation below for jquery,
// when you request the "jquery" module, RequireJS will
// give the value of global "$" (this value will be cached, so it is
// ok to modify/delete the global '$' after all plugins are loaded.
shim: {
"jquery": { exports: "$" },
"util": { exports: "_" },
"json": { exports: "JSON" },
"somejqueryplugin": { exports: "$", deps: ["jquery"] }
}
});
And then, after configuration we can make the first require() request
for all those libraries and after that do the request for our "page main" module.
//libs
require([
"templ", //require plugins
"text",
"json", //3rd libraries
"jquery",
"hogan",
"lib/util" // app lib modules
],
function () {
var $ = require("jquery"),
// the start module is defined on the same script tag of data-main.
// example: <script data-main="main.js" data-start="pagemodule/main" src="vendor/require.js"/>
startModuleName = $("script[data-main][data-start]").attr("data-start");
if (startModuleName) {
require([startModuleName], function (startModule) {
$(function(){
var fn = $.isFunction(startModule) ? startModule : startModule.init;
if (fn) { fn(); }
});
});
}
});
As you can see in the body of the require() above, we're expecting another attribute on the require.js script tag. The data-start attribute will hold the name of the module for the current page.
Thus, on the HTML page we must add this extra attribute:
<script data-main="main" data-start="pagemodule/main" src="vendor/require.js"></script>
By doing this, we will end up with an optimized main.js that contains all the files in "/vendor" and "/lib" directories (the shared resources), but not the page-specific scripts/modules, as they are not hard-coded in the main.js as dependencies. The page-specific modules will be loaded separately on each page of the application.
The "page main" module should return a function() that will be executed by the "app main" above.
define(function(require, exports, module) {
var util = require("lib/util");
return function() {
console.log("initializing page xyz module");
};
});
EDIT
Here is example of how you can use build profile to optimize the page-specific modules that have more than one file.
For example, let's say we have the following page module:
/page1/main.js
/page1/dep1.js
/page1/dep2.js
If we do not optimize this module, then the browser will make 3 requests, one for each script.
We can avoid this by instructing r.js to create a package and include these 3 files.
On the "modules" attribute of the build profile:
...
"modules": [
{
name: "main" // this is our main file
},
{
// create a module for page1/main and include in it
// all its dependencies (dep1, dep2...)
name: "page1/main",
// excluding any dependency that is already included on main module
// i.e. all our shared stuff, like jquery and plugins should not
// be included in this module again.
exclude: ["main"]
}
]
By doing this, we create another per-page main file with all its dependencies. But, since we already have a main file that will load all our shared stuff, we don't need to include them again in page1/main module.
The config is a little verbose since you have to do this for each page module where you have more than one script file.
I uploaded the code of the boilerplate in GitHub: https://github.com/mdezem/MultiPageAppBoilerplate.
It is a working boilerplate, just install node and r.js module for node and execute build.cmd (inside the /build directory, otherwise it will fail because it uses relative paths)
I hope I have been clear. Let me know if something sounds strange ;)
Regards!
<script data-main="js/main" src="js/lib/require.js"></script>
// file: js/main
require(['./global.config'], function(){
require(['./view/home'], function() {
// do something
});
});
This is what I used in my project.

Categories

Resources