I have a react application written in typescript that uses webpack to pile. So far, I could import libraries through the import
keyword from node_modules.
However, there are a few libraries I would like to use that are not on the npm registry. So I can't do a npm install of these libraries. For example, Papa Parse is one of those that I can't quite find its npm package. They usually only provide a minified js file which I can't just import into my Typescript file.
For applications that uses webpack to build, how can I use libraries that are not on the npm registry in my code?
I have a react application written in typescript that uses webpack to pile. So far, I could import libraries through the import
keyword from node_modules.
However, there are a few libraries I would like to use that are not on the npm registry. So I can't do a npm install of these libraries. For example, Papa Parse is one of those that I can't quite find its npm package. They usually only provide a minified js file which I can't just import into my Typescript file.
For applications that uses webpack to build, how can I use libraries that are not on the npm registry in my code?
Share Improve this question asked Aug 18, 2016 at 8:23 CarvenCarven 15.7k30 gold badges124 silver badges185 bronze badges 1- You may have to shim them in webpack.... – Callum Linington Commented Aug 18, 2016 at 8:30
3 Answers
Reset to default 3For anything that doesn't have an npm
package, you'll have to download the file and put it somewhere in your project - I'd remend putting it in a directory called vendor
or lib
.
The import
statement can use a relative path to the module you want to use, so it should be straightforward, e.g. if you put your third-party module in vendor/some-lib.js
, you would import it with:
// src/foo.js
import './../vendor/some-lib';
If you want to get fancy, you can use resolve.alias
in your webpack config so that you never have to work out the relative path.
// webpack.config.js
const path = require('path');
// ...
resolve: {
alias: {
vendor: path.resolve(__dirname, 'vendor')
}
},
// src/foo.js
import 'vendor/some-lib';
You can install git-hosted libraries like this:
npm install git+ssh://[email protected]:mholt/PapaParse.git#4.3.0
Note that everything after the hash has to be either a mit hash or a tag. I got 4.3.0 from here: https://github./mholt/PapaParse/releases
If you omit the hash, you'll get the most recent version, but keep in mind every time someone does a fresh npm install
in your codebase there's a chance of them pulling down a version with breaking changes.
If you cannot import them then you can use require on them and webpack will build them into bundle.
require("PapaParse");
Note:- if you are resolving js files from webpack then you can use simply
import "papaparse"