WebPack 3:无法在配置文件中设置正确的路径,导致找不到模块错误

时间:2018-01-29 13:32:51

标签: webpack configuration webpack-dev-server

我在为 WebPack 3 设置正确的配置时遇到了困难。 首先,我的所有项目文件都位于一个文件夹(root)中。到目前为止一切运作良好。现在我的项目看起来像:

dist <folder> ----  For future builds
node_modules <folder> ----   
public <folder> ----    Probably for the future purpose to serve static: css, images, js, icons...
server <folder> ----    Server.js (express.js) ----
src <folder> ----   components <folder>
    ---css < folder > 
    ---fonts < folder >
    ---icons < folder >
    ---img < folder >
    ---js < folder > - third party JS
    ---.env
    ---ga.js
    ---i18n.js
    ---index.html
    ---index.js
    ---myDetector.js
    ---sitemap.xml
    ---webpack.config.js
package.json     
package-lock.json   

package.json 启动 express.js webpack-dev-server

...
"main": "src/index.js",
  "scripts": {
    "start": "start npm run start:client && start npm run start:server",
    "start:client": "webpack-dev-server --config src/webpack.config.js",
    "start:server": "node server/server.js"
  },
  "proxy": {
    "/contact": {
      "target": "http://localhost:3000"
    }
  },
  ...

webpack.config 更新和工作

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const PreloadWebpackPlugin = require('preload-webpack-plugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
const StyleExtHtmlWebpackPlugin = require('style-ext-html-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const autoprefixer = require('autoprefixer');
const CSPWebpackPlugin = require('csp-webpack-plugin');
const staticSourcePath = path.join(__dirname, 'static');
const sourcePath = path.join(__dirname);
const buildPath = path.join(__dirname, 'dist');
const GoogleFontsPlugin = require("google-fonts-webpack-plugin");
const HtmlCriticalPlugin = require("html-critical-webpack-plugin");

module.exports = {

    devtool: 'source-map',
    devServer: {
        historyApiFallback: true,
        contentBase: './src'        
    },

    entry: {
        vendor:  ['./src/js/plugins.js', 
            './src/js/classList.min.js',
            './src/js/jquery.nicescroll.min.js'].map(function(link){ 
                return path.resolve(__dirname, link); 
            }),

        base: ['./src/css/animate.css', './src/css/flag-icon.min.css',  './src/css/preloader.css', './src/css/react-router-modal.css',
            './src/css/simple-line-icons.css', './src/css/responsive.css', './src/css/style.css', './src/css/outdatedbrowser.css'].map(function(link){ 
                return path.resolve(__dirname, link); 
            }),
        entry: ["babel-polyfill", './src/index.js']
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: '[name].[chunkhash].js',
        publicPath: '/'
    },
    resolve: {
        extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
        modules: [
             path.join(__dirname, 'node_modules')
        ],

    },
    plugins: [
          new webpack.ProvidePlugin({
             $: 'jquery',
            '$': 'jquery',
            jquery: 'jquery',
            jQuery: 'jquery',
            'Popper': 'popper.js',
            Tether: 'tether'
          }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
            /*if (typeof cutCode === 'undefined') {}*/
        }),
        new webpack.optimize.ModuleConcatenationPlugin(),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'vendor.[chunkhash].js',
            minChunks: Infinity
        }),
        new webpack.LoaderOptionsPlugin({
            options: {
                postcss: [
                    autoprefixer({
                        browsers: [
                            'last 3 version',
                            'ie >= 10'
                        ]
                    })
                ],
                context: staticSourcePath
            }
        }),
        new webpack.HashedModuleIdsPlugin(),
        new HtmlWebpackPlugin({
            template: path.join(__dirname, './src/index.html'),
            path: buildPath,
            excludeChunks: ['base'],
            filename: 'index.html',
        }),     

        new PreloadWebpackPlugin({
            rel: 'preload',
            as: 'script',
            include: 'all',
            fileBlacklist: [/\.(css|map)$/, /base?.+/]
        }),
        new ExtractTextPlugin({
            filename: '[name].[contenthash].css',
            allChunks: true
        }),     
        new StyleExtHtmlWebpackPlugin({
            minify: true
        }),
        new webpack.NoEmitOnErrorsPlugin(),
    ],
    module: {

        rules: [{
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['env', 'react', 'stage-1'],
                    }
                },
                include: sourcePath
            },

            {
                test: /\.css$/,

                use: ExtractTextPlugin.extract({
                    fallback: "style-loader",
                    use: "css-loader"
                })
            },      

            {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'url-loader?limit=10000&name=[path][name].[ext]?[hash]',
                }]
            },

            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                use: 'url-loader?limit=10000',
            },
            {
                test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
                use: 'file-loader',
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/i,
                use: [
                    'file-loader?name=images/[name].[ext]',
                    'image-webpack-loader?bypassOnDebug'
                ]
            },
            // font-awesome
            {
                test: /font-awesome\.config\.js/,
                use: [{
                        loader: 'style-loader'
                    },
                    {
                        loader: 'font-awesome-loader'
                    }
                ]
            },

            // Bootstrap 4
            {
                test: /bootstrap\/dist\/js\/umd\//,
                use: 'imports-loader?jQuery=jquery'
            }

        ]
    }

};

错误: enter image description here 我认为问题存在于路径中,例如publicPath等...... 所以寻求帮助和建议以获得更好的配置。

1 个答案:

答案 0 :(得分:1)

问题是node_modules目录和Webpack配置文件的相对位置。解决方案,要么:

  1. webpack.config.js移至项目根目录(当前位于src目录中)
  2. 或者,更新您的Webpack配置文件resolve.modules密钥:将path.resolve('/node_modules')更改为path.resolve(__dirname, '../', 'node_modules')
  3. 我建议选项1)。您通常会拥有与项目根相关的所有配置。这使得在项目后期或新人入职时更容易找到/追踪。