Resource bundle in javascript

Asset Modules

Asset Modules allow one to use asset files (fonts, icons, etc) without configuring additional loaders.

Prior to webpack 5 it was common to use:

  • raw-loader to import a file as a string
  • url-loader to inline a file into the bundle as a data URI
  • file-loader to emit a file into the output directory

Asset Modules types replace all of these loaders by adding 4 new module types:

  • asset/resource emits a separate file and exports the URL. Previously achievable by using file-loader .
  • asset/inline exports a data URI of the asset. Previously achievable by using url-loader .
  • asset/source exports the source code of the asset. Previously achievable by using raw-loader .
  • asset automatically chooses between exporting a data URI and emitting a separate file. Previously achievable by using url-loader with asset size limit.

When using the old assets loaders (i.e. file-loader / url-loader / raw-loader ) along with Asset Modules in webpack 5, you might want to stop Asset Modules from processing your assets again as that would result in asset duplication. This can be done by setting the asset’s module type to ‘javascript/auto’ .

webpack.config.js

module.exports = <  module:  rules: [   test: /\.(png|jpg|gif)$/i, use: [   loader: 'url-loader', options:  limit: 8192, > >, ], + type: 'javascript/auto'   >, ] >, >

To exclude assets that came from new URL calls from the asset loaders add dependency: < not: ['url'] >to the loader configuration.

webpack.config.js

module.exports = <  module:  rules: [   test: /\.(png|jpg|gif)$/i, + dependency: < not: ['url'] >,   use: [   loader: 'url-loader', options:  limit: 8192, >, >, ], >, ], > >

Resource assets

webpack.config.js

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist') >, + module:  + rules: [ +  + test: /\.png/, + type: 'asset/resource' + > + ] + >, >;
import mainImage from './images/main.png'; img.src = mainImage; // '/dist/151cfcfa1bd74779aadb.png'

All .png files will be emitted to the output directory and their paths will be injected into the bundles, besides, you can customize outputPath and publicPath for them.

Custom output filename

By default, asset/resource modules are emitting with [hash][ext][query] filename into output directory.

You can modify this template by setting output.assetModuleFilename in your webpack configuration:

webpack.config.js

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist'), + assetModuleFilename: 'images/[hash][ext][query]'   >, module:  rules: [   test: /\.png/, type: 'asset/resource' > ] >, >;

Another case to customize output filename is to emit some kind of assets to a specified directory:

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist'), + assetModuleFilename: 'images/[hash][ext][query]'   >, module:  rules: [   test: /\.png/, type: 'asset/resource' - > + >, +  + test: /\.html/, + type: 'asset/resource', + generator:  + filename: 'static/[hash][ext][query]' + > + >   ] >, >;

With this configuration all the html files will be emitted into a static directory within the output directory.

Rule.generator.filename is the same as output.assetModuleFilename and works only with asset and asset/resource module types.

Inlining assets

webpack.config.js

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist'), - assetModuleFilename: 'images/[hash][ext][query]'   >, module:  rules: [  - test: /\.png/, - type: 'asset/resource' + test: /\.svg/, + type: 'asset/inline' - >, + > -  - test: /\.html/, - type: 'asset/resource', - generator:  - filename: 'static/[hash][ext][query]' - > - >   ] > >;
- import mainImage from './images/main.png'; + import metroMap from './images/metro.svg';  - img.src = mainImage; // '/dist/151cfcfa1bd74779aadb.png' + block.style.background = `url($)`; // url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo. vc3ZnPgo=)

All .svg files will be injected into the bundles as data URI.

Custom data URI generator

By default, data URI emitted by webpack represents file contents encoded by using Base64 algorithm.

If you want to use a custom encoding algorithm, you may specify a custom function to encode a file content:

webpack.config.js

const path = require('path'); + const svgToMiniDataURI = require('mini-svg-data-uri');  module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist') >, module:  rules: [   test: /\.svg/, type: 'asset/inline', + generator:  + dataUrl: content =>  + content = content.toString(); + return svgToMiniDataURI(content); + > + >   > ] >, >;

Now all .svg files will be encoded by mini-svg-data-uri package.

Source assets

webpack.config.js

const path = require('path'); - const svgToMiniDataURI = require('mini-svg-data-uri');  module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist') >, module:  rules: [  - test: /\.svg/, - type: 'asset/inline', - generator:  - dataUrl: content =>  - content = content.toString(); - return svgToMiniDataURI(content); - > - > + test: /\.txt/, + type: 'asset/source',   > ] >, >;

src/example.txt

