Webpack设置如何更改需要模块路径?

时间:2017-12-29 01:23:16

标签: webpack

我的测试程序看起来像这样 -

script
 --app
 ---- member
 ---------index.js
 ---- util
 ---------memberKit.js
 ---- main.js

我希望到处呼叫./app/*来访问script/app/*

文件 member / index.js ,如下所示 -

import { show as kitShow } from './app/util/memberKit';
export const show = () => console.log('member show es6');
console.log(kitShow);

并提交 webpack.config.js ,如下所示 -

var path = require('path');
// var DirectoryNamedWebpackPlugin = require('directory-named-webpack-plugin');
module.exports = {
    devtool: 'source-map',
    entry: {
        main: path.join(__dirname, '/scripts/main.js')
    },
  // 输出的路径
    output: {
        path: path.join(__dirname, '/bundle'),
        filename: '[name].js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel',
            query: {
                presets: ['es2015']
            }
        }]
    },
    resolve: {
        root: path.resolve(__dirname, 'scripts')
        // plugins: [new DirectoryNamedWebpackPlugin()]
    }
};

我的代码会产生如下错误 -

ERROR in ./scripts/app/member/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./app/util/memberKit in /Users/xxx/Documents/temp/gulp-webpack/scripts/app/member
 @ ./scripts/app/member/index.js 8:17-48

2 个答案:

答案 0 :(得分:0)

您可能希望了解webpack支持模块解析的方法。具体来说是this section

答案 1 :(得分:0)

您的Webpack配置不正确(假设使用Webpack 2+)。还要确保配置文件与scripts/目录位于同一文件夹中。

您需要的是:

resolve: {
    modules: [
        path.resolve(__dirname, 'scripts'),
        'node_modules'
    ]
}

此外,当您使用Webpack的resolve.modules功能时,您必须将这些文件导入为绝对路径而不是相对路径。

import { show as kitShow } from 'app/util/memberKit';

app/文件夹添加为解析别名可能更好:

resolve: {
    modules: [
        path.resolve(__dirname, 'scripts', 'app'),
        'node_modules'
    ]
}

因此,您可以从其逻辑域文件夹中导入内容,而不必担心名为app/的文件夹。

import { show as kitShow } from 'util/memberKit';