After the webpack is packed, it cannot be called. Instead, use uglifyjs to pack and compress

Posted by jwmessiah on Fri, 17 Jan 2020 14:01:51 +0100

Background:

The project is based on native js and does not use any scaffolding or framework, but it also needs to be packaged and compressed.

Some global variables are declared in the js of the project for other js to call.

At this time, if we use the web pack, based on the web Pack feature, we will nest a layer of large functions, which will turn the variables in js into local, which can not be called by other js.  

As a result, webback was discarded. uglifyjs is selected.

Reason:

The web pack version of uglifyjs is also available in the web Pack: uglifyjs web pack plugin.

Packaging approach:

Package source file: js file under dev folder = = = = > target file: js folder.

directory structure

 

 

 

Use:

1. If es5 uses uglify JS official website, this is the default branch.

2. If es6 uses the harmony branch of uglify es official website, it is uglify es.

uglifyjs official website: https://github.com/mishoo/UglifyJS2

Steps:

First, make sure that your computer has node installed. This is started with node.

 

1. Download uglifyjs here I download es version.

npm install uglify-es -D

2. Write a package.json. The following package.json can be downloaded and directly npm i will omit the first step.

I wrote the order in scripts

I think I can also transfer and try to sourceMap after packaging under development,

Pack and compress under production.

My entry file is named entry.js

{
  "name": "ocplayermin",
  "version": "1.0.0",
  "description": "ocplayer min version",
  "main": "entry.js",
  "scripts": {
    "build_min": "NODE_ENV=production node entry.js --progress",
    "build_min_dev": "NODE_ENV=development node entry.js --progress"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {},
  "devDependencies": {
    "uglify-es": "^3.3.9",
    "uglify-js": "^3.7.4"
  }
}

 

Note: node ﹣ env is not compatible under windows. You need to install the cross env plug-in: NPM install cross env -- save dev

After installation, add cross env to build min and build min dev.

 

 

3. entry.js code

We plan to package the js file under the dev file into the js file.

Code logic:

  • 1. Traverse all js files under the dev folder to get the file name and old path.
  • 2. Generate js folder. If there is no js folder, create it to generate the path of new file.
  • 3. Under development, use UglifyJS.minify compression to generate the sourceMap file.
  • 4. The. js.map file is generated in the development environment under production. Delete the. js.map file here to generate the. js file.

Problems encountered:

Since the file read by mapping source map needs to be in the same directory as js when reading by browser, the port path of the front end needs to be assigned to. js.map.

For example: Address: 127.0.0.1:5500/minversion/index.html;

Recommend an easy-to-use editor (use vcode editor's open with live server startup project, default port 5500)

Read the front-end JS path: 127.0.0.1:5500/minversion/js/xxx.js;

The path generated by the mapping must also be 127.0.0.1:5500/minversion/js/xxx.js.map; if it is'. / js/xxx.js.map ', it cannot be read.

I have created a new config.json special access constant. I write the front-end port here and declare it as "plugin" URL. As long as I modify this, entry.js can read it.

If you don't know much about the source map, you can see the official website documents.

config.json

{"pluginUrl":"http://127.0.0.1:5500/minversion"}

entry.js

const path = require('path');
const fs=require('fs');

const UglifyJS = require("uglify-es");//Compatible with es6
//var UglifyJS = require("uglify-js");//es5
const ORIGIN_PATH='/dev';
const ORIGIN_DIR = '.'+ORIGIN_PATH; // Original catalogue
const DESTINATION_PATH='/js';
const DESTINATION_DIR = '.'+DESTINATION_PATH;//Packed catalog
var PLUGIN_URL="";/*address*/
PLUGIN_URL=JSON.parse(fs.readFileSync('./config.json','utf-8')).pluginUrl;

//  Traverse directory to get file information
function getPath(_path, callback) {
    let files = fs.readdirSync(_path);
    files.forEach(function(file){
        //Judge whether the file exists
        if (fs.statSync(_path + '/' + file).isFile()) {
            callback(_path, file);
        }
    });
}
//Generate compressed file
function buildMin (callback) {
    /*Create min folder if min does not exist*/
    if ( !fs.existsSync(DESTINATION_DIR) ) {
        fs.mkdirSync(DESTINATION_DIR);
    } 
    // Function
    getPath(ORIGIN_DIR, function (_path, file) {
        let fileName = file.match(/(\S+)(\.\S+)$/)[1]; // Get file name
 
        let oldPath = _path + '/' + file, // Original path
            newPath = DESTINATION_PATH + '/' + fileName+'.js'; // The new path cannot reach. js
            
         const _code = fs.readFileSync(oldPath, 'utf-8');
         callback(newPath,fileName,_code)
         
    });
}
//Delete files
function deleteFile(delPath, direct) {
    delPath = direct ? delPath : path.join(__dirname, delPath)
    try {
        /**
         * @des Determine whether the file or folder exists
         */
        if (fs.existsSync(delPath)) {
            fs.unlinkSync(delPath);
        } else {
            console.log('inexistence path: ', delPath);
        }
    } catch (error) {
        console.log('del error', error);
    }
}

if (process.env.NODE_ENV === 'production') {
    /*production environment*/
    getPath(DESTINATION_DIR, function (_path, file) {
        //Delete. map file
        if(file.indexOf('.js.map')>-1){
            let delp = _path+'/'+file;
            deleteFile(delp)
        }      
    })
  //Pack buildMin(function(newPath,fileName,_code){ const minCode = UglifyJS.minify(_code,{ compress:{pure_funcs:'console.log'} }).code; fs.writeFileSync('.'+newPath, minCode); }); } if (process.env.NODE_ENV === 'development') { /*development environment*/
  //Pack buildMin(function(newPath,fileName,_code){ var _codeFname = "."+newPath; var _code_file={}; _code_file[_codeFname]=_code; const _minObj = UglifyJS.minify(_code_file,{ sourceMap: { filename:fileName+'.js', url:PLUGIN_URL+newPath+".map",//Generated is 127.0.0.1:5500/minversion/js/xxx.js.map includeSources:PLUGIN_URL+newPath+".map", }, keep_fnames:true, warnings: true, }); fs.writeFileSync('.'+newPath, _minObj.code); fs.writeFileSync('.'+newPath+'.map', _minObj.map); }); }

  

So far, the package is successful. You can copy it to your own project and try it. Remember to change the source folder, target folder to your project path, and plugin? URL.

Topics: Javascript JSON npm github Windows