or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# to-string-loader

1

2

to-string-loader is a webpack loader that converts the output of other loaders (such as CSS and SASS loaders) into string format. It addresses the specific use case where webpack's default output format needs to be converted to a plain string, particularly useful for framework integrations like Angular2 style definitions.

3

4

## Package Information

5

6

- **Package Name**: to-string-loader

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install to-string-loader`

10

- **Dependencies**: loader-utils ^1.0.0

11

12

## Core Imports

13

14

The loader is not imported directly. Instead, it's configured in webpack's loader chain:

15

16

```javascript

17

// webpack.config.js

18

module.exports = {

19

module: {

20

rules: [

21

{

22

test: /\.scss$/,

23

loaders: ['to-string-loader', 'css-loader', 'sass-loader']

24

}

25

]

26

}

27

};

28

```

29

30

## Basic Usage

31

32

### Webpack Configuration

33

34

Configure the loader in your webpack configuration to ensure CSS/SASS output is converted to strings:

35

36

```javascript

37

// webpack.config.js

38

module.exports = {

39

module: {

40

rules: [

41

{

42

test: /\.scss$/,

43

use: [

44

'to-string-loader',

45

'css-loader',

46

'sass-loader'

47

]

48

},

49

{

50

test: /\.css$/,

51

use: [

52

'to-string-loader',

53

'css-loader'

54

]

55

}

56

]

57

}

58

};

59

```

60

61

### Usage in Code

62

63

Once configured, require statements will return strings instead of webpack's default array objects:

64

65

```javascript

66

// Without to-string-loader, this returns an array object with toString() method

67

// With to-string-loader, this returns a plain string

68

const styles = require('./styles.scss');

69

console.log(typeof styles); // "string"

70

71

// Common use case: Angular2 component styles

72

@Component({

73

selector: 'my-component',

74

template: require('./template.html'),

75

styles: [

76

require('./styles.scss') // Returns string directly, no .toString() needed

77

]

78

})

79

export class MyComponent {}

80

```

81

82

## Architecture

83

84

to-string-loader operates as a webpack pitching loader that intercepts the compilation chain:

85

86

- **Pitching Phase**: Executes before the normal loader chain, intercepting requests

87

- **String Conversion**: Generates code that ensures final output is always a string

88

- **ES Module Handling**: Automatically handles ES module default exports

89

- **Caching**: Supports webpack's caching mechanism when available

90

91

## Capabilities

92

93

### Webpack Loader Function

94

95

The main loader function (currently a placeholder in this implementation).

96

97

```javascript { .api }

98

/**

99

* Main webpack loader function

100

* @returns {void} Currently empty placeholder

101

*/

102

module.exports = function() {}

103

```

104

105

### Pitching Loader Function

106

107

The core functionality that converts loader chain output to strings.

108

109

```javascript { .api }

110

/**

111

* Webpack pitching loader that converts output to string format

112

* @param {string} remainingRequest - The remaining request string from webpack

113

* @returns {string} Generated JavaScript code that ensures string output

114

*/

115

module.exports.pitch = function(remainingRequest) {}

116

```

117

118

**Behavior:**

119

- Sets `this.cacheable()` if available for webpack caching

120

- Uses `loaderUtils.stringifyRequest()` to safely handle the request string

121

- Generates code that requires the remaining loader chain with `!!` prefix

122

- Handles ES module interop by extracting `default` export when `__esModule` is true

123

- Converts result to string using `toString()` if not already a string

124

- Exports the final string result

125

126

### Generated Output Code

127

128

The loader generates JavaScript code with the following pattern:

129

130

```javascript

131

var result = require(/* processed remaining request */);

132

133

if (result && result.__esModule) {

134

result = result.default;

135

}

136

137

if (typeof result === "string") {

138

module.exports = result;

139

} else {

140

module.exports = result.toString();

141

}

142

```

143

144

## Webpack Context Properties

145

146

The loader uses standard webpack loader context properties. The pitching loader function receives the webpack loader context as `this`:

147

148

```javascript { .api }

149

/**

150

* Webpack loader context properties used by to-string-loader

151

* Available as 'this' within the pitch function

152

*/

153

interface LoaderContext {

154

/** Optional function to mark loader as cacheable for improved build performance */

155

cacheable?: () => void;

156

/** Resource path being processed */

157

resourcePath: string;

158

/** Request string for the current resource */

159

request: string;

160

/** Previous loaders in the chain */

161

previousRequest: string;

162

/** Current loader index in the chain */

163

loaderIndex: number;

164

}

165

```

166

167

## Dependencies

168

169

### loader-utils

170

171

External dependency providing webpack loader utilities. This package is used to safely process webpack request strings.

172

173

```javascript { .api }

174

/**

175

* loader-utils module for webpack request string processing

176

* Import: const loaderUtils = require("loader-utils");

177

*/

178

const loaderUtils = {

179

/**

180

* Safely stringify a webpack request string for code generation

181

* Escapes the request string to be safely embedded in generated JavaScript

182

* @param {LoaderContext} context - Webpack loader context object

183

* @param {string} request - Request string to stringify (e.g., "!!css-loader!sass-loader!./file.scss")

184

* @returns {string} Safely stringified request that can be used in require() calls

185

*/

186

stringifyRequest(context: LoaderContext, request: string): string;

187

};

188

```

189

190

**Usage in to-string-loader:**

191

- Used to safely stringify the `remainingRequest` parameter with `!!` prefix

192

- The `!!` prefix bypasses all loaders except those explicitly specified

193

- Ensures proper escaping for generated require() statements

194

195

## Error Handling

196

197

The to-string-loader implementation does not include explicit error handling:

198

199

- **Loader Chain Errors**: If errors occur in the remaining loader chain, they will propagate naturally through webpack's error handling

200

- **Runtime Errors**: The generated code includes safe type checking (`typeof result === "string"`) before calling `toString()`

201

- **Dependency Errors**: Missing or invalid loader-utils dependency will cause runtime errors during webpack compilation

202

- **Context Errors**: If `this.cacheable` is called when not available, it will fail silently (conditional check: `if (this.cacheable)`)

203

204

**Error Sources:**

205

- Invalid remaining request strings (handled by loader-utils)

206

- Loader chain failures (passed through webpack)

207

- Missing dependencies (webpack/Node.js runtime errors)

208

209

## Use Cases

210

211

### CSS/SASS String Output

212

213

Convert CSS/SASS loader output to plain strings:

214

215

```javascript

216

// Before: require('./styles.scss') returns array object

217

// After: require('./styles.scss') returns plain string

218

const cssString = require('./styles.scss');

219

```

220

221

### Framework Integration

222

223

Enable framework integrations that expect string styles:

224

225

```javascript

226

// Angular2 component example

227

@Component({

228

styles: [

229

require('./component.scss') // Now returns string directly

230

]

231

})

232

233

// React styled-components example

234

const StyledComponent = styled.div`

235

${require('./base-styles.css')} // String output

236

`;

237

```

238

239

### Dynamic Style Injection

240

241

Inject styles as strings into DOM:

242

243

```javascript

244

const styles = require('./dynamic-styles.css');

245

const styleElement = document.createElement('style');

246

styleElement.textContent = styles; // Works directly as string

247

document.head.appendChild(styleElement);

248

```

249

250

## Platform Requirements

251

252

- **Environment**: Node.js (webpack compilation environment)

253

- **Webpack Compatibility**: Works with webpack loader specification

254

- **Loader Chain Position**: Must be the first loader in the chain (rightmost in array)

255

- **Dependencies**: Requires loader-utils ^1.0.0