找不到模块“模块”-Rewire.js
Posted
技术标签:
【中文标题】找不到模块“模块”-Rewire.js【英文标题】:Cannot find module "module" - Rewire.js 【发布时间】:2018-02-21 22:19:34 【问题描述】:我正在尝试将rewire
与我的 Karma(Webpack + Typescript)单元测试一起使用。我的单元测试是用 Typescript 编写的,与 Webpack 捆绑在一起,然后使用 Karma 运行。我不断收到错误:
PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR
Error: Cannot find module "module"
at src/myTest.spec.ts:187
我查看了Rewire的代码,问题出在一行
var Module = require("module"),
我知道有一个Webpack Rewire 插件,但是当我使用它时,我遇到了与already reported in an issue 相同的问题。
我所有不使用rewire
的测试都可以正常工作。
这是我的测试文件:
import rewire = require("rewire");
const decorators = rewire("./decorators");
describe('something', () =>
it('should do something', () =>
decorators.__set__('Test', () => 'hello');
// In know this is pointless, but it's just to make sure that rewire works.
expect(decorators.Test).toBe('hello');
);
);
这是我的 webpack 配置:
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var nodeModules = ;
fs.readdirSync('node_modules')
.filter(function (x)
return ['.bin'].indexOf(x) === -1;
)
.forEach(function (mod)
nodeModules[mod] = 'commonjs ' + mod;
);
// Our Webpack Defaults
var webpackConfig =
entry: './src/index.ts',
target: 'node',
module:
loaders: [
test: /\.ts$/, loaders: ['ts-loader'], exclude: /node_modules/
]
,
plugins: [
new webpack.BannerPlugin(banner: 'require("source-map-support").install();', raw: true, entryOnly: false),
new webpack.optimize.UglifyJsPlugin(sourceMap: true),
new webpack.optimize.AggressiveMergingPlugin(),
],
output:
path: path.resolve(__dirname, './dist'),
filename: 'index.js',
sourceMapFilename: 'index.map'
,
externals: nodeModules,
devtool: 'source-map',
resolve:
extensions: ['.ts', '.js']
;
module.exports = webpackConfig;
这是我karma.conf.js
的(相关)部分:
frameworks: ['jasmine'],
files: [
'src/**/*.spec.ts',
'test/**/*.ts'
],
exclude: [],
webpack:
devtool: webpackConfig.devtool,
module: webpackConfig.module,
resolve: webpackConfig.resolve,
,
webpackMiddleware:
quiet: true,
stats:
colors: true
,
preprocessors:
'src/**/*.spec.ts': ['webpack', 'sourcemap'],
'test/**/*.ts': ['webpack', 'sourcemap']
,
【问题讨论】:
嘿,您能找到上述解决方案吗?我有同样的问题。 不,我最终使用了另一个库:) 哪个库? 我使用 MochaJs 是因为 Jasmine 仅用于前端代码。 【参考方案1】:我觉得你写错了 import rewire = require("rewire");
应该是
import rewire from 'rewire'
对于 ES6 或
const rewire = require('rewire')
对于 ES5
【讨论】:
以上是关于找不到模块“模块”-Rewire.js的主要内容,如果未能解决你的问题,请参考以下文章