Jhon Caylog
Jhon Caylog

Reputation: 503

How to bundle javascript files/Jquery Files using webpack?

I was able to succeffully bundles my sass files using webpack but i am having trouble packing my javascript files. The way i do it on css is that the entry point is ./public/javascript/index.js which contains import '../sass/main.scss'; and then main.scss contains like @import "layout/header"; and a lot more. The question is that how would i pack javascript files ?

for example i have my javascript files on \public\js\ -- > js files here like test.js and etc.

I have provided my webpack config below.

My webpack config

const javascript = {
    test: /\.(js)$/,
    use: {
        loader: 'babel-loader',
        options: {
            presets: ['@babel/env']
        }
    }
}

const images = {
    test: /\.(jpg|jpeg|png|gif)$/,
    use: {
        loader: 'file-loader',
        options: {
            outputPath: '../images/'
        }
    }
}

const postcss = {
    loader: 'postcss-loader',
    options: {
        plugins() { return [ autoprefixer({ browsers: 'last 5 versions' }) ]; }
    }
}

const styles = {
    test: /\.scss$/,
    use: [
        'style-loader',
        MiniCssExtractPlugin.loader,
        'css-loader',
        postcss,
        'sass-loader'
    ]
}

const config = {
    watch: true,
    watchOptions: {
        poll: true,
        ignored: /node_modules/
    },
    entry: './public/javascript/index.js',
    output: {
        path: path.resolve(__dirname, 'public', 'dist'),
        filename: 'main.js'
    },
    module: {
        rules: [
            javascript,
            images,
            styles
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style.bundle.css'
        }),
        new OptimizeCssAssetsPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano'),
            cssProcessorOptions: { preset: 'default', discardComments: { removeAll: true } },
            canPrint: true
        })
    ]
}

Upvotes: 1

Views: 1410

Answers (1)

foobar2k19
foobar2k19

Reputation: 84

Webpack is, by simplest explanation, a javascript bundler. There are plugins to support other assets like css, but the webpack hello world will bundle your javascript for you.

By defining an entry point, you're asking webpack to traverse the module dependency tree you've created with import/require statements, and bundle the scripts it finds along the way into a single output file.

If you were to create a file in ./public/javascript named "foo.js" and add an import "./foo"; in your index.js file, you'd see that after running your webpack build, any code you add to foo.js will appear in your main.js

Upvotes: 2

Related Questions