首页 > 解决方案 > 如何配置 webpack 自动检测 .css 文件的变化,以及导出内部 bundle.js 功能

问题描述

我使用 webpack 来编译代码。
我有以下要求:

我可以单独实现每个要求,但不能一起实现。
什么应该同时达到这些要求?

谢谢


要求1的设置:
为了实现要求1,我按照此处
的说明进行了 此设置:

webpack 配置文件:

cat ~/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webpack/webpack.config.js
...
module.exports = {
    context: path.resolve('js/dir1/'),

    // option1 - webback detects changes in the .css file, 
    //           but an internal bundle.js function can be called from the outside via e.g. lib1.func1()
    entry:{
        index: [
            './main.js',
            "../../css/style.css"
        ]
    },

    output: {
        path: path.resolve('build/lib'),
        publicPath: 'build',
        filename: 'bundle.js',
        library: "lib1",
        libraryTarget: "umd",
    },
...

要求 2 的设置:
为了达到要求 2,我按照此处的说明进行操作

使用此设置:

webpack 配置文件:

cat ~/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webpack/webpack.config.js
...
module.exports = {
    context: path.resolve('js/dir1/'),

    // option2 - webback does not detect changes in the .css file
    //           but an internal bundle.js function can be called from the outside via e.g. lib1.func1()
    entry: './main.js',

    output: {
        path: path.resolve('build/lib'),
        publicPath: 'build',
        filename: 'bundle.js',
        library: "lib1",
        libraryTarget: "umd",
    },
...

标签: webpack

解决方案


我按照教程创建了多个条目(它创建了一个未使用的捆绑文件css.bundle.js:)

通过以下设置(选项3),我可以同时实现这两个要求。
(注意entry, 和output.filename字段的更改)。

cat ~/avner/constructionOverlay/code/meshlabjs/branches/meshlabjs_avnerV1/webpack/webpack.config.js
...
module.exports = {
    context: path.resolve('js/dir1/'),


    // option3 - webback detects changes in the .css file, and
    //           an internal bundle.js function can be called from the outside via e.g. lib1.func1()
    entry: {
        app: './main.js',
        css: "../../css/style.css"
    },
    
    output: {
        // the output file bundle.js is placed in the path "build/dir1/"
        path: path.resolve('build/dir1'),
        publicPath: 'build',
        filename: "./[name].bundle.js" ,
        library: "lib1",
        libraryTarget: "umd",
    },

推荐阅读