如何将某些JavaScript代码从导入批量转换为要求? [英] How to bulk convert some javascript code from import to require?

查看:57
本文介绍了如何将某些JavaScript代码从导入批量转换为要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换许多Javascript文件,将import替换为require.显然,手工进行编辑将是艰巨的任务,因此我想使用脚本将其自动化.如何使用Unix Shell脚本完成此任务?以下是我要替换的模式.文件的所有其他内容应保持不变.令牌之间的间距可能不一致.

I need to convert lots of Javascript files replacing import with require. Obviously doing edits by hand would be daunting so I want to automate it with a script. How can I accomplish this using a Unix shell script? Below are the patterns that I would like to replace. All other contents of the file should remain unchanged. Spacing could be inconsistent between tokens..

我当时在考虑awk等,但是对语法并不真正熟悉.

I was thinking about awk etc but not really familiar with the syntax.

import Foo from 'bar'; -> const Foo = require('bar');
import Foo from "bar"; -> const Foo = require("bar");
import {Foo} from "bar"; -> const {Foo} = require("bar");
import {Foo, Bar, baz as Baz} from 'bar' -> const {Foo, Bar, baz as Baz} = require('bar');

推荐答案

对于ERE,对于-E使用GNU sed,对于空格/非空格,使用\s/\S速记:

With GNU sed for -E for EREs and \s/\S shorthand for spaces/non-spaces:

$ sed -E 's/import(\s+\S+\s+)from\s+(\S+);/const\1= require(\2);/' file
const Foo = require('bar');
const Foo = require("bar");
const {Foo} = require("bar");

当然是非常脆弱的方法...

A very fragile approach of course...

这篇关于如何将某些JavaScript代码从导入批量转换为要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