How to add extra replacers #73
Replies: 4 comments 7 replies
-
I cannot seem to get this working. My code is nearly identical to yours, only changed .exampleReplacer.js to .ts as you included types in your first code snippet. I get the following error: |
Beta Was this translation helpful? Give feedback.
-
@raouldeheer You might want to update the example code snippet mentioned above in ESM format. A replacer written in ESM format didn't work for me, got error "Failed to import replacer". |
Beta Was this translation helpful? Give feedback.
-
It took me a whole day to figure out how to write a replacer for If your package.json file: {
"name": "your-project-name",
"description": "",
"type": "module",
"files": [
"dist"
],
...
} Then, if you need to add a replacer, keeping the default tsconfig.json file: {
"compilerOptions": {
...
},
"tsc-alias": {
"verbose": true,
"resolveFullPaths": true,
"replacers": {
"yourCustomReplacer": {
"enabled": true,
"file": "./yourCustomReplacer.cjs" //Your custom replacer, must be .cjs when package.json type is module.
}
}
}
} Finally, the const fs = require('fs');
exports.default = ({ orig, file }) => {
const fileContents = fs.readFileSync(file, 'utf8');
//Add your custom logic for replacing text inside the file.
newContents = newContents.replace(/\.(png|jpg|gif|svg)";/g, '.jsx"');
fs.writeFileSync(file, newContents);
return orig;
}; |
Beta Was this translation helpful? Give feedback.
-
I wonna to add one detail about the option tsc-alias.replacers.X.file.
where "scripts/treatExtensions.js" is:
File "scripts/treatExtensions.js" was called but the error "tsc-alias error: Failed to import replacer " appears all time.
to:
Which is strange, since the file is always processed anyway and all other configuration files are specified with relative paths... |
Beta Was this translation helpful? Give feedback.
-
In this tutorial I will explain how to add an extra replacer to
tsc-alias
with command-line, API ortsconfig.json
.A replacer is a function that transform an import statement to a replaced import statement.
For example:
import "@/functions"
toimport "./functions"
.Replacer code
This is an example replacer that logs all import statements.
Compiling replacer to commonjs
Replacers have to be compiled to commonjs. This can be done with this command:
Adding replacer to tsc-alias
With command-line
With API
With tsconfig (recommended)
Beta Was this translation helpful? Give feedback.
All reactions