What HashedModuleIdsPlugin do? - javascript

What does HashedModuleIdsPlugin do?
From Webpack docs:
This plugin will cause hashes to be based on the relative path of the module, generating a four character string as the module id. Suggested for use in production.
After reading it couple of times, I still can't understand why and when to use it and how it is related to the way I define a name to each bundle in output section:
filename: '[contenthash].[name].js',

I understand it this way, webpack 4.3 added contenthash, but before that, you can use HashedModuleIdsPlugin, I am not quite sure.
https://github.com/webpack/webpack/releases/tag/v4.3.0

By default, Webpack will create a list of modules (all the imported packages you have, as well as project files) and this list will be an array. The "module ID" (the pointer to the actual module code) will be the array index.
HashedModuleIdsPlugin will define this module list as an object, where the keys are the generated hash (from the relative file name) and the values will be the actual module code.
There is also the NamedModulesPlugin (if we're talking Webpack 3), which does the same thing but instead of a hash, the key is the actual relative path, for example:
"./node_modules/tiny-relative-date/lib/factory.js": function(e, t, n) {
In Webpack 4+, this was replaced by: https://webpack.js.org/configuration/optimization/#optimizationmoduleids

Related

Resolving JavaScript modules via 'gf' in Vim when using a Webpack tilde alias

I'm a new member of a Vue.js project that uses the tilde (~) notation in module imports, as in
import WhateverApi from '~/api/whatever';
The project repository contains all kinds of files all thrown together: a Vagrant machine, a Laravel backend application, config files and a Vue.js SPA. The latter is in a nested folder structure (resources/assets/js/), which should be interpreted as the project root, hence ~.
Using Vim, I'm used to being able to jump to a linked file via gf. When I do that on the path shown above, Vim complains that the file does not exist, as it probably interprets the tilde (somewhat correctly) as the user's home folder.
Googling yielded no result, mainly because I'm at a loss what exactly to search for. This appears to be some magic Webpack is doing. As the other team members use WebStorm/PHPStorm, they do not have this problem.
How do I get Vim to resolve the path correctly within the project scope?
Update with an example:
Webpack has an alias setting, which allows to define any path as an alias to use in source code files. It looks like this:
resolve: {
alias: {
vue$: 'vue/dist/vue.esm.js',
'~': path.resolve(__dirname, 'resources/assets/js'),
sass: path.resolve(__dirname, 'resources/assets/sass'),
},
extensions: ['*', '.js', '.vue', '.json'],
},
Ignore the $vue key, it's specific to Vue.js with Webpack. ~ and sass are interesting. The first one is basically a substitute filter that exchanges every ~ in paths to resources/assets/js. The same for sass with it's according path. However, the import statements vary. Here's an example of a Vue single file component with both import statements as an example:
<template>
<div>
<p>Some content.</p>
</div>
</template>
<script>
import WhateverApi from '~/api/whatever';
export default {};
</script>
<style lang="scss" scoped>
#import '~sass/variables/all';
</style>
Now, when using gf, it would be fantastic if it could resolve those (weird) combinations according to the following rules:
Paths starting with ~/ should replace ~ to resources/assets/js and try to find files by attaching the extensions .js, .vue and .json.
Paths starting with ~sass should replace ~ to resources/assets/sass and try to find files by attaching the extension .scss.
I know this is involved — and happened way before I joined the team. There's an interesting project trying to simplify this (https://github.com/davidosomething/vim-enhanced-resolver) but unfortunately it appears to be broken, as it throws errors trying to resolve an existing path.
Any help is greatly appreciated.
Googling yielded no result, mainly because I'm at a loss
what exactly to search for.
For Vim help, try first Vim help itself. For example, which
command are you using? If it is gf, check the help of gf
to see how it works:
:h gf
[count]gf Edit the file whose name is under or after the cursor.
Mnemonic: "goto file".
Uses the 'isfname' option to find out which characters
are supposed to be in a file name. Trailing
punctuation characters ".,:;!" are ignored. Escaped
spaces "\ " are reduced to a single space.
Uses the 'path' option as a list of directory names to
look for the file. See the 'path' option for details
about relative directories and wildcards.
Uses the 'suffixesadd' option to check for file names
with a suffix added.
If the file can't be found, 'includeexpr' is used to
modify the name and another attempt is done.
You can also check :h 'includeexpr'. For example, this
will expand an initial ~ to resources/assets/js:
set inex=substitute(v:fname,'^\\~','resources/assets/js','')
After sidyll pointed me in the right direction, I managed to get this to work after quite some tinkering and reading help pages. The secret is a combination of recursive substitute() calls, regex capture groups and suffixesadd:
set includeexpr=substitute(substitute(v:fname,'^\\~\/','resources/assets/js/',''),'^\\~sass/\\(.*\\)/\\(.*\\)$','resources/assets/sass/\\1/_\\2','')
set suffixesadd=.js,.vue,.scss
This is rather ugly but that's Vimscript for you.
The method with substitude and includeexpr involves storing a project path in the vim configuration. it's far from ideal.
With the plugin vim-npr, I managed to do that perfectly.

Webpack makes invalid bundle when change the module's name case

it may sounds strange, but when I change the module name in my application, webpack changes the bundle output and makes it wrong. I have windows, it means that module paths should be case insensitive and the bundles must be the same all the time. Webpack shows me that some modules have ambiguous names and it can affect if you are using case-sensitive OS, but nevertheless the bundle works correct.
Then I fixed by changing the names in require from lower-case component to uppercase Component and after that webpack begins making invalid bundle, and there are a lot of diffs if you compare these two output bundles. My questions are: why does webpack behave different with case-sensitive names in case-insensitive environment and how to fix it? Maybe it changes the modules order or something like this.
P.S. The app is big: ~2.5 mb.
P.S.S. The problem is in inheritance. I use TypeScript and the error is that I try to extend from undefined.
Thanks!
why does webpack behaves different with case-sensitive name in case-insensitive environment
The true enviroment for webpack is the web and the web is case sensitive. Also it's probably just ordering e.g. alphabetically and that will change the ordering with changing names.
The problem is in inheritance. I use TypeScript and the error is that I try to extend from undefined
You might have a circular reference in there. The fact that it worked before is conincidental (e.g. the ordering by file names satisfied what was expected).
Fix
Remove the circular reference. E.g. use atom-typescript to find it : https://github.com/TypeStrong/atom-typescript/blob/master/docs/dependency-view.md#circular

RequireJS - exclude by directory (or regex)

This is a portion of my build configuration for requireJS's optimizer, r.js.
exclude: [
'widgets/cr-log-display',
'widgets/cr-pager',
'widgets/cr-time-input'
My question is simply this: is it possible to exclude ALL dependencies starting with widgets/.
The docs don't seem to indicate that a regex, or anything similar can be passed here. Is there another configuration parameter that I'm missing?
I'm pretty sure you cannot pass a regular expression to exclude. I'm saying this from having read the source of r.js. The processing of exclude uses an internal function named findBuildModule, which compares what is passed to exclude against module names with ===. And by the same token, there is no way to tell r.js "exclude all modules under this directory".
The one avenue I see you might be able to use is onBuildWrite, which is a global setting that takes a function. I've used it for other purposes than what you want but perhaps this would do the trick:
onBuildWrite: function (moduleName, path, contents) {
return /^widgets\//.test(moduleName) ? "" : contents;
}
If the module name starts with widgets/ then the contents that will be written to the bundle will be the empty string, otherwise the contents will be whatever the module's contents happen to be.
Note that this will not do exactly what exclude does. The exclude setting excludes the listed modules and their dependencies. The onBuildWrite example above is an analogue to excludeShallow in that the modules that match the regular expression will be excluded but their dependencies won't be excluded. There is no way to easily write an onBuildWrite function that will extend the exclusion to dependencies of the modules that you'd like to exclude. r.js does not give an API to query dependencies of a module.

RequireJS - Omitting testing code from optimized build

I have been looking into integrating testing into my app based on RequireJS. I have found this example of how QUnit testing could be integrated into the RequireJS structure. Obviously you don't want the testing code to be lying around in the Production build. How can you keep testing out of the final production build in RequireJS?
There are lots of options you can set in the build file. See the full example on GitHub (https://github.com/jrburke/r.js/blob/master/build/example.build.js)
What you want to do is exclude certain items from your module:
//This module entry combines all the dependencies of foo/bar/bip into one file,
//but excludes foo/bar/bop and its dependencies from the built file. If you want
//to exclude a module that is also another module being optimized, it is more
//efficient if you define that module optimization entry before using it
//in an exclude array.
{
name: "foo/bar/bip",
exclude: [
"foo/bar/bop"
]
},
//This module entry shows how to specify a specific module be excluded
//from the built module file. excludeShallow means just exclude that
//specific module, but if that module has nested dependencies that are
//part of the built file, keep them in there. This is useful during
//development when you want to have a fast bundled set of modules, but
//just develop/debug one or two modules at a time.
{
name: "foo/bar/bin",
excludeShallow: [
"foo/bar/bot"
]
}
You can also exclude items with a regular expression, but this is probably overkill:
//When the optimizer copies files from the source location to the
//destination directory, it will skip directories and files that start
//with a ".". If you want to copy .directories or certain .files, for
//instance if you keep some packages in a .packages directory, or copy
//over .htaccess files, you can set this to null. If you want to change
//the exclusion rules, change it to a different regexp. If the regexp
//matches, it means the directory will be excluded. This used to be
//called dirExclusionRegExp before the 1.0.2 release.
//As of 1.0.3, this value can also be a string that is converted to a
//RegExp via new RegExp().
fileExclusionRegExp: /^\./,

nodeJS require.paths resolve problem

I am trying to require a file relatively and mysteriously the following is happening
This works well which points to /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
This doesn't but it should point to exactly the same file:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
Anyone knows why I can't still use ./ in this case for loading the path since
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
results in:
"/Users/marcos/Desktop/Taper/lib/utils"
anyway?
Thanks in advance
UPDATED:
From the documentation:
A module prefixed with '/' is an absolute path to the file. For
example, require('/home/marco/foo.js') will load the file at
/home/marco/foo.js.
A module prefixed with './' is relative to the file calling require().
That is, circle.js must be in the same directory as foo.js for
require('./circle') to find it.
Without a leading '/' or './' to indicate a file, the module is either
a "core module" or is loaded from a node_modules folder.
If the given path does not exist, require() will throw an Error with
its code property set to 'MODULE_NOT_FOUND'.
Here’s the original answer, which refers to require.paths (which is no longer supported):
From the documentation:
In node, require.paths is an array of strings that represent paths to be searched for modules when they are not prefixed with '/', './', or '../'.
(emphasis mine)
You can pass that using NODE_PATH
Example:
NODE_PATH=`pwd` node app.js
I created a new node module called rekuire.
It allows you to "require" without using relative paths.
It's a big time saver when it comes to testing/refactoring.
https://npmjs.org/package/rekuire

Categories

Resources