问题描述
我正在从头开始使用React + Koa + TypeScript构建简单的应用程序,但是我遇到了错误,该错误指示未找到Webpack配置模块(显然位于根级别),并且运行时无法解析该模块:
/Users/miqdad/Documents/Works/blog/dist/server/index.js:99
throw e;
^
Error: Cannot find module '/Users/miqdad/Documents/Works/blog/webpack.config'
at webpackEmptyContext (/Users/miqdad/Documents/Works/blog/dist/server/index.js:97:10)
at Module../server/index.ts (/Users/miqdad/Documents/Works/blog/dist/server/index.js:154:71)
at __webpack_require__ (/Users/miqdad/Documents/Works/blog/dist/server/index.js:20:30)
at /Users/miqdad/Documents/Works/blog/dist/server/index.js:84:18
at Object.<anonymous> (/Users/miqdad/Documents/Works/blog/dist/server/index.js:87:10)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) {
code: 'MODULE_NOT_FOUND'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! blog@0.0.1 dev:server: `cross-env TARGET=server webpack && node dist/server/index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the blog@0.0.1 dev:server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/miqdad/.npm/_logs/2020-10-03T02_42_41_863Z-debug.log
这是我的src/server/index.ts
和my folder structure:
import Koa from 'koa';
import cors from '@koa/cors';
import bodyParser from 'koa-bodyparser';
import logger from 'koa-logger';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import path from 'path';
import appRootDir from 'app-root-dir';
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || 'localhost';
const isProd = process.env.NODE_ENV === 'production';
const app = new Koa();
app.use(bodyParser());
app.use(logger());
app.use(cors());
if (!isProd) {
// source of the error
const webpackConfig = require(path.resolve(
appRootDir.get(),'webpack.config',));
const compiler = webpack(webpackConfig);
app.use(
webpackDevMiddleware(compiler,{
publicPath: webpackConfig.output.publicPath,serverSideRender: true,stats: 'minimal',logLevel: 'error',}),);
app.use(webpackHotMiddleware(compiler,{}));
}
app.listen(PORT,() => {
console.log(`✅ Server is running at http://${HOST}:${PORT}`);
});
我的webpack配置分为客户端和服务器配置文件。我认为主要的关注点位于服务器配置文件中,这可能会使我在其中丢失某些内容。出于调试目的,这些是我的ts,webpack和babel文件配置:
tsconfig.json
{
"compilerOptions": {
"outDir": "dist","module": "commonjs","target": "es5","lib": ["dom","ES2020"],"baseUrl": "src","paths": {
"@client/*": ["client/*"],"@server/*": ["server/*"],"@helpers/*": ["helpers/*"]
},"sourceMap": true,"allowJs": true,"jsx": "react","moduleResolution": "node","forceConsistentCasingInFileNames": true,"noImplicitReturns": true,"noImplicitThis": true,"noImplicitAny": true,"strictnullchecks": true,"suppressImplicitAnyIndexErrors": true,"noUnusedLocals": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true
},"exclude": ["node_modules","configs","dist"]
}
webpack.config.js
const path = require('path');
const utils = require('./configs/utils');
const paths = require('./configs/paths');
const { env,target } = utils;
const configPath = path.resolve(
paths.root,'configs',target,`webpack.${env === 'production' ? 'prod' : 'dev'}`,);
const config = require(configPath);
module.exports = config;
configs/webpack.base.js
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const paths = require('./paths');
const utils = require('./utils');
const { env,isProd } = utils;
const baseConfig = {
mode: env,context: paths.src,resolve: {
modules: ['node_modules'],extensions: ['.js','.ts','.tsx','.json'],alias: {
'react-dom': '@hot-loader/react-dom',},output: {
publicPath: '/',path: paths.dist,module: {
rules: [
{
test: /[jt]sx?$/,exclude: paths.nodeModules,loader: 'babel-loader',options: {
cacheDirectory: true,cacheIdentifier: target,cacheCompression: isProd,compact: isProd,configFile: paths.babelConfig,{
loader: 'file-loader',exclude: [/\.m?([jt])sx?$/,/\.json$/],options: {
emitFile: !isProd,name: 'assets/[name].[hash:8].[ext]',],plugins: [
new CircularDependencyPlugin({
exclude: /node_modules/,failOnError: true,new ForkTsCheckerWebpackPlugin({
eslint: {
files: './**/*.{ts,tsx,js,jsx}',typescript: {
context: paths.root,configFile: paths.tsConfig,stats: {
colors: true,modules: false,children: false,performance: {
hints: false,};
module.exports = baseConfig;
config/server/webpack.base.js
const { merge } = require('webpack-merge');
const nodeExternals = require('webpack-node-externals');
const base = require('../webpack.base');
const paths = require('../paths');
const serverBaseConfig = merge(base,{
target: 'node',entry: {
index: paths.srcServer,output: {
path: paths.distServer,externals: [nodeExternals()],node: {
__dirname: false,__filename: false,});
module.exports = serverBaseConfig;
config/server/webpack.dev.js
const WebpackBar = require('webpackbar');
const { merge } = require('webpack-merge');
const serverBase = require('./webpack.base');
const serverDevConfig = merge(serverBase,{
mode: 'development',devtool: false,output: {
filename: '[name].js',plugins: [new WebpackBar({ name: 'server',color: 'green' })],});
module.exports = serverDevConfig;
babel.config.js
const { compilerOptions } = require('./tsconfig');
const utils = require('./configs/utils');
const resolver = require('./configs/utils/resolver');
const { env,isDev } = utils;
const isClient = target === 'client';
module.exports = (api) => {
const alias = resolver(compilerOptions);
api.cache(() => `${env}${target}`);
const targets = target === 'server' ? { node: 'current' } : undefined;
const presets = [
['@babel/preset-env',{ targets,useBuiltIns: 'entry',corejs: 3 }],'@babel/preset-typescript',['@babel/preset-react',{ development: isDev,useBuiltIns: true }],];
const plugins = [
['@babel/plugin-transform-runtime'],['@babel/plugin-proposal-class-properties',{ loose: true }],['babel-plugin-module-resolver',{ alias }],];
if (isClient && isDev) {
plugins.push('react-hot-loader/babel');
}
return { presets,plugins };
};
依赖
"koa": "^2.13.0","typescript": "^4.0.3","webpack-cli": "^3.3.12","webpack": "^4.44.2",
我怀疑是因为目标模块总是试图在node_modules
下解决吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)