2

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..

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');
Moonwalker
  • 3,462
  • 4
  • 25
  • 31
  • Questions asking for software recommendations or the "best" of anything are off-topic for Stack Overflow. That being said, you could always do a mass find-replace with a regular expression. `import ([\{\}a-zA-Z0-9]+) from (["'][a-zA-Z0-9 -]+["']) -> const $1 = require($2)` (that was off the top of my head so it's probably broken in some way) – Mike Cluck Apr 11 '17 at 18:23

2 Answers2

9

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...

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    all this time I was running various regex on sed on my mac os x and nothing worked, thus my question. and then your answer struck me GNU sed...and of course I forgot default sed on Mac OS X in not GNU...:) Thanks! – Moonwalker Apr 11 '17 at 19:12
  • s/import(\s+.+\s+)from\s+(\S+);/ seem to be capturing the right token – Moonwalker Apr 11 '17 at 19:40
  • Sure, it's just not as precise as the regexp I posted so it'll be a bit more likely to produce false matches. – Ed Morton Apr 11 '17 at 23:14
  • I had to deal with ones like `import { createStore } from 'redux';` as well so I just modified it to `sed -i -E 's/import\s+\{\s+(\S+)\s+\}\s+from\s+(\S+);/const \1 = require(\2).\1;/'` – Alex028502 Sep 02 '22 at 11:26
  • had a few others to do by hand after that.. and a few adjustments to make.. but still made the job a lot easier – Alex028502 Sep 02 '22 at 11:48
4

Just in case someone wanted the opposite, use:

sed -E 's~const (.*) = require\((.*)\);~import \* as \1 from \2~'
Jose Alban
  • 7,286
  • 2
  • 34
  • 19