joeyguo/js-beautify-sourcemap

node 环境下使用报错

ganyouyin opened this issue · 1 comments

使用方式:

// index.js
const jbs = require('js-beautify-sourcemap');
const fs = require('fs');

let code = fs.readFileSync('./lib.js', 'utf-8');

let result = jbs(code, {}, {
    line: 2,
    column: 100
});

fs.writeFileSync('lib.formatted.js', result.code, {encoding: 'utf-8'});

console.log(result.loc);

之后执行:

node index.js

报错信息:

Error: Cannot find module './beautify.js'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at /Users/ganyouyin/Documents/____tmp____/test/node_modules/js-beautify-sourcemap/dist/js-beautify-sourcemap.js:4065:27
    at /Users/ganyouyin/Documents/____tmp____/test/node_modules/js-beautify-sourcemap/dist/js-beautify-sourcemap.js:4082:3
    at /Users/ganyouyin/Documents/____tmp____/test/node_modules/js-beautify-sourcemap/dist/js-beautify-sourcemap.js:8:82
    at Object.<anonymous> (/Users/ganyouyin/Documents/____tmp____/test/node_modules/js-beautify-sourcemap/dist/js-beautify-sourcemap.js:11:2)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)

定位到代码:

} else if (typeof exports !== "undefined") {
    // Add support for CommonJS. Just put this file somewhere on your require.paths
    // and you will be able to `var html_beautify = require("beautify").html_beautify`.
    var js_beautify = require('./beautify.js');
    var css_beautify = require('./beautify-css.js');

    exports.html_beautify = function (html_source, options) {
        return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
    };
} else if (typeof window !== "undefined") {

改成如下代码后可正常工作:

} else if (typeof exports !== "undefined") {
    // Add support for CommonJS. Just put this file somewhere on your require.paths
    // and you will be able to `var html_beautify = require("beautify").html_beautify`.
    var js_beautify = require('js-beautify');

    exports.html_beautify = function (html_source, options) {
        return style_html(html_source, options, js_beautify.js_beautify, js_beautify.css_beautify);
    };
} else if (typeof window !== "undefined") {

已fix