微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

webpack.config.js 没有设置全局变量

如何解决webpack.config.js 没有设置全局变量

知道为什么这个 webpack.config.js 没有设置全局 LESS 变量:current-vehicle 定义于:/resources/scripts/theme.js

/webpack.config.js

const merge = require("webpack-merge");
const path = require("path");
const baseConfig = require("laravel-mix/setup/webpack.config");

require('dotenv').config();

/**
 * Update the output directory and chunk filenames to work as expected.
 *
 * @param {object} config - The webpack config
 *
 * @return {object} The updated webpack config
 */
const addOutputConfiguration = config => {
  const publicPath = process.env.CDN_URL + '/js/';
  return merge(config,{
    output: {
      path: path.resolve(__dirname,"public/cdn/js"),publicPath,chunkFilename: "[name].js"
    },module: {
      loaders: [
        {
          loader: 'less-loader',options: {
            modifyVars: require("./resources/scripts/theme")
          }
        },],},});
};

module.exports = addOutputConfiguration(baseConfig);

这里有完整的存储库:https://github.com/tlg-265/issue-import-less.local

设置

$ git clone https://github.com/tlg-265/issue-import-less.local
$ cd issue-import-less.local
$ npm i
$ npm run watch

Then open with the browser (you do NOT need a server).

LESS 变量:current-vehicle 在此处读取:

https://github.com/tlg-265/issue-import-less.local/blob/master/resources/assets/js/components/controls/ModalWindow/ModalWindow.less#L1

当您执行:$ npm run watch 时,您会收到错误Variable @current-vehicle is undefined,如下面的屏幕截图所示:

enter image description here

理想情况下,当您运行它时,您应该在浏览器上看到以下内容

enter image description here

当点击链接时,你应该得到:

enter image description here

但不幸的是我还没有到达那里。

知道如何让它发挥作用吗?

提前致谢!

解决方法

你的这部分配置让我震惊:

    module: {
      loaders: [ // <==== !!!!!! here
        {
          loader: 'less-loader',options: {
            modifyVars: require("./resources/scripts/theme")
          }
        },],},

我记得 loaders 键是用于 Webpack 版本 1 或 2,在版本 3 之后他们强烈建议使用 rules,请将其更改为 rules 并尝试使用。不知道,可能是来自 Laravel webpack 的配置。

无论如何,在less-loader之后也请添加这个加载器:

{ 
  loader: 'text-transform-loader',options: {
    prependText: '@import "./resources/scripts/theme.less"',

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。