简体   繁体   English

Vue-CLI 3:如何在 webpack 包中包含 /src 目录外部的 LESS 文件?

[英]Vue-CLI 3: How to include LESS files from outside of /src directory in webpack bundle?

I'm looking for a way to include.less files that live outside of the /src directory of my Vue-Cli project into my webpack bundle.我正在寻找一种方法,将位于我的 Vue-Cli 项目的 /src 目录之外的文件包含到我的 webpack 包中。 Need these.less files to only be included in 'development' mode .需要这些.less 文件只包含在“开发”模式中。

When built in a Production environment, we'll need to link to external folder for styles which looks like: /assets/styles/main.css在生产环境中构建时,我们需要链接到 styles 的外部文件夹,如下所示: /assets/styles/main.css

Directory Structure:目录结构:

Vue-Project
|-- /Styles
|   `-- app
|       `-- styles
|           |-- main.less
|           `-- atoms/modules/etc
|               `-- *.less
|-- /src
`-- vue.config.js

Should I be Chaining WebPack or Updating Loader Options ?我应该链接 WebPack还是更新加载程序选项

vue.config.js: vue.config.js:

module.exports = {
  lintOnSave: false,

  configureWebpack: config => {
    if (process.env.NODE_ENV === "production") {
      // mutate config for production...
    } else {
      // mutate for development...

      // CONFIG LESS FILES HERE?

    }
  }
};

Tried the following, but didn't work:尝试了以下,但没有奏效:

css: {
    loaderOptions: {
      less: {
        data: `@import "@/styles/main.less";`
        // @imported .less files from Styles/app/styles/main.less etc into src/styles/main.less
      }
    }
  }

Any guidance on this is much appreciated.非常感谢对此的任何指导。

You first need to install these packages, less-loader will be required to convert the .less files into .css files.您首先需要安装这些包,需要 less-loader 将.less文件转换为.css文件。

npm install concurrently less less-loader less-watch-compiler --save-dev

Secondly, add less-watcher.config.json file in your root folder and place the following code in it.其次,在您的根文件夹中添加less-watcher.config.json文件,并将以下代码放入其中。

{
    "watchFolder": "Styles/",
    "outputFolder": "Styles/",
    "sourceMap": true,
    "runOnce": false,
    "enableJs": true
  }

Note that watchFolder should be the folder where all your .less files are loacated, and outputFolder is the folder where generated .css files will be placed.请注意, watchFolder应该是所有.less文件所在的文件夹, outputFolder是生成的.css文件所在的文件夹。

Now in your packages.json file add this code inside scripts object现在在您的packages.json文件中,在脚本object 中添加此代码

"start": "concurrently --kill-others \"less-watch-compiler --config less-watcher.config.json\" \"webpack-dev-server --open --mode development\""

This will ensure that whenever your run npm start it will regenerate the .css files before running the project.这将确保无论何时开始运行 npm,它都会在运行项目之前重新生成.css文件。

Finally in your index.js file import the .css file最后在你的index.js文件中导入.css文件

import "../Styles/app/main.css";

Your folder/files structure您的文件夹/文件结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM