Champer Wu
Champer Wu

Reputation: 1271

Is that possible to import css file as string in es6?

I want to pack the css file and insert it into shadow DOM in my app.

I have tried the way from css-loader:

As following the file :webpack.config.js

const path = require('path');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const VueLoaderPlugin = require('vue-loader/lib/plugin')


module.exports = {
    context: path.resolve(__dirname, 'src'),
    entry: {
      content: './content/index.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
    },
    module: {
        rules: [
            {
                use: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/
            },
            {
              test: /\.vue$/,
              loader: 'vue-loader'
            },
            {
              test: /\.css$/,
              use: [
                'vue-style-loader',
                'to-string-loader',
                {
                  loader: 'css-loader',
                  options: {}
                }
              ]
            }
        ]
    }
}

I tried to use the way like this:

const css = require('./test.css').toString();

console.log(css); // [Object, Object]

import styles from './test.css';
console.log(styles) // {}

CSS file:

#app{
  position: fixed;
  right: 0;
  top:0;
  width: 420px;
  height: 420px;
  z-index: 9999;
}

It seem not to work for me.

Is there having a way to do it?

Upvotes: 6

Views: 3391

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30380

From your webpack.config.js, it seems that the order you've specifeid the loaders for .css files is back to front.

Try revervsing the order of loaders in the use array so that the results of the css-loader are passed to the to-string-loader, and then from the to-string-loader to your script:

{
    test: /\.css$/,
    use: [
        'to-string-loader',
        'css-loader'
    ]
}

Also, I'm not sure you need to include vue-style-loader here, which is why I've removed that from the loaders applied to css files.

Upvotes: 5

Related Questions