Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack / typescript require works but import doesn't

I'm trying to import a node_module into a TypeScript file. I'm using an adaptation of angular2-webpack-starter for my project structure.

import ace from 'brace';

In one of my files gives me

Cannot find module 'brace'.

But

var ace = require('brace');

Works fine. According to this issue I shouldn't be having any problems.

My webpack config file is copied from angular2-webpack-starter. My tsconfig.json is as follows

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true
  },
  "files": [
    "src/bootstrap.ts",
    "src/vendor.ts",
    "src/polyfills.ts"
  ],
   "filesGlob": [
      "./src/**/*.ts",
      "!./node_modules/**/*.ts"
   ],
   "compileOnSave": false,
   "buildOnSave": false
}

Why would one work but not the other?

like image 534
Jack Guy Avatar asked Jan 07 '23 21:01

Jack Guy


1 Answers

The answer is related to this issue. If a module doesn't have type data available (via a .d.ts file), the ES6 module syntax

import name from "module-name";
import * as name from "module-name";
import { member } from "module-name";
//etc

will not work and one must use the CommonJS alternative,

var name = require("module-name");
like image 69
Jack Guy Avatar answered Jan 15 '23 07:01

Jack Guy