【问题标题】:Resolve path for stylesheets in HTML-webpack-plugin解析 HTML-webpack-plugin 中样式表的路径
【发布时间】:2017-02-05 20:18:28
【问题描述】:

我正在使用html-webpack-plugin 即时生成index.html。它工作得很好。但是,问题是,我还使用extract-text-webpack-pluginjs 中提取css

html-webpack-plugin 的文档中所述

如果您在 webpack 的输出中有任何 CSS 资源(例如,使用 ExtractTextPlugin 提取的 CSS),那么这些资源将包含在 HTML 头部的标签中。

它添加了一个<link> 指向我的css。但是链接看起来像这样。

电流输出

<link rel="stylesheet" type="text/css" href="/js/../css/index.css" />

我需要这样解析网址

预期输出

<link rel="stylesheet" type="text/css" href="/css/index.css" />

我的 webpack 配置(仅限基本部分)

output: {
        path: path.resolve('./build/app/js'),
        filename: '[name].js',
        publicPath: '/js/',
    },
    plugins: [
      new ExtractTextPlugin(path.normalize('../css/index.css')),
      new HTMLwebpackPlugin({
        filename: '../index.html',
        template: './app/views/index.ejs',
        hash: true,
      }),
]

build 的文件夹结构是这样的

|--js
|  |-main.js
|
--css
|  |-index.css
|
|--fonts
|
|--img
|
index.html

插件的所有输出目的地都将与 webpack 的 output 配置中给出的 path 相关