- import metroMap from './images/metro.svg'; + import exampleText from './example.txt';  - block.style.background = `url($); // url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDo. vc3ZnPgo=) + block.textContent = exampleText; // 'Hello world'

All .txt files will be injected into the bundles as is.

URL assets

When using new URL(‘./path/to/asset’, import.meta.url) , webpack creates an asset module too.

const logo = new URL('./logo.svg', import.meta.url);

Depending on the target in your configuration, webpack would compile the above code into a different result:

// target: web new URL( __webpack_public_path__ + 'logo.svg', document.baseURI || self.location.href ); // target: webworker new URL(__webpack_public_path__ + 'logo.svg', self.location); // target: node, node-webkit, nwjs, electron-main, electron-renderer, electron-preload, async-node new URL( __webpack_public_path__ + 'logo.svg', require('url').pathToFileUrl(__filename) );

As of webpack 5.38.0, Data URLs are supported in new URL() as well:

const url = new URL('data:,', import.meta.url); console.log(url.href === 'data:,'); console.log(url.protocol === 'data:'); console.log(url.pathname === ',');

General asset type

webpack.config.js

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist') >, module:  rules: [  + test: /\.txt/, + type: 'asset',   > ] >, >;

Now webpack will automatically choose between resource and inline by following a default condition: a file with size less than 8kb will be treated as a inline module type and resource module type otherwise.

You can change this condition by setting a Rule.parser.dataUrlCondition.maxSize option on the module rule level of your webpack configuration:

webpack.config.js

const path = require('path'); module.exports = <  entry: './src/index.js', output:  filename: 'main.js', path: path.resolve(__dirname, 'dist') >, module:  rules: [   test: /\.txt/, type: 'asset', + parser:  + dataUrlCondition:  + maxSize: 4 * 1024 // 4kb + > + >   > ] >, >;

Also you can specify a function to decide to inlining a module or not.

Replacing Inline Loader Syntax

Before Asset Modules and Webpack 5, it was possible to use inline syntax with the legacy loaders mentioned above.

It is now recommended to remove all inline loader syntax and use a resourceQuery condition to mimic the functionality of the inline syntax.

For example, in the case of replacing raw-loader with asset/source type:

- import myModule from 'raw-loader!my-module'; + import myModule from 'my-module?raw';

and in the webpack configuration:

module: <  rules: [ // . +  + resourceQuery: /raw/, + type: 'asset/source', + >   ] >,

and if you’d like to exclude raw assets from being processed by other loaders, use a negative condition:

module: <  rules: [ // . +  + test: /\.m?js$/, + resourceQuery: < not: [/raw/] >, + use: [ . ] + >,     resourceQuery: /raw/, type: 'asset/source', > ] >,

or a oneOf list of rules. Here only the first matching rule will be applied:

module: <  rules: [ // . + < oneOf: [     resourceQuery: /raw/, type: 'asset/source', >, +  + test: /\.m?js$/, + use: [ . ] + >, + ] >   ] >,

Disable emitting assets

For use cases like Server side rendering, you might want to disable emitting assets, which is feasible with emit option under Rule.generator :

module.exports =  // … module:  rules: [  test: /\.png$/i, type: 'asset/resource', generator:  emit: false, >, >, ], >, >;

Further Reading

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A jQuery Plugin used for extracting html embedded copy strings

acatl/resourcebundle

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

ResourceBundle is a jQuery Plugin, it is intended to help you separate content from code and localize your applications.

For example if you wish to display a message on your page, you will not have to hardcode the message on the page/javascript itself, instead you will pull your messages from property source that the ResourceBundle will load and parse. Then you will be able to access the resources through the ResourceBundle plugin.

Add the file to your HTML

script src pl-s">https://yoursite.com/javascripts/plugins/jquery.resourcebundle.js" type pl-s">text/javascript">script> 

Add a tag that will contain your property source that ResourceBundle will be linked to:

script id pl-s">resources" type pl-s">text/plain"> script>

Add some properties to your resource tag, each property should be in the form of key=value pairs.

script id pl-s">resources" type pl-s">text/plain"> message1=Hi this is a message message2=Another message template_message=Hello my name is: $Name> how are you today? script>

You now may load your resource bundle for example:

$(document).ready( function ()  var resources = $.getResourceBundle("resources"); >);

To access your resources you may do:

$(document).ready( function ()  var resources = $.getResourceBundle("resources"); alert(resources.getString("message2")); >);

which would result in an alert with: Another message

enjoy! feedback is more than welcomed!

About

A jQuery Plugin used for extracting html embedded copy strings

Источник

Читайте также:  Метод compute java map
Оцените статью