My goal is to use an external JavaScript Library in an Angular 2 project. To do so, there are two ways:
1) Declare those variables in my files (they will be present in the environment during runtime) like this:
declare var numbro: any; // in my Component
And I added the numbro.js file like this in the index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>APP Angular 2</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="../node_modules/numbro/numbro.js"></script>
<base href="/">
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
2) The other solution is to use their declaration files in TypeScript (if they already exist)
The problem here is that not all JavaScript libraries support TypeScript and it didn't seem a good idea to create declaration files for each library I want to use in my project. Therefore, I decided to adopt the first way. Everything seemed good until I faced this error:
ORIGINAL EXCEPTION: require is not defined
Here is my webpack configuration:
'use strict';
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const merge = require('webpack-merge');
const webpack = require('webpack');
const communConfig = require('./webpack-commun.config.js');
module.exports = function(options) {
const hotModuleReplacementPlugin = new webpack.HotModuleReplacementPlugin();
const commonsChunkPlugin = new CommonsChunkPlugin({
name: [ 'vendor', 'polyfills' ]
});
const htmlPlugin = new HtmlWebpackPlugin({
template: options.html
});
return merge(communConfig(options), {
entry: {
polyfills: options.polyfills,
vendor: options.vendor,
app: [
`webpack-dev-server/client?http://localhost:${options.port}`,
'webpack/hot/only-dev-server',
options.entry
]
},
output: {
path: options.outputDir,
publicPath: `http://localhost:${options.port}`,
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
hotModuleReplacementPlugin,
commonsChunkPlugin,
htmlPlugin
]
});
};
Here is my vendor.ts file:
import 'rxjs';
import 'core-js/es6';
import 'zone.js/dist/zone';
import '@angular/common';
import '@angular/compiler';
import '@angular/core';
import '@angular/http';
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import 'numbro';
And Here is my pollyfills.ts:
import 'es6-shim';
import 'reflect-metadata';
import 'ts-helpers';
Is there a way to resolve this?