【问题讨论】:

    标签: javascript html css webpack html-webpack-plugin


    【解决方案1】:

    当前输出 /js/../css/index.css 是由 publicPath /js/ 和提取 url ../css/index.css 引起的。

    所以,如果你想解决它,只需这样做:

    1. 将 publicPath 更改为 /。(我建议您将 publicPath 设置为您的应用开发根 url)。

    2. new ExtractTextPlugin(path.normalize('../css/index.css')) 更改为new ExtractTextPlugin(path.normalize('css/index.css'))

    3. HTMLwebpackPlugin -> filename 也应该更改

    【讨论】:

    • 这将解决 css 问题。但是 js 呢?在这之后会搞砸的,
    • 是的!这是一个解决方案。
    【解决方案2】:

    这是一个完整的演示版!

    我的webpack.config.js

    'use strict';
    
    /**
     * @Created by xgqfrms on 2016/1/26.
     * @version 1.0.0 created
     * @description Using Next Generation Vanilla JS & JS Modules today with Webpack 3 & Babel!
     *
     * @license MIT
     * @copyright xgqfrms 2016-forever || 2018-present
     * @update 2018.1.29
     *
     */
    
    // import { export } from "module-name";
    
    /* "module": "webpack.config.mjs", ??? */
    // import path from "path";
    // import webpack from "webpack";
    // import UglifyJSPlugin from "uglifyjs-webpack-plugin";
    // import HtmlWebpackPlugin from "html-webpack-plugin";
    
    
    const path = require('path');
    const webpack = require('webpack'); //to access built-in plugins
    const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
    const HtmlWebpackPlugin = require('html-webpack-plugin');// template
    const CleanWebpackPlugin = require('clean-webpack-plugin');
    const ExtractTextPlugin = require("extract-text-webpack-plugin");// extract css files
    
    // set process.env.NODE_ENV && npm run dev
    if (process.env.NODE_ENV !== 'production') {
        console.log('?, Looks like we are in development mode!');
    }else{
        console.log('Tada, ?, we are in production mode!');
    }
    
    // const extractSCSS = new ExtractTextPlugin('stylesheets/[name]-one.scss');
    const extractSCSS = new ExtractTextPlugin({
        filename: (getPath) => {
            // relative path
            return getPath('css/[name].[hash:16].css');
            // js/../css & bug ???
            // return getPath('../css/[name].css');
            // return getPath('../css/[name].[hash:16].css').replace('js/../css', './css');
            // return getPath('/css/[name].[hash:16].css').replace('/css', '/css');
            // return getPath('../css/[name].css').replace('js/css', 'css');// relative path
        },
        // allChunks: true,
    });
    const extractSASS = new ExtractTextPlugin('css/[name].css');
    
    const BASE_URI = {
        MODULES: './src/modules/',
        ES5: './src/es5/',
        APP: './src/index.js',
        NIM: './src/modules/no-import-module',
    };
    
    
    
    const MODULES_OBJ = [
        "module01",
        "module02",
        // "module03",
    ];
    
    let entry_obj = {};
    MODULES_OBJ.forEach(
        (item, i) => {
            entry_obj[item] = `${BASE_URI.MODULES}/${item}`;
        }
    );
    
    entry_obj["index"] = `${BASE_URI.APP}`;
    entry_obj["no-import-module"] = `${BASE_URI.NIM}`;
    
    
    module.exports = {
        entry: Object.assign({}, entry_obj),
        output: {
            path: path.resolve(__dirname, "build/"),
            // path: path.resolve(__dirname, "build/js/"),
            // filename: '[name].min.js',
            filename: 'js/[name].[hash:16].min.js',// hash version
            // [hash] & [chunkhash] can using [hash:16] (default 20)。
            // filename: "[chunkhash].bundle.js",
            // publicPath: '/'
            // pathinfo: true,
            // sourceMapFilename:  [name], [id], [hash] & [chunkhash], // default "[file].map"。
        },
        resolve: {
            // auto resolve files's extensions
            extensions: ['.js', '.jsx','.scss', '.sass', '.css'],
        },
        module: {
            // loaders
            rules: [
                {
                    test: /\.js$/,
                    // test: /\.(js|jsx)$/,
                    exclude: /node_modules/,
                    // exclude: /(node_modules|bower_components)/,
                    // loader: "babel-loader",
                    // options: {
                    //     presets: ['env'],
                    // },
                    // use: 'babel-loader',
                    use: [
                        {
                            loader: "babel-loader",
                            options: {
                                presets: ['env'],
                            },
                        }
                    ],
                },
                {
                    // test: /\.scss$/,
                    test: /\.(scss|sass)$/,
                    // test: /\.(css|scss|sass)$/,
                    use: ExtractTextPlugin.extract({
                        fallback: "style-loader",
                        use: [
                            {
                                loader: 'css-loader',
                                options: {
                                    url: false,
                                    minimize: true,
                                    sourceMap: true,
                                    modules: true,
                                    localIdentName: '[path][name]__[local]--[hash:base64:5]',
                                    // camelCase: true,
                                    // importLoaders: 1,
                                    // // 0 => none loader(default); 1 => postcss-loader; 2 => postcss-loader, sass-loader
                                    // alias: {
                                    //     "../fonts/bootstrap": "bootstrap-sass/assets/fonts/bootstrap"
                                    // },
                                }
                            }, 
                            {
                                loader: 'sass-loader',
                                options: {
                                    sourceMap: true,
                                    // includePaths: [
                                    //     path.resolve("./node_modules/bootstrap-sass/assets/stylesheets")
                                    // ],
                                }
                            }
                        ],
                        // allChunks: true,
                        publicPath: "./dist",
                    })
                },
                {
                    test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                    loader: 'url-loader',
                    options: {
                        limit: 10000
                    }
                },
            ],
        },
        devtool: 'source-map',
        plugins: [
            new UglifyJSPlugin({
                sourceMap: true,
                extractComments: true,// {Boolean|RegExp|Function<(node, comment) -> {Boolean|Object}>}
                // test: /\.js$/i,// test: /\.js($&#124;\?)/i
                // include: /\/includes/,
                // exclude: /\/excludes/,
                // parallel: true,
                // parallel: {
                //     cache: true,
                //     workers: 2, // for e.g
                // },
                // uglifyOptions: {
                //     ie8: true,// ie8: false,
                //     ecma: 5,//ecma: 8,
                //     parse: {...options},
                //     mangle: {
                //         ...options,
                //         properties: {
                //             // mangle property options
                //         }
                //     },
                //     output: {
                //         comments: false,
                //         beautify: false,
                //         ...options
                //     },
                //     compress: {...options},
                //     warnings: false
                // },
                // warningsFilter: (src) => true
            }),
            extractSCSS,
            extractSASS,
            new HtmlWebpackPlugin({
                title: 'using ES6 today with webpack3 & babel!',
                // filename: '../index.html',// relative path
                filename: './index.html',
                template: './src/index.html',
                // favicon: "",
                minify: {
                    // https://github.com/kangax/html-minifier#options-quick-reference
                    minifyCSS: true,
                    minifyJS: true,
                    html5: true,
                    collapseWhitespace: true,
                    removeComments: true,
                    removeEmptyAttributes: true,
                    removeEmptyElements: true,
                    quoteCharacter: true,
                    // useShortDoctype: true,
                    // removeTagWhitespace: true,
                },
                hash: true,// all files & path hash
            }),
            // new CleanWebpackPlugin(['build']),// rm-rf
        ],
    };

    【讨论】:

      猜你喜欢
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      • 2017-12-15
      • 2015-02-14
      相关资源
      最近更新 更多