Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Plugins and loaders for webpack used with Dojo

License

NotificationsYou must be signed in to change notification settings

dojo/webpack-contrib

Repository files navigation

Build Statuscodecovnpm version

This repository contains all of the custom Webpackplugins andloaders used by@dojo/cli-build-app and@dojo/cli-build-widget to facilitate building Dojo 2 applications and widgets, respectively.


Usage

To use@dojo/webpack-contrib in a single project, install the package:

npm install @dojo/webpack-contrib

Loaders

css-module-decorator-loader

A webpack loader that injects CSS module path information into the generated modules, making it easier for@dojo/widget-core to resolve theme styles. This loader takes no options.

css-module-dts-loader

A webpack loader that generates.d.ts files for CSS modules. This is used by both@dojo/cli-build-app and@dojo/cli-build-widget to provide in-widget type checks for CSS classes.

The loader expects the following options:

PropertyTypeOptionalDescription
type'ts' or'css'NoThe type of file being processed. Ifts, the loader assumes the resource is a TypeScript file and will parse it for CSS module imports. If any CSS modules are found, then the loader generates ad.ts file for each. Ifcss is specified, then the loader assumes the resource is a CSS module and generates the.d.ts file for it.
instanceNamestringYesAn optional instance name for the TypeScript compiler created by thets-loader. This option is valid only when thetype ists, and ensures the same compiler instance is used across all files.

Example:

