How to require/import .less file in typescript file

梦想与她 提交于 2019-12-23 15:50:49

问题


I am trying to import a .less file in .ts file but I am not able to do that. I am using webpack2 as bundler & webstorm IDE

Here snippet for less loader in a webpack.config.js file

{
  test: /\.less$/,      //less loader
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    //loader: 'css-loader!less-loader'
    loader: 'raw-loader!less-loader'
  })
}, {
  test: /\.ts$/,    //typescript loader
  //include: path.resolve(__dirname, "ts-src"),
  include: path.resolve(__dirname, "js"),
  loader: "ts-loader"
}
//rest of code
resolve: {
  extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".css", ".less"],
}

As mentioned in link I tried by creating a global.d.ts file but no luck

Also i tried to require the file in the main.ts but in this case I am not seeing any option to requires a less file. My question is how to load a .less file in a typescript files

[


回答1:


Though I could not find out how to include .less in ts files but I found an way around by creating a javascript file and importing less in it

import.js

import "./../styles/main.less";

Have created a config file to resolve the paths to be used in CommonsChunkPlugin

entryConfig.js

module.exports={
    // rest of code
    style:'./js/import.js'
}

In webpack.config.js

entry: {
  //rest of code
  style: entryConfig.style
},

//rest of code

new webpack.optimize.CommonsChunkPlugin({
    name: 'common',
    filename: 'common-[hash].js',
    chunk: ['common', 'home','style']
})

where string style is same as the key name in entry object




回答2:


If your style.less file is in root of project, src folder you can use it as follows.

import "style.less";

webpack.config.js should have properly configured style-loader and less-loader as mentioned in here I have it like this:

module: {
   rules: [
      ...
      { test: /\.less$/i, use: ['style-loader', 'css-loader', 'less-loader'], issuer: /\.[tj]s$/i},
      { test: /\.less$/i, use: ['css-loader', 'less-loader'], issuer: /\.html?$/i },
   ]
}

I have two, one for imports in ts/js files, the other one is for require in html templates

<require from="style.less"></require>


来源:https://stackoverflow.com/questions/44064890/how-to-require-import-less-file-in-typescript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!