cjs-to-es6 - 將CommonJS轉換成ES6模塊
cjs-to-es6
CLI to convert JavaScript files from CommonJS to ES6 modules (aka ES2015 modules, aka JavaScript modules, aka hipster require()
). Uses 5to6-codemod under the hood.
Usage
Install it:
npm install -g cjs-to-es6
Then run it:
cjs-to-es6 [ --verbose ] files/directories...
Examples:
cjs-to-es6 index.js # convert a single file cjs-to-es6 lib/ # convert all files in a directory cjs-to-es6 foo.js bar.js lib/ # convert many files/directories
All files are modified in-place.
Example input and output
In comes CommonJS:
var flimshaw = require('flimshaw');
var twentyEightSkidoo = require('twenty-eight').skidoo;
exports.flubTheDub = 'flubTheDub';
module.exports = 'zings';
Out goes ES6 modules:
import flimshaw from 'flimshaw';
import {skidoo as twentyEightSkidoo} from 'twenty-eight';
export let flubTheDub = 'flubTheDub';
export default 'zings';
Migrating from CommonJS to ES6 modules
Not all uses of CommonJS have a 1-to-1 equivalent in ES6 modules. So you might have to correct some errors manually.
Use --verbose
to get detailed output, or follow these general tips:
export
s must be at the top level
This is invalid:
if (clownShoes) {
export default new Clown();
} else {
export default new RespectableGentleman();
}
Instead do:
var result = clownShoes ? new Clown() : new RespectableGentleman();
export default result;
import
s also have to be at the top level
This is invalid:
try {
import MysterModule from 'mystery-module';
} catch (err) {
console.log("It's a mystery!");
}
There is no equivalent for this try
/catch
pattern in ES6 modules.
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!