1657072800
Convert CommonJS module into ES module. Powered by cjs-es.
npm install -D rollup-plugin-cjs-es
require
s.Promise.resolve(require("..."))
.import cjs from "rollup-plugin-cjs-es";
export default {
input: ["entry.js"],
output: {
dir: "dist",
format: "cjs"
},
plugins: [
cjs({
nested: true
})
]
};
require
is reassignedIf require
, exports
, or module
are dynamically assigned, the transformer can't find them and it will emit a warning e.g.
(function(r) {
r("foo");
})(require);
const r = require;
r("foo");
These patterns are common in module loaders like UMD. I suggest using other plugins to unwrap the module back to the normal CJS pattern.
To lazy load an ES module, we can use the import()
function:
foo.js
export const foo = () => {
return import("./bar");
};
bar.js
export const bar = "bar";
After rolluped into CommonJS format, the dist folder would contain two entries:
foo.js
'use strict';
const foo = () => {
return Promise.resolve(require("./bar.js"));
};
exports.foo = foo;
bar.js
'use strict';
const bar = "bar";
exports.bar = bar;
So that bar.js
is not loaded until require("foo").foo()
is called.
With this plugin, you can use the same feature using CommonJS syntax, by writing the require statement inside a promise:
module.exports = {
foo: () => {
return Promise.resolve(require("./bar.js"));
}
};
The plugin would transform it into a dynamic import()
.
In the following example, you would get a warning:
entry.js
const foo = require("./foo");
foo.foo();
foo.js
const myObject = {
foo: () => console.log("foo");
};
// assign the entire object so that cjs-es won't convert the object pattern into named exports.
module.exports = myObject;
(!) Missing exports
https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-mo
dule
entry.js
foo is not exported by foo.js
1: import * as foo from "./foo";
2: foo.foo();
^
That is because cjs-es tends to import named exports by default.
To solve this problem, the plugin generates a .cjsescache
file when a build is finished (whether it succeeded or not), which record the export type of each imported module. In the next build, it will read the cache file and determine the export type according to the cache.
You can also use exportType
option to tell the plugin that foo.js exports default member manually:
{
plugins: [
cjsEs({
exportType: {
// the path would be resolved with the current directory.
"foo.js": "default"
}
})
]
}
In the following example, you would get an error under ES enviroment:
entry.js
Promise.resolve(require("./foo"))
.then(foo => foo());
foo.js
module.exports = function() {
console.log("foo");
};
After rolluped into ES format and renamed them into .mjs
:
entry.mjs
import("./foo.mjs")
.then(foo => foo());
foo.mjs
function foo() {
console.log("foo");
}
export default foo;
(node:9996) ExperimentalWarning: The ESM module loader is experimental.
(node:9996) UnhandledPromiseRejectionWarning: TypeError: foo is not a function
at then.foo (file:///D:/Dev/node-test/dist/entry.mjs:2:16)
at <anonymous>
To correctly call the default member, entry.js
has to be modified:
Promise.resolve(require("./foo"))
.then(foo => foo.default());
However, this would break other enviroments like CommonJS:
(node:9432) UnhandledPromiseRejectionWarning: TypeError: foo.default is not a fu
nction
at Promise.resolve.then.foo (D:\Dev\node-test\dist\entry.js:4:27)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
at Function.Module.runMain (module.js:705:11)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:660:3
Avoid default export if you want to use dynamic import()
+ CommonJS in the same time.
rollup-plugin-commonjs uses a smart method to determine whether to use named or default import. It creates a proxy loader when a module is imported:
source
const foo = require("foo");
foo.bar();
transformed
import "foo";
import foo from "commonjs-proxy:foo";
foo.bar();
With this technic, it can first look into the "foo"
module to check its export type, then generate the proxy module which maps named exports into a default export. However, if the required module "foo"
uses named exports, it has to be converted into a single object:
commonjs-proxy:foo
import * as _ from "foo";
export default _;
As a result, all named exports are included in the bundle even that only bar
is used.
The same problem applies to cjs-es as well if you force a module to use default export:
entry.js
const foo = require("./foo");
foo.foo();
foo.js
module.exports = {
foo: () => console.log("foo"),
bar: () => console.log("bar")
};
bundled
const _export_foo_ = () => console.log("foo");
_export_foo_();
bundled with exportType: "default"
var foo = {
foo: () => console.log("foo"),
bar: () => console.log("bar")
};
foo.foo();
Note that this won't be true after rollup supports tree-shaking for object literal. See https://github.com/rollup/rollup/issues/2201
This module exports a single function.
cjsEsFactory(options?:Object) => rollupPlugin
options
has following optional properties:
include
: Array<string>
. A list of minimatch pattern. Only matched files would be transformed. Match all files by default.
exclude
: Array<string>
. A list of minimatch pattern. Override options.include
. Default: []
.
cache
: String
. Path to the cache file. false
to disable the cache. Default: ".cjsescache"
.
sourceMap
: boolean
. If true then generate the source map. Default: true
.
nested
: boolean
. If true then analyze the AST recursively, otherwise only top-level nodes are analyzed. Default: false
.
exportType
: null|string|object|function
. Tell the plugin how to determine the export type. Valid export types are "named"
, "default"
.
If exportType
is a function, it has following signature:
(moduleId) => exportType:String|null|Promise<String|null>
The return value should be the export type of moduleId
.
If exportType
is an object, it is a "path/to/file.js": type
map.
Default: null
.
1.0.1 (Jul 27, 2020)
this.isExternal
.1.0.0 (Mar 13, 2020)
0.9.0 (Jun 14, 2019)
0.8.0 (Jun 5, 2019)
0.7.0 (Sep 19, 2018)
module.exports
and exports
are bound to a single reference.0.6.0 (Jul 19, 2018)
0.5.1 (Jun 30, 2018)
0.5.0 (Jun 29, 2018)
options.cache
is a file path now.require()
had been split out as a new plugin.0.4.0 (Jun 16, 2018)
options.cache
. Now the plugin would generate a cache file by default.0.3.2 (May 4, 2018)
TypeError: cannot access property 'name' on undefined
in unwrapImport.0.3.1 (May 1, 2018)
0.3.0 (May 1, 2018)
options.nested
.options.hoist
and options.dynamicImport
.0.2.1 (Apr 28, 2018)
0.2.0 (Apr 28, 2018)
exportType
option.importStyle
, exportStyle
option.0.1.0 (Apr 27, 2018)
Author: eight04
Source code: https://github.com/eight04/rollup-plugin-cjs-es
License: MIT license
#javascript #Rollup
1657072800
Convert CommonJS module into ES module. Powered by cjs-es.
npm install -D rollup-plugin-cjs-es
require
s.Promise.resolve(require("..."))
.import cjs from "rollup-plugin-cjs-es";
export default {
input: ["entry.js"],
output: {
dir: "dist",
format: "cjs"
},
plugins: [
cjs({
nested: true
})
]
};
require
is reassignedIf require
, exports
, or module
are dynamically assigned, the transformer can't find them and it will emit a warning e.g.
(function(r) {
r("foo");
})(require);
const r = require;
r("foo");
These patterns are common in module loaders like UMD. I suggest using other plugins to unwrap the module back to the normal CJS pattern.
To lazy load an ES module, we can use the import()
function:
foo.js
export const foo = () => {
return import("./bar");
};
bar.js
export const bar = "bar";
After rolluped into CommonJS format, the dist folder would contain two entries:
foo.js
'use strict';
const foo = () => {
return Promise.resolve(require("./bar.js"));
};
exports.foo = foo;
bar.js
'use strict';
const bar = "bar";
exports.bar = bar;
So that bar.js
is not loaded until require("foo").foo()
is called.
With this plugin, you can use the same feature using CommonJS syntax, by writing the require statement inside a promise:
module.exports = {
foo: () => {
return Promise.resolve(require("./bar.js"));
}
};
The plugin would transform it into a dynamic import()
.
In the following example, you would get a warning:
entry.js
const foo = require("./foo");
foo.foo();
foo.js
const myObject = {
foo: () => console.log("foo");
};
// assign the entire object so that cjs-es won't convert the object pattern into named exports.
module.exports = myObject;
(!) Missing exports
https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-mo
dule
entry.js
foo is not exported by foo.js
1: import * as foo from "./foo";
2: foo.foo();
^
That is because cjs-es tends to import named exports by default.
To solve this problem, the plugin generates a .cjsescache
file when a build is finished (whether it succeeded or not), which record the export type of each imported module. In the next build, it will read the cache file and determine the export type according to the cache.
You can also use exportType
option to tell the plugin that foo.js exports default member manually:
{
plugins: [
cjsEs({
exportType: {
// the path would be resolved with the current directory.
"foo.js": "default"
}
})
]
}
In the following example, you would get an error under ES enviroment:
entry.js
Promise.resolve(require("./foo"))
.then(foo => foo());
foo.js
module.exports = function() {
console.log("foo");
};
After rolluped into ES format and renamed them into .mjs
:
entry.mjs
import("./foo.mjs")
.then(foo => foo());
foo.mjs
function foo() {
console.log("foo");
}
export default foo;
(node:9996) ExperimentalWarning: The ESM module loader is experimental.
(node:9996) UnhandledPromiseRejectionWarning: TypeError: foo is not a function
at then.foo (file:///D:/Dev/node-test/dist/entry.mjs:2:16)
at <anonymous>
To correctly call the default member, entry.js
has to be modified:
Promise.resolve(require("./foo"))
.then(foo => foo.default());
However, this would break other enviroments like CommonJS:
(node:9432) UnhandledPromiseRejectionWarning: TypeError: foo.default is not a fu
nction
at Promise.resolve.then.foo (D:\Dev\node-test\dist\entry.js:4:27)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:118:7)
at Function.Module.runMain (module.js:705:11)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:660:3
Avoid default export if you want to use dynamic import()
+ CommonJS in the same time.
rollup-plugin-commonjs uses a smart method to determine whether to use named or default import. It creates a proxy loader when a module is imported:
source
const foo = require("foo");
foo.bar();
transformed
import "foo";
import foo from "commonjs-proxy:foo";
foo.bar();
With this technic, it can first look into the "foo"
module to check its export type, then generate the proxy module which maps named exports into a default export. However, if the required module "foo"
uses named exports, it has to be converted into a single object:
commonjs-proxy:foo
import * as _ from "foo";
export default _;
As a result, all named exports are included in the bundle even that only bar
is used.
The same problem applies to cjs-es as well if you force a module to use default export:
entry.js
const foo = require("./foo");
foo.foo();
foo.js
module.exports = {
foo: () => console.log("foo"),
bar: () => console.log("bar")
};
bundled
const _export_foo_ = () => console.log("foo");
_export_foo_();
bundled with exportType: "default"
var foo = {
foo: () => console.log("foo"),
bar: () => console.log("bar")
};
foo.foo();
Note that this won't be true after rollup supports tree-shaking for object literal. See https://github.com/rollup/rollup/issues/2201
This module exports a single function.
cjsEsFactory(options?:Object) => rollupPlugin
options
has following optional properties:
include
: Array<string>
. A list of minimatch pattern. Only matched files would be transformed. Match all files by default.
exclude
: Array<string>
. A list of minimatch pattern. Override options.include
. Default: []
.
cache
: String
. Path to the cache file. false
to disable the cache. Default: ".cjsescache"
.
sourceMap
: boolean
. If true then generate the source map. Default: true
.
nested
: boolean
. If true then analyze the AST recursively, otherwise only top-level nodes are analyzed. Default: false
.
exportType
: null|string|object|function
. Tell the plugin how to determine the export type. Valid export types are "named"
, "default"
.
If exportType
is a function, it has following signature:
(moduleId) => exportType:String|null|Promise<String|null>
The return value should be the export type of moduleId
.
If exportType
is an object, it is a "path/to/file.js": type
map.
Default: null
.
1.0.1 (Jul 27, 2020)
this.isExternal
.1.0.0 (Mar 13, 2020)
0.9.0 (Jun 14, 2019)
0.8.0 (Jun 5, 2019)
0.7.0 (Sep 19, 2018)
module.exports
and exports
are bound to a single reference.0.6.0 (Jul 19, 2018)
0.5.1 (Jun 30, 2018)
0.5.0 (Jun 29, 2018)
options.cache
is a file path now.require()
had been split out as a new plugin.0.4.0 (Jun 16, 2018)
options.cache
. Now the plugin would generate a cache file by default.0.3.2 (May 4, 2018)
TypeError: cannot access property 'name' on undefined
in unwrapImport.0.3.1 (May 1, 2018)
0.3.0 (May 1, 2018)
options.nested
.options.hoist
and options.dynamicImport
.0.2.1 (Apr 28, 2018)
0.2.0 (Apr 28, 2018)
exportType
option.importStyle
, exportStyle
option.0.1.0 (Apr 27, 2018)
Author: eight04
Source code: https://github.com/eight04/rollup-plugin-cjs-es
License: MIT license
#javascript #Rollup
1622722796
WordPress needs no introduction. It has been in the world for quite a long time. And up till now, it has given a tough fight to leading web development technology. The main reason behind its remarkable success is, it is highly customizable and also SEO-friendly. Other benefits include open-source technology, security, user-friendliness, and the thousands of free plugins it offers.
Talking of WordPress plugins, are a piece of software that enables you to add more features to the website. They are easy to integrate into your website and don’t hamper the performance of the site. WordPress, as a leading technology, has to offer many out-of-the-box plugins.
However, not always the WordPress would be able to meet your all needs. Hence you have to customize the WordPress plugin to provide you the functionality you wished. WordPress Plugins are easy to install and customize. You don’t have to build the solution from scratch and that’s one of the reasons why small and medium-sized businesses love it. It doesn’t need a hefty investment or the hiring of an in-house development team. You can use the core functionality of the plugin and expand it as your like.
In this blog, we would be talking in-depth about plugins and how to customize WordPress plugins to improve the functionality of your web applications.
What Is The Working Of The WordPress Plugins?
Developing your own plugin requires you to have some knowledge of the way they work. It ensures the better functioning of the customized plugins and avoids any mistakes that can hamper the experience on your site.
1. Hooks
Plugins operate primarily using hooks. As a hook attaches you to something, the same way a feature or functionality is hooked to your website. The piece of code interacts with the other components present on the website. There are two types of hooks: a. Action and b. Filter.
A. Action
If you want something to happen at a particular time, you need to use a WordPress “action” hook. With actions, you can add, change and improve the functionality of your plugin. It allows you to attach a new action that can be triggered by your users on the website.
There are several predefined actions available on WordPress, custom WordPress plugin development also allows you to develop your own action. This way you can make your plugin function as your want. It also allows you to set values for which the hook function. The add_ action function will then connect that function to a specific action.
B. Filters
They are the type of hooks that are accepted to a single variable or a series of variables. It sends them back after they have modified it. It allows you to change the content displayed to the user.
You can add the filter on your website with the apply_filter function, then you can define the filter under the function. To add a filter hook on the website, you have to add the $tag (the filter name) and $value (the filtered value or variable), this allows the hook to work. Also, you can add extra function values under $var.
Once you have made your filter, you can execute it with the add_filter function. This will activate your filter and would work when a specific function is triggered. You can also manipulate the variable and return it.
2. Shortcodes
Shortcodes are a good way to create and display the custom functionality of your website to visitors. They are client-side bits of code. They can be placed in the posts and pages like in the menu and widgets, etc.
There are many plugins that use shortcodes. By creating your very own shortcode, you too can customize the WordPress plugin. You can create your own shortcode with the add_shortcode function. The name of the shortcode that you use would be the first variable and the second variable would be the output of it when it is triggered. The output can be – attributes, content, and name.
3. Widgets
Other than the hooks and shortcodes, you can use the widgets to add functionality to the site. WordPress Widgets are a good way to create a widget by extending the WP_Widget class. They render a user-friendly experience, as they have an object-oriented design approach and the functions and values are stored in a single entity.
How To Customize WordPress Plugins?
There are various methods to customize the WordPress plugins. Depending on your need, and the degree of customization you wish to make in the plugin, choose the right option for you. Also, don’t forget to keep in mind that it requires a little bit of technical knowledge too. So find an expert WordPress plugin development company in case you lack the knowledge to do it by yourself.
1. Hire A Plugin Developer3
One of the best ways to customize a WordPress plugin is by hiring a plugin developer. There are many plugin developers listed in the WordPress directory. You can contact them and collaborate with world-class WordPress developers. It is quite easy to find a WordPress plugin developer.
Since it is not much work and doesn’t pay well or for the long term a lot of developers would be unwilling to collaborate but, you will eventually find people.
2. Creating A Supporting Plugin
If you are looking for added functionality in an already existing plugin go for this option. It is a cheap way to meet your needs and creating a supporting plugin takes very little time as it has very limited needs. Furthermore, you can extend a plugin to a current feature set without altering its base code.
However, to do so, you have to hire a WordPress developer as it also requires some technical knowledge.
3. Use Custom Hooks
Use the WordPress hooks to integrate some other feature into an existing plugin. You can add an action or a filter as per your need and improve the functionality of the website.
If the plugin you want to customize has the hook, you don’t have to do much to customize it. You can write your own plugin that works with these hooks. This way you don’t have to build a WordPress plugin right from scratch. If the hook is not present in the plugin code, you can contact a WordPress developer or write the code yourself. It may take some time, but it works.
Once the hook is added, you just have to manually patch each one upon the release of the new plugin update.
4. Override Callbacks
The last way to customize WordPress plugins is by override callbacks. You can alter the core functionality of the WordPress plugin with this method. You can completely change the way it functions with your website. It is a way to completely transform the plugin. By adding your own custom callbacks, you can create the exact functionality you desire.
We suggest you go for a web developer proficient in WordPress as this requires a good amount of technical knowledge and the working of a plugin.
#customize wordpress plugins #how to customize plugins in wordpress #how to customize wordpress plugins #how to edit plugins in wordpress #how to edit wordpress plugins #wordpress plugin customization
1656997200
🍣 A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle
This plugin requires an LTS Node version (v12.0.0+) and Rollup v2.68.0+. If you are using @rollup/plugin-node-resolve
, it should be v13.0.6+.
Using npm:
npm install @rollup/plugin-commonjs --save-dev
Create a rollup.config.js
configuration file and import the plugin:
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [commonjs()]
};
Then call rollup
either via the CLI or the API.
When used together with the node-resolve plugin
strictRequires
Type: "auto" | boolean | "debug" | string[]
Default: "auto"
By default, this plugin will try to hoist require
statements as imports to the top of each file. While this works well for many code bases and allows for very efficient ESM output, it does not perfectly capture CommonJS semantics as the initialisation order of required modules will be different. The resultant side effects can include log statements being emitted in a different order, and some code that is dependent on the initialisation order of polyfills in require statements may not work. But it is especially problematic when there are circular require
calls between CommonJS modules as those often rely on the lazy execution of nested require
calls.
Setting this option to true
will wrap all CommonJS files in functions which are executed when they are required for the first time, preserving NodeJS semantics. This is the safest setting and should be used if the generated code does not work correctly with "auto"
. Note that strictRequires: true
can have a small impact on the size and performance of generated code, but less so if the code is minified.
The default value of "auto"
will only wrap CommonJS files when they are part of a CommonJS dependency cycle, e.g. an index file that is required by some of its dependencies, or if they are only required in a potentially "conditional" way like from within an if-statement or a function. All other CommonJS files are hoisted. This is the recommended setting for most code bases. Note that the detection of conditional requires can be subject to race conditions if there are both conditional and unconditional requires of the same file, which in edge cases may result in inconsistencies between builds. If you think this is a problem for you, you can avoid this by using any value other than "auto"
or "debug"
.
false
will entirely prevent wrapping and hoist all files. This may still work depending on the nature of cyclic dependencies but will often cause problems.
You can also provide a minimatch pattern, or array of patterns, to only specify a subset of files which should be wrapped in functions for proper require
semantics.
"debug"
works like "auto"
but after bundling, it will display a warning containing a list of ids that have been wrapped which can be used as minimatch pattern for fine-tuning or to avoid the potential race conditions mentioned for "auto"
.
dynamicRequireTargets
Type: string | string[]
Default: []
Note: In previous versions, this option would spin up a rather comprehensive mock environment that was capable of handling modules that manipulate require.cache
. This is no longer supported. If you rely on this e.g. when using request-promise-native, use version 21 of this plugin.
Some modules contain dynamic require
calls, or require modules that contain circular dependencies, which are not handled well by static imports. Including those modules as dynamicRequireTargets
will simulate a CommonJS (NodeJS-like) environment for them with support for dynamic dependencies. It also enables strictRequires
for those modules, see above.
Note: In extreme cases, this feature may result in some paths being rendered as absolute in the final bundle. The plugin tries to avoid exposing paths from the local machine, but if you are dynamicRequirePaths
with paths that are far away from your project's folder, that may require replacing strings like "/Users/John/Desktop/foo-project/"
-> "/"
.
Example:
commonjs({ dynamicRequireTargets: [ // include using a glob pattern (either a string or an array of strings) 'node_modules/logform/*.js', // exclude files that are known to not be required dynamically, this allows for better optimizations '!node_modules/logform/index.js', '!node_modules/logform/format.js', '!node_modules/logform/levels.js', '!node_modules/logform/browser.js' ] });
dynamicRequireRoot
Type: string
Default: process.cwd()
To avoid long paths when using the dynamicRequireTargets
option, you can use this option to specify a directory that is a common parent for all files that use dynamic require statements. Using a directory higher up such as /
may lead to unnecessarily long paths in the generated code and may expose directory names on your machine like your home directory name. By default it uses the current working directory.
exclude
Type: string | string[]
Default: null
A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default, all files with extensions other than those in extensions
or ".cjs"
are ignored, but you can exclude additional files. See also the include
option.
include
Type: string | string[]
Default: null
A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should operate on. By default, all files with extension ".cjs"
or those in extensions
are included, but you can narrow this list by only including specific files. These files will be analyzed and transpiled if either the analysis does not find ES module specific statements or transformMixedEsModules
is true
.
extensions
Type: string[]
Default: ['.js']
For extensionless imports, search for extensions other than .js in the order specified. Note that you need to make sure that non-JavaScript files are transpiled by another plugin first.
ignoreGlobal
Type: boolean
Default: false
If true, uses of global
won't be dealt with by this plugin.
sourceMap
Type: boolean
Default: true
If false, skips source map generation for CommonJS modules. This will improve performance.
transformMixedEsModules
Type: boolean
Default: false
Instructs the plugin whether to enable mixed module transformations. This is useful in scenarios with modules that contain a mix of ES import
statements and CommonJS require
expressions. Set to true
if require
calls should be transformed to imports in mixed modules, or false
if the require
expressions should survive the transformation. The latter can be important if the code contains environment detection, or you are coding for an environment with special treatment for require
calls such as ElectronJS. See also the "ignore" option.
ignore
Type: string[] | ((id: string) => boolean)
Default: []
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an id => boolean
function.
ignoreTryCatch
Type: boolean | 'remove' | string[] | ((id: string) => boolean)
Default: true
In most cases, where require
calls to external dependencies are inside a try-catch
clause, they should be left unconverted as it requires an optional dependency that may or may not be installed beside the rolled up package. Due to the conversion of require
to a static import
- the call is hoisted to the top of the file, outside of the try-catch
clause.
true
: All external require
calls inside a try
will be left unconverted.false
: All external require
calls inside a try
will be converted as if the try-catch
clause is not there.remove
: Remove all external require
calls from inside any try
block.string[]
: Pass an array containing the IDs to left unconverted.((id: string) => boolean|'remove')
: Pass a function that control individual IDs.Note that non-external requires will not be ignored by this option.
ignoreDynamicRequires
Type: boolean
Default: false
Some require
calls cannot be resolved statically to be translated to imports, e.g.
function wrappedRequire(target) {
return require(target);
}
wrappedRequire('foo');
wrappedRequire('bar');
When this option is set to false
, the generated code will either directly throw an error when such a call is encountered or, when dynamicRequireTargets
is used, when such a call cannot be resolved with a configured dynamic require target.
Setting this option to true
will instead leave the require
call in the code or use it as a fallback for dynamicRequireTargets
.
esmExternals
Type: boolean | string[] | ((id: string) => boolean)
Default: false
Controls how to render imports from external dependencies. By default, this plugin assumes that all external dependencies are CommonJS. This means they are rendered as default imports to be compatible with e.g. NodeJS where ES modules can only import a default export from a CommonJS dependency:
// input
const foo = require('foo');
// output
import foo from 'foo';
This is likely not desired for ES module dependencies: Here require
should usually return the namespace to be compatible with how bundled modules are handled.
If you set esmExternals
to true
, this plugins assumes that all external dependencies are ES modules and will adhere to the requireReturnsDefault
option. If that option is not set, they will be rendered as namespace imports.
You can also supply an array of ids to be treated as ES modules, or a function that will be passed each external id to determine if it is an ES module.
defaultIsModuleExports
Type: boolean | "auto"
Default: "auto"
Controls what is the default export when importing a CommonJS file from an ES module.
true
: The value of the default export is module.exports
. This currently matches the behavior of Node.js when importing a CommonJS file.// mod.cjs
exports.default = 3;
import foo from './mod.cjs';
console.log(foo); // { default: 3 }
false
: The value of the default export is exports.default
.// mod.cjs
exports.default = 3;
import foo from './mod.cjs';
console.log(foo); // 3
"auto"
: The value of the default export is exports.default
if the CommonJS file has an exports.__esModule === true
property; otherwise it's module.exports
. This makes it possible to import the default export of ES modules compiled to CommonJS as if they were not compiled.// mod.cjs
exports.default = 3;
// mod-compiled.cjs
exports.__esModule = true;
exports.default = 3;
import foo from './mod.cjs';
import bar from './mod-compiled.cjs';
console.log(foo); // { default: 3 }
console.log(bar); // 3
requireReturnsDefault
Type: boolean | "namespace" | "auto" | "preferred" | ((id: string) => boolean | "auto" | "preferred")
Default: false
Controls what is returned when requiring an ES module from a CommonJS file. When using the esmExternals
option, this will also apply to external modules. By default, this plugin will render those imports as namespace imports, i.e.
// input
const foo = require('foo');
// output
import * as foo from 'foo';
This is in line with how other bundlers handle this situation and is also the most likely behaviour in case Node should ever support this. However there are some situations where this may not be desired:
There is code in an external dependency that cannot be changed where a require
statement expects the default export to be returned from an ES module.
If the imported module is in the same bundle, Rollup will generate a namespace object for the imported module which can increase bundle size unnecessarily:
// input: main.js
const dep = require('./dep.js');
console.log(dep.default);
// input: dep.js
export default 'foo';
// output
var dep = 'foo';
var dep$1 = /*#__PURE__*/ Object.freeze({
__proto__: null,
default: dep
});
console.log(dep$1.default);
For these situations, you can change Rollup's behaviour either globally or per module. To change it globally, set the requireReturnsDefault
option to one of the following values:
false
: This is the default, requiring an ES module returns its namespace. This is the only option that will also add a marker __esModule: true
to the namespace to support interop patterns in CommonJS modules that are transpiled ES modules.
// input
const dep = require('dep');
console.log(dep);
// output
import * as dep$1 from 'dep';
function getAugmentedNamespace(n) {
var a = Object.defineProperty({}, '__esModule', { value: true });
Object.keys(n).forEach(function (k) {
var d = Object.getOwnPropertyDescriptor(n, k);
Object.defineProperty(
a,
k,
d.get
? d
: {
enumerable: true,
get: function () {
return n[k];
}
}
);
});
return a;
}
var dep = /*@__PURE__*/ getAugmentedNamespace(dep$1);
console.log(dep);
"namespace"
: Like false
, requiring an ES module returns its namespace, but the plugin does not add the __esModule
marker and thus creates more efficient code. For external dependencies when using esmExternals: true
, no additional interop code is generated.
// output
import * as dep from 'dep';
console.log(dep);
"auto"
: This is complementary to how output.exports
: "auto"
works in Rollup: If a module has a default export and no named exports, requiring that module returns the default export. In all other cases, the namespace is returned. For external dependencies when using esmExternals: true
, a corresponding interop helper is added:
// output
import * as dep$1 from 'dep';
function getDefaultExportFromNamespaceIfNotNamed(n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1
? n['default']
: n;
}
var dep = getDefaultExportFromNamespaceIfNotNamed(dep$1);
console.log(dep);
"preferred"
: If a module has a default export, requiring that module always returns the default export, no matter whether additional named exports exist. This is similar to how previous versions of this plugin worked. Again for external dependencies when using esmExternals: true
, an interop helper is added:
// output
import * as dep$1 from 'dep';
function getDefaultExportFromNamespaceIfPresent(n) {
return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
}
var dep = getDefaultExportFromNamespaceIfPresent(dep$1);
console.log(dep);
true
: This will always try to return the default export on require without checking if it actually exists. This can throw at build time if there is no default export. This is how external dependencies are handled when esmExternals
is not used. The advantage over the other options is that, like false
, this does not add an interop helper for external dependencies, keeping the code lean:
// output
import dep from 'dep';
console.log(dep);
To change this for individual modules, you can supply a function for requireReturnsDefault
instead. This function will then be called once for each required ES module or external dependency with the corresponding id and allows you to return different values for different modules.
Since most CommonJS packages you are importing are probably dependencies in node_modules
, you may need to use @rollup/plugin-node-resolve:
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
},
plugins: [commonjs(), resolve()]
};
Symlinks are common in monorepos and are also created by the npm link
command. Rollup with @rollup/plugin-node-resolve
resolves modules to their real paths by default. So include
and exclude
paths should handle real paths rather than symlinked paths (e.g. ../common/node_modules/**
instead of node_modules/**
). You may also use a regular expression for include
that works regardless of base path. Try this:
commonjs({
include: /node_modules/
});
Whether symlinked module paths are realpathed or preserved depends on Rollup's preserveSymlinks
setting, which is false by default, matching Node.js' default behavior. Setting preserveSymlinks
to true in your Rollup config will cause import
and export
to match based on symlinked paths instead.
ES modules are always parsed in strict mode. That means that certain non-strict constructs (like octal literals) will be treated as syntax errors when Rollup parses modules that use them. Some older CommonJS modules depend on those constructs, and if you depend on them your bundle will blow up. There's basically nothing we can do about that.
Luckily, there is absolutely no good reason not to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
This plugin exposes the result of its CommonJS file type detection for other plugins to use. You can access it via this.getModuleInfo
or the moduleParsed
hook:
function cjsDetectionPlugin() {
return {
name: 'cjs-detection',
moduleParsed({
id,
meta: {
commonjs: { isCommonJS }
}
}) {
console.log(`File ${id} is CommonJS: ${isCommonJS}`);
}
};
}
Author: rollup
Source Code: https://github.com/rollup/plugins/
License:
#vite #typescript #javascript #Rollup
1625301328
When the exchange server is synchronised with MS Outlook then, automatically a copy of its mailboxes will be generated in OST (Offline Storage Table) file format. The user can access OST data in the offline mode and work on them. The changes will get updated when the internet connectivity is re-established. OST files cannot be accessed in the other system or remote system. So to access the OST files in another system Outlook, then convert Outlook OST to PST format. Due to various reasons for which users’ want to convert OST to PST file format such as the Exchange might face some technical issues, downtime or crash. How to convert OST to PST in Outlook 2016, 2013, 2010? Well, in this blog, we will discuss both manual as well as the professional best OST to PST Converter online solution.
For better understanding of users’, we have listed some common reasons below.
Before providing methods to the query “how to convert OST file to PST in outlook 2016”, first understand why users’ need to convert OST to PST. Some of the basic reasons are provided below.
These are a few reasons for Outlook OST to PST conversion. Now let’s proceed ahead to different methods to convert OST to PST online.
Manual strategies are cost-effective methods and here, we will discuss the complete manual steps for OST to PST conversion. Before starting the steps, it is suggested to create a backup copy of the original data as there might be a risk of human error that can ultimately lead to severe data loss. How to convert OST to PST manually? Follow the methods provided below -
To avoid all the limitations that we have already seen above with the conventional manual techniques, users can opt for a well known and reliable automated method for conversion. There are numerous third-party solutions available to convert OST to PST, however it is suggested to use a trusted software. Using the smart DRS Best OST to PST Converter online utility that allows to export OST to PST, MBOX, MSG, EML, PDF, CSV, HTML, Gmail, Yandex mail, Yahoo, Office 365, etc. It can easily open corrupt OST files and convert them to healthy PST. The tool even allows users to smoothly export all the mailbox items like attachments, calendar, contacts, journals, tasks, etc. There are no file size restrictions and no risk of severe data loss. The advanced software is compatible with all versions of Mac and Windows. The free OST to PST Converter online version allows to export 50 emails for free.
Above in this blog, we have discussed the recommended solutions by experts on the query “how to convert OST to PST in Outlook 2016”. At the end of this article, we can conclude that manual strategies have several limitations, so it is suggested to use the well known DRS OST to PST Converter for an effective, accurate and effortless conversion.
#how to convert ost file to pst in outlook 2016 #how to convert ost to pst online #how to convert ost to pst manually #convert ost to pst #ost to pst converter #outlook ost to pst
1657062000
Currently (rollup@0.65), rollup doesn't support code splitting with IIFE output. This plugin would transform ES module output into IIFEs.
npm install -D rollup-plugin-iife
import iife from "rollup-plugin-iife";
export default {
input: ["entry.js", "entry2.js"],
output: {
dir: "dist",
format: "es",
globals: {
vue: "Vue"
}
},
externals: ["vue"],
plugins: [iife()]
};
You can define global variables with output.globals
just like before. You can also specify them with the plugin option names
.
The plugin would first lookup names
option then output.globals
.
This module exports a single function.
createPlugin({
names?: Function|Object,
sourcemap?: Boolean,
prefix?: String,
strict?: Boolean
}) => PluginInstance
Create the plugin instance.
If names
is a function, the signature is:
(moduleId: String) => globalVariableName: String
If names
is an object, it is a moduleId
/globalVariableName
map. moduleId
can be relative to the output folder (e.g. ./entry.js
), the plugin would resolve it to the absolute path.
If the plugin can't find a proper variable name, it would generate one according to its filename with camelcase.
If sourcemap
is false then don't generate the sourcemap. Default: true
.
When prefix
is defined, it will be used to prefix auto-generated variable names. It doesn't prefix names defined in the names
option. It doesn't prefix external imports.
If strict
is true then add 'use strict';
directive to the IIFE. Default: true
.
<script>
tags).0.6.0 (Feb 11, 2022)
import.meta.url
. The plugin also throws and error if it sees unconverted import.meta
.0.5.0 (Feb 18, 2021)
'use strict';
directive is inserted by default.strict
option.0.4.0 (Dec 28, 2020)
0.3.1 (Feb 8, 2020)
0.3.0 (Aug 14, 2019)
var
.0.2.1 (Jun 23, 2019)
0.2.0 (Jan 26, 2019)
0.1.2 (Jan 25, 2019)
prefix
option.0.1.1 (Sep 28, 2018)
output.globals
option.0.1.0 (Aug 28, 2018)
Author: eight04
Source code: https://github.com/eight04/rollup-plugin-iife
License: MIT license
#javascript #Rollup