Webpack packs a js code as a js library file and uses it as a plug-in.

Understand a few basic concepts:

UMD

UMD (Universal Module Definition), hopes to provide a front-end and back-end cross-platform solution (supports AMD and CommonJS module methods).

Implementation principle
The implementation of UMD is very simple:

First determine whether the Node.js module format is supported (whether exports exist), and use the Node.js module format if it exists.
Then judge whether it supports AMD (whether the define exists), and if it exists, use the AMD method to load the module.
Neither of the first two exists, exposes the module globally (window or global).

For example:

// if the module has no dependencies, the above pattern can be simplified to
(function (root, factory) {
    
    
    if (typeof define === 'function' && define.amd) {
    
    
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports === 'object') {
    
    
        // Node. Does not work with strict CommonJS, but
        // only CommonJS-like environments that support module.exports,
        // like Node.
        module.exports = factory();
    } else {
    
    
        // Browser globals (root is window)
        root.returnExports = factory();
  }
}(this, function () {
    
    

    // Just return a value to define the module export.
    // This example returns an object, but the module
    // can return a function as the exported value.
    return {
    
    };
}));

After packaging with webpack, you can configure such a format code

insert image description here
You can see him doing the same.


Scenario, if you write a js file. There are many functions and methods in it. If you want to use it for the front end, you also want to use it for the nodejs back end, so you can use this method.

  1. Configure install configure webpack. webpack.config.jsThe base configuration can be
const path  = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    
    
    entry:"./src/index.js",
    output:{
    
    
      filename:'bundle.js',//打包好的js名称
      path:path.resolve(__dirname,'./dist'),
      library: 'TEST', // 为你的库指定一个全局变量名
      libraryTarget: 'umd', // 将你的库以 UMD 格式导出
      clean:true
    },
    mode:'production',
    plugins:[
      new HtmlWebpackPlugin({
    
    
        template:"./index.html",
        filename:'app.html',
        inject:'body'
      })
    ],
    devtool:"inline-source-map",
    devServer:{
    
    
      static:'./dist'
    }
}

And your index.jsfile can be

export function greet(name) {
    
    
  return `Hello, ${
      
      name}!`;
}

export function add(a, b) {
    
    
  return a + b;
}
export const pi = 3.14;

Execute the packaged code
npx webpack


After that, your dist folder will have a bundle.jscode, so that you can use the methods in this library. Here through this. <script>Test Anyway, when I only import the front-end browser environment, I import the packaged UMD format module through the tag in the HTML file :

<script src="./bundle.js" type="module"></script>
<script type="module">
	console.log(TEST);
</script>

insert image description here
<script>Import this packaged .jsfile directly in . There is a global library name that binds all exported functions to the library object through the webpack configuration name.
You can also directly importimport this js.

 <script type="module">
	import './bundle.js';
    console.log(TEST);
 </script>

No set of codes have been explored, running under nodejs and es6 modules. Too much food mainly! ! ! !

So how to use it in nodejs?

Here webpack says libraryTarget: 'umd', // 将你的库以 UMD 格式导出, and this is a front-end and back-end cross-platform solution
, but when I run it in nodejs, I report an error : self is not defined. The "self is not defined" error usually occurs because when using UMD format modules, there are references to global objects like self or window in the code, but in some environments (such as Node.js, etc.) these global objects are not defined.

This error usually occurs when global object references like this, self, or window are used, and these objects are not defined in the current context. UMD modules may have different global objects in different environments, so using these global objects directly may cause "self is not defined" errors in some environments.

Because it is packaged by webpack, then set thisglobalObject: 'this'

output:{
    
    
      filename:'bundle.js',
      path:path.resolve(__dirname,'./dist'),
      library: 'TEST', // 为你的库指定一个全局变量名
      libraryTarget: 'umd', // 将你的库以 UMD 格式导出
      globalObject: 'this',//指定 UMD 格式中的全局对象,以便在不同环境下正确解析全局对象的引用。
      clean:true
    },

Here you can use it in ondejs

const cc  = require("./bundle.js");//把全局的TEXT名称赋值转为cc
console.log(cc.add(1,4));

insert image description here
Basic packaging is fine, but after opening this, you cannot specify this

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/131828116