【问题标题】:Bundling CSS and JS using webpack with one config通过一个配置使用 webpack 捆绑 CSS 和 JS
【发布时间】:2017-07-12 21:01:52
【问题描述】:

我正在尝试了解 webpack 的工作原理。我正在开发一个 Wordpress 主题,我决定尝试一下 Webpack。

我正在为 Webpack 的配置而苦苦挣扎。配置它来处理 SASS 相当容易,但是当要添加对应该捆绑到一个 JS 文件中的 JS 文件的支持时:scripts.js,然后就很难理解它是如何工作的了。

这是我的配置:

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
    devtool: 'source-map',
    watch: true,
    entry: ['./scss/style.scss'],
    output: {
        filename: './style.css',
        publicPath: '/'
    },
    module: {
        rules: [{
            test: /\.scss$/,
            exclude: /node_modules/,
            loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
        }]
    },
    plugins: [
        new ExtractTextPlugin({ // define where to save the file
            filename: './style.css',
            allChunks: true
        }),
        new UglifyJSPlugin({
            sourceMap: true
        })
    ]
};

我想知道 JS 文件的配置应该是什么样子的?

【问题讨论】:

  • 您的入口点应该是 javascript 文件,而不是 scss 文件。您可以在您的 javascript 文件中导入 scss 文件,以便 webpack 找到它们。也许建议阅读:blog.andrewray.me/webpack-when-to-use-and-why
  • @andy-ray 我认为 Webpack 是一种新方法,用于捆绑 Gulp 或 Grunt 之前所做的事情。我为每个插件添加配置的地方,我收到了我想要的。
  • Grunt 和 Gulp 仅适用于文件,没有依赖图的概念。 Webpack 为您提供所有静态资产的依赖关系图。在最常见的设置中,您需要 javascript 代码中的 scss 来告诉 Webpack 您的 javascript 应用程序需要某些 CSS 才能运行
  • 我明白了,但是 Wordpress 模板不是 JS 应用程序。它使用 PHP 代码。

标签: javascript wordpress webpack


【解决方案1】:

替换 webpack 选项:

entry: ['./scss/style.scss'],
output: {
    filename: './style.css',
    publicPath: '/'
},

entry: ['./js/index.js'],
output: {
    filename: './bundle.js',
    publicPath: '/'
},

./js/index.js的内容:

require('./scss/style.scss')

style.css bundle 的输出路径已经在你的 webpack 配置中的 ExtractTextPlugin 选项中指定。像您通常在 html 文件中一样包含 css 包。

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 2019-10-19
    • 2018-04-02
    • 2020-01-10
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多