在我的webpack中,我有这个带有webpack块的配置
module.exports = createConfig([
customConfig({
resolve: {
modules: [
'src',
'node_modules',
],
},
}),
entryPoint({
app: ['./src/client'],
}),
setOutput({
path: path.resolve(__dirname, `../${assetPath}`),
publicPath: `${publicPath}/`,
filename: 'bundle.js',
}),
babel(),
cssModules(),
我能够从node_modules导入非常好,而且还可以从src文件的第一个目录中导入
src
components
icons
index.js
navs
primary.js
containers
index.js
client.js
<{1>} client.js
如果我import App from 'containers
它可以正常使用
但是如果在primary.js中我试图避免像这样的相对进口
import Icons from 'components/icons'
我收到此错误
module.js:471
throw err;
^
Error: Cannot find module 'components/icons'
at Function.Module._resolveFilename (module.js:469:15)
at Function._module2.default._resolveFilename (/Users/abiodun/projects/***/****/node_modules/require-hacker/babel-transpiled-modules/require hacker.js:423:34)
at Function.module._load (/Users/abiodun/projects/****/****/node_modules/piping/lib/piping.js:211:27)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Users/abiodun/projects/****/****/src/components/primary-nav/primary-nav.jsx:5:1)
at Module._compile (module.js:570:32)
at Module.require._compile (/Users/abiodun/projects/****/****/node_modules/webpack-isomorphic-tools/source/index.js:477:29)
at loader (/Users/abiodun/projects/****/****/node_modules/babel-register/lib/node.js:144:5)
at Object.require.extensions.(anonymous function) [as .jsx] (/Users/abiodun/projects/****/****/node_modules/babel-register/lib/node.js:154:7)
任何帮助都值得赞赏
答案 0 :(得分:1)
所以事实证明问题来自节点方面,因为我正在进行同构服务器端渲染。 我必须添加&#39; add-module-path&#39;模块使节点需要来自node_modules以外的不同目录 npm i add-module-path --save 这是我的rootServer.js文件中的最终代码。
require('app-module-path').addPath(__dirname); // add this lines
const WebpackIsomorphicTools = require('webpack-isomorphic-tools');
const isomorphicConfig = require('./webpack/isomorphic.config');
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production';
if (global.__DEVELOPMENT__) {
if (!require('piping')({ hook: true, ignore: /(\/\.|~$|\.json|\.scss$)/i, })) {}
require('./babel');
require('app-module-path').addPath('./src'); // add this path if it's development
}
else {
require('app-module-path').addPath('./dist'); // add this part if it's production
}
const serverPath = global.__DEVELOPMENT__ ? 'src' : 'dist';
global.webpackIsomorphicTools = new WebpackIsomorphicTools(isomorphicConfig)
.server('./', () => {
require(`./${serverPath}/server`)();
});
Webpack在没有同构服务器端渲染的情况下处理前端非常好。