简体   繁体   中英

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
        })
    ]
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM