简体   繁体   中英

In Webpack, how to get multiple outputs with a single entry main.js(having multiple css files inside files)?

My directory structure should be like.

|-src/
|   |-styles/ (less)
|   |   |-xx.less(input inside main.js)
|   |   |-yy.less(input inside main.js)
|   |   |-zz.less(input inside main.js)
|
|-dist/  
    |-assets/
    |   |-xx.css(output should be like this)
    |   |-yy.css(output should be like this)
    |   |-zz.css(output should be like this)

and my main.js file contains,

require('./styles/xx.less');
require('./styles/yy.less');
require('./styles/zz.less');

and my entry point is

entry: {
    app: './main.js'
  },

1. How can I get output as chunks(xx.css,yy.css,zz.css)? 2. Tried extractTextPlugin there I was able to get output in the name of app.css but not as I wanted. Which plugin I can try to extract output as in same name and number of input I have in main.js file?

You can separate your css requires into files and in the entry point to them. for example:

xx.less.js

require('./styles/xx.less');

and in webpack entry:

app: [path.join(__dirname, 'path/to/xx.less.js')]

and call webpack several times using node script or something

More elaborate answer:

every entry in the webpack config represent the bundled file that will be created, the entry point to the start point js file and every css file will be created according to the reference of the css in that js file.

So if you want several css files you need several entries in your webpack config and every js in the entry will require its less file and in that way you will get 3 js file and 3 css files so your config should look something like this:

{
        entry: {
            xx: [ path.resolve(__dirname, 'path/to/js/xx.js')],
            yy: [ path.resolve(__dirname, 'path/to/js/yy.js')],
            zz: [ path.resolve(__dirname, 'path/to/js/zz.js')]
        },

        output: {
            path: path.resolve(__dirname, 'dist/assets'),
            filename: '[name].js' //the placeholder name will be replace by the entry name (xx,yy,zz)
        }

        ...

        plugins: [
            new ExtractTextPlugin({
                filename: '[name].css' //this is the name of the css according to the entry in the js file
            })
}

Your less loader should stay the same and just point to the src/styles where all the less files are and in your javascript files (xx.js,yy.js,zz.js) you should require the corresponding less file

in xx.js you call xx.less: require('./styles/xx.less');

in yy.js you call yy.less: require('./styles/yy.less');

in zz.js you call zz.less: require('./styles/zz.less');

And when you run webpack he will 3 css files (and 3 js files...)

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