1

我正在尝试在 Webpack 2 中使用以下语法:

import someSvc = require("./some.svc.js");

但我收到错误:

error TS2307: Cannot find module './some.svc.js'.

我究竟做错了什么?!如何在 Webpack 2 中导入我的 js 模块?

为了彻底起见,我将我的项目归结为最小的示例,并将提供以下文件:

webpack.config.js

var path = require('path');

module.exports = function makeWebpackConfig() {
  var config = {};
  config.entry = { 'app': './src/main.ts' };
  config.output = {
    path: root('dist'),
    filename: 'js/[name].js'
  };
  config.module = {
    rules: [
      {
        test: /\.ts$/,
        loaders: ['ts-loader']
      }
    ]
  };
  return config;
}();

// Helper functions
function root(args) {
  args = Array.prototype.slice.call(arguments, 0);
  return path.join.apply(path, [__dirname].concat(args));
}

包.json

{
  "name": "webpack",
  "version": "1.0.0",
  "description": "",
  "main": "src/main.ts",
  "dependencies": {},
  "devDependencies": {
    "ts-loader": "^0.9.5",
    "typescript": "^2.0.3"
  },
  "scripts": {},
  "author": "",
  "license": "ISC"
}

tsconfig.js

{
  "compilerOptions": {
    "target": "ES5",
    "module": "commonjs",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noEmitHelpers": true
  },
  "compileOnSave": false,
  "buildOnSave": false,
  "exclude": [
    "node_modules"
  ]
}

src/main.ts

import someSvc = require("./some.svc.js");

src/some.svc.js

if (typeof module !== 'undefined' && module.exports) {
    module.exports.config = function (conf) {
        return { abc: 123 };
    };
}

将这些文件粘贴在一起,运行webpack,您应该会看到相同的错误。

我错过了一些简单的东西来让它工作吗?

4

1 回答 1

2

在为此挣扎了太久之后,像往常一样写SO帖子不知何故触发了我的大脑或其他东西。

从 SystemJs 到 Webpack,我根本没想到require会发生变化。

不过,我通过两个更改解决了这个问题。

这一行:

import someSvc = require("./some.svc.js");

变成:

var someSvc = require("./some.svc.js");

并运行它(我使用的是 TypeScript 2.0):

npm install @types/node --save-dev

于 2016-10-22T00:28:39.350 回答