A plugin for Greenwood for loading CommonJS based modules (require
/ module.exports
) in the browser using ESM (import
/ export
) syntax. Note: It is highly encouraged that you favor ESM based packages for the cleanest / fastest interop and developer experience. Additional processing time and dependencies are required to handle the conversion.
This package assumes you already have
@greenwood/cli
installed.
You can use your favorite JavaScript package manager to install this package.
examples:
# npm
npm install @greenwood/plugin-import-commonjs --save-dev
# yarn
yarn add @greenwood/plugin-import-commonjs --dev
Add this plugin to your greenwood.config.js and spread the export
.
import { greenwoodPluginImportCommonJs } from '@greenwood/plugin-import-commonjs';
export default {
...
plugins: [
greenwoodPluginImportCommonJs()
]
}
This will then allow you to use a CommonJS based modules in the browser. For example, here is how you could use lodash (although as mentioned above, in this case, you would want to use lodash-es instead.)
// <script src="my-file.js">
import _ from 'lodash';
.
.
console.log(_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 })); // { 'a': 1, 'b': 2 }