webpack 找不到模块“module”- Rewire.js

zengzsys  于 2023-01-05  发布在  Webpack
关注(0)|答案(2)|浏览(208)

我尝试在Karma(Webpack + Typescript)单元测试中使用rewire。我的单元测试是用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']
},
slhcrj9b

slhcrj9b1#

我认为你写这个错误的导入rewire = require("rewire");
应该是

import rewire from 'rewire'

对于ES6或

const rewire = require('rewire')

适用于ES5

w8f9ii69

w8f9ii692#

在package.json中重写脚本对我很有效:

"test": "ts-node -O '{\"module\":\"commonjs\"}' node_modules/jest/bin/jest.js"

如果您收到错误
语法错误:JSON中位置0处的意外标记
这为我解决了这个问题:

ts-node -O \"{\\\"module\\\":\\\"commonjs\\\"}\" node_modules/jest/bin/jest.js

这不是我的主意。请看这个对Github问题的回答,以获得一个很好的解释。

相关问题