constwebpackConfig={loaders:[// Generate `.d.ts` files for all CSS modules imported in TypeScript files beneath// the `src/` directory{include:'./src/',test:/\.ts$/,enforce:'pre',loader:'@dojo/webpack-contrib/css-module-dts-loader?type=ts&instanceName=APP_NAME'},// Generate `.d.ts` files for all CSS modules beneath the `src/` directory{include:'./src/',test:/\.m\.css$/,enforce:'pre',loader:'@dojo/webpack-contrib/css-module-dts-loader?type=css'}]};

promise-loader

A webpack loader that returns a promise fromrequire() calls that resolves to the requested resource. It also removes absolute paths from source maps, ensuring consistent builds across environments. It is used by@dojo/cli-build-app for lazily loading bundles.

This loader expects two parameters, one required and one optional:

  1. The required promise implementation (e.g.,bluebird). If there already exists a globalPromise constructor, thenglobal should be specified.
  2. An optional chunk name.

Example:

constresourcePromise=require('@dojo/webpack-contrib/promise-loader?global,resource-chunk-name!./path/to/resource');resourcePromise.then((resource)=>{// resource is available})

static-build-loader

A webpack loader which allows code to be statically optimized for a particular context at bundling time.This loader acts on JavaScript. Some examples show the TypeScript source, but the loader will onlywork if acting on the compiled output.

Features

The loader examines code, looking for usages of@dojo/has,@dojo/has.exists,@dojo/has.add, orhas pragmas tooptimize. It does this by parsing theAST structure of the code, and modifying it when appropriate.

The loader takes three options:

  • features: A map ofstatic features or a feature or list of features that resolve to a similar static mapbased on the functionality provided by the specified targets. Each key in the map is the name of the featureand the value istrue if the feature is present in that context, otherwisefalse.
  • isRunningInNode: An optional boolean parameter. If set tofalse this indicates that the loader will not berunning in an environment with a Node-like require.
  • staticOnly: A list of feature keys that shouldnot havehas.add calls modified. In most cases, this optionwill not be needed. It is provided for cases where a module will sometimes be parsed and have its flags resolved statically if so, butmay also not be parsed and may require a different runtime value for the flag.

For example in a webpack configuration, the map of features would look like this:

{use:[{loader:'@dojo/webpack-contrib/static-build-loader',options:{features:{'foo':true,'bar':false},staticOnly:['bar']}}]};

This asserts featurefoo istrue and featurebar isfalse.Alternatively a list of features can be provided that will be resolved to the appropriate map

{use:[{loader:'@dojo/webpack-contrib/static-build-loader',options:{features:['firefox','chrome']}}]}

Available features

When specifying a static map, any values can be used. When passing a string or list of strings, the followingvalues are supported. Each value corresponds to the set of known features that the environment supports. Ifmultiple features are specified, the intersection of available features will be returned.

  • android
  • chrome
  • edge
  • firefox
  • ie11
  • ios
  • node
  • node8
  • safari

In either case, the resulting map is then used in the features below.

Dead Code Removal

The loader assumes that the@dojo/has API is being used in modules that are being compiledinto a webpack bundle and attempts to rewrite calls to thehas() API when it can see it has a statically asserted flag forthat feature.

The loader detects structures like the following in transpiled TypeScript modules:

importhasfrom'./has';if(has('foo')){console.log('has foo');}else{console.log('doesn\'t have foo');}constbar=has('bar') ?'has bar' :'doesn\'t have bar';

And will rewrite the code (given the static feature set above), like:

importhasfrom'./has';if(true){console.log('has foo');}else{console.log('doesn\'t have foo');}constbar=false ?'has bar' :'doesn\'t have bar';

When this is minified via Uglify via webpack, Uglify looks for structures that can be optimised and would re-write it further tosomething like:

importhasfrom'./has';console.log('has foo');constbar='doesn\'t have bar';

Any features which are not statically asserted, are not re-written. This allows the code to determine at run-time if the featureis present.

Elided Imports

The loader looks forhas pragmas, which are strings that contain a call to has for a specific feature, andremoves the next import found in the code. For example, given the above feature set, which hasfoo = true andbar = false, the imports of'a' and'b' would be removed but'c' and'd' would remain.

"has('foo')";conststatementBeforeImport=3;// This is the next import so it will be removed despite// the conetnet between it and the pragmaimport'a';// The pragma can be negated to remove the import if the condition// is known to be false'!has("bar")';import'b';'!has("foo")';// This import will not be removed because `foo` is not falseimport'c';'has("baz")';// This import will not be removed because the value of `has('baz')`// is now known staticallyimport'd';

Plugins

build-time-render

A webpack plugin that generates a bundle's HTML and inlines critical CSS at build time. This is similar to server-side rendering, but does not require a dedicated server to manage it.

The plugin takes an options object with the following properties:

PropertyTypeOptionalDescription
entriesstring[]NoThe entry scripts to include in the generated HTML file
pathsstring[] or{ path: string; match: string[] }YesAn array of paths that will be matched against the URL hash, rendering the HTML associated with any matched path. If the path is a string, then it will be compared directly towindow.location.hash. If the path is an object, then it should include apath string that will be used to resolve the HTML, andmatch string array that represents multiple paths that should trigger thepath to be rendered. Defaults to an empty array ('[]').
rootstringYesThe ID for the root HTML element. If falsy, then no HTML will be generated. Defaults to an emtpy string ('').
useManifestbooleanYesDetermines whether a manifest file should be used to resolve the entries. Defaults tofalse.
staticbooleanYesRemoves js and css scripts tags from generatedindex.html files for truly static sites. Not compatible with hash routing. Defaults tofalse.

Usage

Beyond the plugin itself, it is also beneficial to include the@dojo/webpack-contrib/build-time-render/hasBuildTimeRender module in theentry config option. This file adds thehas('build-item-render') flag that applications can use to determine whether the app has been pre-rendered.

The following example will generate an HTML file containing<script> tags for the specifiedentries, along with the critical CSS and HTML for the root,#account, and#help paths. Both the#faq and#contact hashes will display the#help HTML.

importBuildTimeRenderfrom'@dojo/webpack-contrib/build-time-render/BuildTimeRender';constentry={main:{'@dojo/webpack-contrib/build-time-render/hasBuildTimeRender','./src/main.ts','./src/main.css'}};constwebpackConfig={entry,plugins:[newBuildTimeRender({entries:Object.keys(entry),paths:['#account',{path:'#help',match:['faq','contact']}],root:'app',useManifest:true})]};

css-module-plugin

A webpack plugin that converts.m.css import paths to.m.css.js. This is used in conjunction with thecss-module-dts-loader loader to ensure that webpack can probably resolve CSS module paths.

If the requested resource uses a relative path, then its path will be resolved relative to the requesting module. Otherwise, the resource will be loaded from${basePath}node_modules (see below for the definition ofbasePath):

// Path is relative to the current moduleimport*aslocalCssfrom'./path/to/local-styles.m.css';// Imported from node_modulesimport*asexternalCssfrom'some-mid/styles.m.css';

The plugin constructor accepts a single argument:

PropertyTypeOptionalDescription
basePathstringNoThe root path from which to resolve CSS modules

emit-all-plugin

Webpack is a bundler, which does not work well when build libraries. Rather than create separate toolchains for building libraries and applications/custom elements, the existing build tooling can be used to emit library files by way of theemitAllFactory that produces both a plugin instance and a custom TypeScript transformer. The transformer is needed to ensure that any.d.ts dependencies are correctly emitted, while the plugin ensures assets are emitted as individual files instead of as a generated bundle:

import{emitAllFactory}from'@dojo/webpack-contrib/emit-all-plugin/EmitAllPlugin';// See list of available options belowconstemitAll=emitAllFactory(options);constconfig={// ...plugins:[...,emitAll.plugin],module:{rules:[// ...{test:/.*\.ts(x)?$/,use:[{loader:'ts-loader',options:{// ...getCustomTransformers(program){return{before:[emitAll.transformer()]};}}}]}]}}

At the very least CSS and transpiled TS files will be emitted, but additional assets can be included with a filter.

The factory takes an options object with the following properties:

PropertyTypeOptionalDescription
basePathstringYesThe base path for the project's source files. Only files within this directory are emitted. Defaults to the project'ssrc/ directory.
inlineSourceMapsbooleanYesSpecifies whether sources maps should be inlined with the output source files or emitted separately. Defaults tofalse.
legacybooleanYesSpecifies whether TypeScript files should be transpiled to ES modules or to legacy JavaScript. Defaults tofalse.
assetFilterFunctionYesUsed to filter assets to only those that should be included in the output. Accepts the asset file path and the asset object. If the function returnstrue, the asset will be emitted; otherwise it will be excluded.

external-loader-plugin

External libraries that cannot be loaded normally via webpack can be included in a webpack build using this plugin.

The plugin takes an options object with the following properties:

PropertyTypeOptionalDescription
dependenciesExternalDep[]NoExternal dependencies to load. Described in more detail below
hashbooleanYesWhether to use the build's hash to cache bust injected dependencies
outputPathstringYesWhere to copy dependencies to; defaults to "externals"
pathPrefixstringYesUsed to change the directory where files are placed(e.g. placing files in_build for testing)

All external dependencies specified in thedependencies options will be placed in${pathPrefix}/${outputPath}.EachExternalDep in thedependencies array specifies one external dependency. Each can be astring, indicating a path that should be delegated to the configured loader, or an object with the followingproperties:

PropertyTypeoptionalDescription
fromstringfalseA path relative to the root of the project specifying the dependency location to copy into the build application.
tostringtrueA path that replacesfrom as the location to copy this dependency to. By default, dependencies will be copied to${externalsOutputPath}/${to} or${externalsOutputPath}/${from} ifto is not specified. If the path includes. characters, it must end in a forward slash to be treated as a directory
namestringtrueIndicates that this path, and any children of this path, should be loaded via the external loader
injectstring, string[], or booleantrueThis property indicates that this dependency defines, or includes, scripts or stylesheets that should be loaded on the page. Ifinject is set totrue, then the file at the location specified byto orfrom will be loaded on the page. If this dependency is a folder, theninject can be set to a string or array of strings to define one or more files to inject. Each path ininject should be relative to${externalsOutputPath}/${to} or${externalsOutputPath}/${from} depending on whetherto was provided.

i18n-plugin

Rather than manually set locale data within an application's entry point, that data can instead be read from a config and injected in at build time.

The plugin accepts an options object with the following properties:

PropertyTypeOptionalDescription
cldrPathsstring[]YesAn array of paths to CLDR JSON modules that should be included in the build and registered with the i18n ecosystem. If a path begins with a ".", then it is treated as relative to the current working directory. Otherwise, it is treated as a valid mid.
defaultLocalestringNoThe default locale.
supportedLocalesstring[]YesAn array of supported locales beyond the default.
targetstringYesThe entry point into which the i18n module should be injected. Defaults tosrc/main.ts.

A custom module is generated from the locale data, injected into the bundle, and then imported into the specified entry point. The user's locale is compared against the default locale and supported locales, and if it is supported is set as the root locale for the application. If the user's locale is not supported, then the default locale is used. For example, the user's locale will be used in the following scenarios:

The user's locale can be represented by the default locale:

  • Default Locale: 'en'
  • Supported Locales: none
  • User's locale: 'en-US'

The user's locale can be represented by one of the supported locales:

  • Default Locale: 'en'
  • Supported Locales: [ 'fr' ]
  • User's locale: 'fr-CA'

However, in the following scenario the default locale will be used, although it still will be possible to switch between any of the supported locales at run time, since their required data will also be included in the build:

  • Default Locale: 'en'
  • Supported Locales: [ 'de', 'ja', 'ar' ]
  • User's locale: 'cz'

service-worker-plugin

A custom webpack plugin that generates a service worker from configuration options, or simply ensures a custom service worker is copied to the output directory. Generated service workers support both precaching and runtime caching and allow you specify additional resources that should be loaded by the service worker.

The plugin accepts either a string path for an existing service worker to copy to the output directory, or an options object with the following properties:

PropertyTypeOptionalDescription
bundlesstring[]YesAn array of bundles to include in the precache. Defaults to all bundles.
cachePrefixstringYesThe prefix to use for the runtime precache cache.
clientsClaimbooleanYesWhether the service worker should start controlling clients on activation. Defaults tofalse.
excludeBundlesstring[]YesAn array of bundles to include in the precache. Defaults to[].
importScriptsstring[]YesAn array of script paths that should be loaded within the service worker
precacheobjectYesAn object of precache configuration options (see below)
routesobject[]YesAn array of runtime caching config objects (see below)
skipWaitingbooleanYesWhether the service worker should skip the waiting lifecycle

Precaching

Theprecache option can take the following options to control precaching behavior:

PropertyTypeOptionalDescription
baseDirstringYesThe base directory to matchinclude against.
ignorestring[]YesAn array of glob pattern string matching files that should be ignored when generating the precache. Defaults to[ 'node_modules/**/*' ].
includestring orstring[]YesA glob pattern string or an array of glob pattern strings matching files that should be included in the precache. Defaults to all files in the build pipeline.
indexstringYesThe index filename that should be checked if a request fails for a URL ending in/. Defaults to'index.html'.
maxCacheSizenumberYesThe maximum size in bytes a file must not exceed to be added to the precache. Defaults to2097152 (2 MB).
strictbooleanYesIftrue, then the build will fail if aninclude pattern matches a non-existent directory. Defaults totrue.
symlinksbooleanYesWhether to follow symlinks when generating the precache. Defaults totrue.

Runtime Caching

In addition to precaching, strategies can be provided for specific routes to determine whether and how they can be cached. Thisroutes option is an array of objects with the following properties:

PropertyTypeOptionalDescription
urlPatternstringNoA pattern string (which will be converted a regular expression) that matches a specific route.
strategystringNoThe caching strategy (see below).
optionsobjectYesAn object of additional options, each detailed below.
cacheNamestringYesThe name of the cache to use for the route. Note that thecachePrefix isnot prepended to the cache name. Defaults to the main runtime cache (${cachePrefix}-runtime-${domain}).
cacheableResponseobjectYesUses HTTP status codes and or headers to determine whether a response can be cached. This object has two optional properties:statuses andheaders.statuses is an array of HTTP status codes that should be considered valid for the cache.headers is an object of HTTP header and value pairs; at least one header must match for the response to be considered valid. Defaults to{ statuses: [ 200 ] } when thestrategy is'cacheFirst', and{ statuses: [0, 200] } when thestrategy is eithernetworkFirst orstaleWhileRevalidate.
expirationobjectYesControls how the cache is invalidated. This object has two optional properties.maxEntries is the number of responses that can be cached at any given time. Once this max is exceeded, the oldest entry is removed.maxAgeSeconds is the oldest a cached response can be in seconds before it gets removed.
networkTimeoutSecondsnumberYesUsed with thenetworkFirst strategy to specify how long in seconds to wait for a resource to load before falling back on the cache.

Strategies

Four routing strategies are currently supported:

  • networkFirst attempts to load a resource over the network, falling back on the cache if the request fails or times out. This is a useful strategy for assets that either change frequently or may change frequently (i.e., are not versioned).
  • cacheFirst loads a resource from the cache unless it does not exist, in which case it is fetched over the network. This is best for resources that change infrequently or can be cached for a long time (e.g., versioned assets).
  • networkOnly forces the resource to always be retrieved over the network, and is useful for requests that have no offline equivalent.
  • staleWhileRevalidate requests resources from both the cache and the network simulaneously. The cache is updated with each successful network response. This strategy is best for resources that do not need to be continuously up-to-date, like user avatars. However, when fetching third-party resources that do not send CORS headers, it is not possible to read the contents of the response or verify the status code. As such, it is possible that a bad response could be cached. In such cases, thenetworkFirst strategy may be a better fit.

Example

importServiceWorkerPluginfrom'@dojo/webpack-contrib/service-worker-plugin/ServiceWorkerPlugin';newServiceWorkerPlugin({cachePrefix:'my-app',// exclude the "admin" bundle from cachingexcludeBundles:['admin'],routes:[// Use the cache-first strategy for loading images, adding them to the "my-app-images" cache.// Only the first ten images should be cached, and for one week.{urlPattern:'.*\\.(png|jpg|gif|svg)',strategy:'cacheFirst',cacheName:'my-app-images',expiration:{maxEntries:10,maxAgeSeconds:604800}},// Use the cache-first strategy to cache up to 25 articles that expire after one day.{urlPattern:'http://my-app-url.com/api/articles',strategy:'cacheFirst',expiration:{maxEntries:25,maxAgeSeconds:86400}}]});

webpack-bundle-analyzer

A webpack plugin that provides a visualization of the size of webpack output with an interactive sunburst graphic.Functionally this is a copy ofwebpack-bundle-analyzer with a custom visualization.

The plugin accepts an options object with the following optional properties.

PropertyTypeDescriptionDefault
analyzerMode'server' or 'static' or 'disabled'Whether to serve bundle analysis in a live server, render the report in a static HTML file or files, or to disable visual report generation entirely.`'server'
analyzerPortnumberThe port to use inserver mode8888
reportFilenamestringPath to the report bundle file. Multiple report will be created with-<bundleName> appended to this value if there is more than one output bundle.'report.html'
openAnalyzerbooleanWhether the report should be opened in a browser automaticallytrue
generateStatsFilebooleanWhether a JSON Webpack Stats file should be generatedfalse
statsFilenamestringName to use for the stats file if one is generated'stats.json'
statsOptonsanyOptions to pass tostats.toJson(). More documentation can be foundherenull
logLevel'info' or 'warn' or 'error' or 'silent'The level of logs from this plugin'info'

Example

importBundleAnalyzerPluginfrom'@dojo/webpack-contrib/webpack-bundle-analyzer/BundleAnalyzerPlugin';newBundleAnalyzerPlugin({analyzerMode:'static',reportFilename:'../info/report.html',openAnalyzer:false});

bootstrap-plugin

A custom webpack plugin that conditionally loads supported dojo shims based on usage and browser capabilities.

Supported Shims

  • @dojo/framework/shim/IntersectionObserver
  • @dojo/framework/shim/ResizeObserver
  • @dojo/framework/shim/WebAnimations

To use the plugin, use the providedbootstrap.js from@dojo/webpack-contrib/bootstrap-plugin as the application entry and add the plugin to the webpack configuration.

TheBootstrapPlugin accepts requires the path to application entry point and an array ofshimModules to process.

newBootstrapPlugin({entryPath:mainEntryPath,shimModules:[{module:'@dojo/framework/shim/IntersectionObserver',has:'intersection-observer'},{module:'@dojo/framework/shim/ResizeObserver',has:'resize-observer'},{module:'@dojo/framework/shim/WebAnimations',has:'web-animations'}]})

Transformers

registry-transformer

A customTypeScript transformer that generatesregistry keys forwidgets included in lazily-loaded bundles. This allows widget authors to use the same pattern for authoring widgets regardless of whether they are loaded from a registry or imported directly.

For example, ifLazyWidget needs to be split into a separate bundle and this transformer is not applied, thenLazyWidget would need to be added to the registry (registry.define('lazy-widget', LazyWidget)), and all calls tow(LazyWidget) would need to be updated to reference its registry key (w<LazyWidget>('lazy-widget')). By using this transformer,LazyWidget would instead be added to the registry at build time, allowing existing code to remain unchanged.

element-transformer

A customTypeScript transformer that generates a custom element definition for specified widgets.

For example given a widgetHello,

import{v}from'@dojo/framework/widget-core/d';import{WidgetBase}from'@dojo/framework/widget-core/WidgetBase';interfaceHelloProperties{name:string;flag:boolean;onClick():void;onChange(value:string):void;}exportclassHelloextendsWidgetBase<HelloProperties>{protectedrender(){const{ name}=this.properties;returnv('h1',{},['Hello ${name}!']);}}exportdefaultHello;

The generated output would be ,

import{v}from'@dojo/framework/widget-core/d';import{WidgetBase}from'@dojo/framework/widget-core/WidgetBase';interfaceHelloProperties{name:string;flag:boolean;onClick():void;onChange(value:string):void;}exportclassHelloextendsWidgetBase<HelloProperties>{protectedrender(){const{ name}=this.properties;returnv('h1',{},['Hello ${name}!']);}}Hello.__customElementDescriptor={ ...{tagName:'widget-hello',attributes:['name'],properties:['flag'],events:['onClick',onChange']}, ...Hello.prototype.__customElementDescriptor||{}};exportdefaultHello;

How do I contribute?

We appreciate your interest! Please see theDojo 2 Meta Repository for theContributing Guidelines.

Code Style

This repository usesprettier for code styling rules and formatting. A pre-commit hook is installed automatically and configured to runprettier against all staged files as per the configuration in the projectspackage.json.

An additional npm script to runprettier (with write set totrue) against allsrc andtest project files is available by running:

npm run prettier

Testing

To test this package, after ensuring all dependencies are installed (npm install), run the following command:

npm runtest

Licensing information

© 2018JS Foundation.New BSD license.

About

Plugins and loaders for webpack used with Dojo

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors12


[8]ページ先頭

©2009-2025 Movatter.jp