Using Webpack for simple site

2019-07-10 04:19发布

问题:

I'm trying to get webpack to work for the first time and I'm doing it on a simple website but, no matter what I try, it never works correctly. I've been stuck on it for weeks and I've seriously tried every thread out there to no avail. I just need someone who doesn't have a problem with webpack to look at my code and provide comment on how to get it to work correctly.

I have all my source code in the src directory. Libraries and developer dependencies are in the node_modules directory. And I want to run webpack and have it output everything to the dist directory. If I run a server using only the files in the src directory, it works fine but as soon as I run webpack and try to use the files in the dist directory, it all falls apart.

Here's webpack.config.js:

var webpack = require('webpack');
var path = require('path');

module.exports = {
context: __dirname + "\\src",
debug: true,
entry: "./index.webpack.js",
output: {
    path: __dirname + "\\dist",
    filename: "index.min.js"
},
module: {
    loaders: [
        {
            test:/\.js$/,
            exclude:/(node_modules)/,
            loader:'babel-loader',
            query: {
                presets:['es2015']
            }
        },
        {
            test:/\.css$/,
            exclude:/(node_modules)/,
            loader:'style-loader!css-loader'
        },
        {
            test:/\.less$/,
            exclude:/(node_modules)/,
            loader:'style-loader!css-loader!less-loader'
        },
        {
            test:/\.(png|woff|woff2|eot|ttf|svg)$/,
            exclude:/(node_modules)/,
            loader: 'url-loader?limit=100000'
        },
        {
            test:/\.(jpe?g|png|gif|svg)$/i,
            exclude:/(node_modules)/,
            loader: 'url?limit=10000!img?progressive=true'
        },
        {
            test:/\.html$/,
            exclude:/(node_modules)/,
            loader: 'html-loader'
        }
    ]
},
plugins: [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
]

};

And my entry point is index.webpack.js:

require('file?name=[name].[ext]!./index.html');
require('jQuery');
require('bootstrap');
require('file?name=[name].[ext]!./css/footer.css');
require('file?name=[name].[ext]!./css/header.css');
require('file?name=[name].[ext]!./css/styles.css');
require('file?name=[name].[ext]!./fonts/HelveticaRounded-Black.eot');
require('file?name=[name].[ext]!./fonts/HelveticaRounded-Black.svg');
require('file?name=[name].[ext]!./fonts/HelveticaRounded-Black.ttf');
require('file?name=[name].[ext]!./fonts/HelveticaRounded-Black.woff');
require('file?name=[name].[ext]!./img/butterfly.gif');
require('file?name=[name].[ext]!./img/dr photo.jpg');
require('file?name=[name].[ext]!./img/firefly.gif');
require('file?name=[name].[ext]!./img/footerspikes.gif');
require('file?name=[name].[ext]!./img/mainheaderimage.jpg');
require('file?name=[name].[ext]!./img/mushrooms.gif');
require('file?name=[name].[ext]!./img/teethkids.gif');
require('file?name=[name].[ext]!./img/titlebanner.gif');
require('file?name=[name].[ext]!./refs/footer.html');
require('file?name=[name].[ext]!./refs/header.html');
require('file?name=[name].[ext]!./refs/leftmargin.html');
require('file?name=[name].[ext]!./refs/rightmargin.html');

What do you think?

--edited after trying first answer--

my updated webpack.config.js:

var debug = process.env.NODE_ENV !== "production";

var webpack = require('webpack');
var path = require('path');
var htmlWebpackPlugin = require('html-webpack-plugin');
var commonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
var cleanWebpackPlugin = require('clean-webpack-plugin');

module.exports = {
    context: path.join(__dirname, 'src'),
    debug: true,
    entry: {
        entry: path.join(__dirname, 'src', 'index.webpack.js'),
        vendor: ['jquery', 'bootstrapjs']
    },
    resolve: {
        alias: {
            'jquery': path.join(__dirname, 'node_modules', 'jquery', 'dist', 'jquery.min.js'),
            'bootstrapjs': path.join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js', 'bootstrap.min.js')
        }
    },
    output: {
        path: path.join(__dirname, 'dist'),
        filename: "[name].[chunkhash].bundle.min.js"
    },
    module: {
        loaders: [
            {
                test:/\.js$/,
                exclude:/node_modules/,
                include:path.join(__dirname, 'src'),
                loader:'babel-loader',
            },
            {
                test:/\.css$/,
                include:path.join(__dirname, 'src'),
                loader:'style-loader!css-loader'
            },
            {
                test:/\.less$/,
                include:path.join(__dirname, 'src'),
                loader:'style-loader!css-loader!less-loader'
            },
            {
                test:/\.(png|woff|woff2|eot|ttf|svg)$/,
                include:path.join(__dirname, 'src'),
                loader: 'url-loader?limit=100000'
            },
            {
                test:/\.(jpe?g|png|gif|svg)$/i,
                include:path.join(__dirname, 'src'),
                loader: 'url-loader?limit=100000!img?progressive=true'
            },
            {
                test:/\.html$/,
                include:path.join(__dirname, 'src'),
                loader: 'html-loader'
            }
        ]
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        inline: true,
        stats: 'errors-only'
    },
    plugins: debug ? [
        new cleanWebpackPlugin(['dist']),
        new htmlWebpackPlugin({
            template: path.join(__dirname, 'src', 'pages', 'index.html'),
            hash: true,
            chunks: 'commons'
        }),
        new webpack.ProvidePlugin({ 
            $: "jquery", 
            jQuery: "jquery",
            jquery: "jquery"
        }),
        new commonsChunkPlugin({
            name: ['commons', 'vendor', 'bootstrap']
        })
    ] : [
        new cleanWebpackPlugin(['dist']),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
        new htmlWebpackPlugin({
            template: path.join(__dirname, 'src', 'pages', 'index.html'),
            hash: true,
            chunks: 'commons'
        }),
        new webpack.ProvidePlugin({ 
            $: "jquery", 
            jQuery: "jquery",
            jquery: "jquery"
        }),
        new commonsChunkPlugin({
            name: ['commons', 'vendor', 'bootstrap']
        })
    ]
};

My index.webpack.js is now an empty file.

I'm basically still having the exact same problems as before only I'm using html-webpack-plugin instead of requiring all my files in the entry file.

$ is not defined even though I'm defining it with provideplugin.

bootstrap css isn't going through and it doesn't work when I put it in the vendors list.

any ideas?

回答1:

Since your starting out, now would be a good time to switch to Webpack 2 and https://webpack.js.org/ for the documentation, which is currently in beta and you can install it using the beta distribution tag via:

npm install webpack@beta --save

Great, now take a deep breath and let's try to get the next point through: you have to forget about serving your raw application sources and assets and always point your web server to the output directory (or simply use webpack-dev-server). Let me try to explain.

Webpack is a module bundler that agressive on optimization for distribution and almost all of it's features depend on module loaders. What module loaders do is they take your static references to your sources or assets and they produce a JS module. Oprah show: CSS sources get a JS module and PNGs get a JS module and MP3s get a JS module--everyone gets a module \o/. This might trip you up if you're used to simply authoring your sources, dropping in assets and pointing your web server to the root and statically referecing these from HTML, because it won't work with Webpack.

Using file-loader like this won't get you anywhere, because you're doing nothing with the output. Remember I said that everything gets a module and what file-loader produces is a module that exports a string to some asset that's in the output. So first thing you have to start doing is start taking those outputs and then inject them into the HTML to get the actual references.

You should consider using html-webpack-plugin to produce the necessary HTML template and require other assets as necessary in your JS sources.