Webpack构建文件在html页面加载上不起作用

tct7dpnv  于 2022-11-13  发布在  Webpack
关注(0)|答案(2)|浏览(345)

我在Webpack中做了一个简单的任务来捆绑我所有的JS文件。控制台日志显示文件创建成功,但加载html页面时它不工作。
下面是代码:

const path =  require('path');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  
  entry:[
    '/src/assets/js/libraries/aos.js',
    '/src/assets/js/libraries/jquery.mask.js',
    '/src/assets/js/libraries/slick.js',
    '/src/assets/js/scripts/email.js',
    '/src/assets/js/scripts/google-analytics.js',
    '/src/assets/js/scripts/modernizr-3.11.2.min.js',
    '/src/assets/js/scripts/scripts.js',
  ],

  output: {
    path: path.resolve(__dirname, './public/core/assets/js'),
    filename: 'bundle.js'
  },

  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin()],
  },

  module: {
    rules: [
        {
            test: /\.js$/,
            exclude: /(node_modules)/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env']
                }
            }
        }],
      },

  watch: true,
  mode: 'production'
}

这是控制台显示的内容(一切似乎都编译得很好):

$ npm run build

> project@1.0.0 build
> webpack --config webpack.config.js

asset bundle.js 161 KiB [emitted] [minimized] (name: main) 1 related asset
runtime modules 123 bytes 1 module
modules by path ./src/assets/js/ 126 KiB
  modules by path ./src/assets/js/scripts/*.js 13.5 KiB
    ./src/assets/js/scripts/email.js 393 bytes [built] [code generated]
    ./src/assets/js/scripts/google-analytics.js 209 bytes [built] [code generated]
    ./src/assets/js/scripts/modernizr-3.11.2.min.js 11.7 KiB [built] [code generated]
    ./src/assets/js/scripts/scripts.js 1.22 KiB [built] [code generated]
  modules by path ./src/assets/js/libraries/*.js 113 KiB
    ./src/assets/js/libraries/aos.js 21 KiB [built] [code generated]
    ./src/assets/js/libraries/jquery.mask.js 19.5 KiB [built] [code generated]
    ./src/assets/js/libraries/slick.js 72.2 KiB [built] [code generated]
./node_modules/jquery/dist/jquery.js 283 KiB [built] [code generated]
webpack 5.74.0 compiled successfully in 3199 ms

屁股你可以看到这是一个非常基本的任务。
我的html页面的所有路径都是正确的(我在没有Webpack的情况下进行了测试),但是当我捆绑Webpack时就不工作了。

z31licg0

z31licg01#

请使用publicPath选项尝试

output: {
    path: path.resolve(__dirname, './public/core/assets/js'),
    filename: 'bundle.js',
    publicPath: '/'
  },
k10s72fa

k10s72fa2#

HtmlWebpack插件

您正在正确地导入所有的.js文件,webpack只是不知道这一点。当您与webpack捆绑时,您需要使用脚本标记将.js文件自动插入到html中。因此,当您运行output.html文件时,模块将自动加载,您不必在构建. See HtmlWebpackPlugin之前手动插入到.html文件中。

装载机

当你用webpack导入html和图像以及其他文件时,加载器就派上用场了。

  1. HTML Loader(用于解析html)
  2. CSS loader(如果您有样式表)
    1.文件加载器(用于图像和其他类似文件)

相关问题