Webpack / typescript require works but import doesn't

风格不统一 提交于 2021-01-27 12:42:25

问题


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?


回答1:


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");


来源:https://stackoverflow.com/questions/34563578/webpack-typescript-require-works-but-import-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!